cli-barcode PHP
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

390 rader
11 KiB

  1. #!/usr/bin/env php
  2. <?php
  3. ##########################################################################
  4. # Gustavo Arnosti Neves - 2016 Jul 11
  5. # guneves < a t > gmail < d o t > com
  6. #
  7. # PHP cli-barcode-generator
  8. #
  9. # Most of the work here is for option / argument parsing.
  10. # Picqer's barcode framework makes it east on the bar coding generation.
  11. # While ulrichsg's getopt-php helps with the cli part.
  12. #
  13. ##########################################################################
  14. require_once 'vendor/autoload.php';
  15. define("_BC_VERSION", "1.0.8");
  16. # default padding for cli messages
  17. define("_BC_PADDING", 30);
  18. define("_BC_HELP_NEWLINE", "\n ");
  19. $verbose = false;
  20. $quiet = false;
  21. $encoding = null;
  22. $format = null;
  23. $bc_string = null;
  24. $bc_file = null;
  25. $width = 2;
  26. $height = 30;
  27. $color = '#000000';
  28. #$_defPermission = $false; # to be implemented
  29. #$_defGroup = $false; # to be implemented
  30. $encodings_list = array(
  31. 'CODE_39',
  32. 'CODE_39_CHECKSUM',
  33. 'CODE_39E',
  34. 'CODE_39E_CHECKSUM',
  35. 'CODE_93',
  36. 'STANDARD_2_5',
  37. 'STANDARD_2_5_CHECKSUM',
  38. 'INTERLEAVED_2_5',
  39. 'INTERLEAVED_2_5_CHECKSUM',
  40. 'CODE_128',
  41. 'CODE_128_A',
  42. 'CODE_128_B',
  43. 'CODE_128_C',
  44. 'EAN_2',
  45. 'EAN_5',
  46. 'EAN_8',
  47. 'EAN_13',
  48. 'UPC_A',
  49. 'UPC_E',
  50. 'MSI',
  51. 'MSI_CHECKSUM',
  52. 'POSTNET',
  53. 'PLANET',
  54. 'RMS4CC',
  55. 'KIX',
  56. 'IMB',
  57. 'CODABAR',
  58. 'CODE_11',
  59. 'PHARMA_CODE',
  60. 'PHARMA_CODE_TWO_TRACKS'
  61. );
  62. sort($encodings_list);
  63. $formats_list = array(
  64. 'SVG',
  65. 'PNG',
  66. 'JPG',
  67. 'HTML'
  68. );
  69. sort($formats_list);
  70. # Converts Hex Color to array(r, g, b, [a])
  71. function hexToRgb($hex) {
  72. $hex = str_replace('#', '', $hex);
  73. $length = strlen($hex);
  74. $rgb[] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
  75. $rgb[] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
  76. $rgb[] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
  77. return $rgb;
  78. }
  79. /////////////////// PRINT HELP
  80. function getVersionString($suffix='') {
  81. return "PHP-CLI Barcode v"._BC_VERSION.$suffix;
  82. }
  83. function printVersion($suffix='') {
  84. echo getVersionString($suffix)."\n";
  85. }
  86. // prints help information
  87. function print_help($getopt) {
  88. printVersion();
  89. global $encodings_list;
  90. global $formats_list;
  91. echo $getopt->getHelpText(_BC_PADDING);
  92. echo "\nRequired Options and Parameters:\n";
  93. echo " -e <encoding>\n";
  94. echo " -f <output format>\n";
  95. echo " <input string>\n";
  96. echo " <output file>\n";
  97. echo "\nOutput Formats:\n";
  98. foreach($formats_list as $for) {
  99. echo " $for\n";
  100. }
  101. echo "\nEncodings:\n";
  102. foreach($encodings_list as $enc) {
  103. echo " $enc\n";
  104. }
  105. echo "\nExamples:\n";
  106. echo " barcode -f HTML -e CODE_39 \"1234567890\" \"/tmp/1234567890.html\"\n";
  107. echo " barcode -e CODE_128 -f PNG -c \"#888\" -w 3 -h 50 \"AGREATBAR\" \"/tmp/AGREATBAR.png\"\n";
  108. echo " barcode \"1234567890\" \"/tmp/mybar.svg\" --encoding EAN_13 --format SVG\n";
  109. }
  110. /////////////////// CREATE SH SCRIPT
  111. // creates a shell script named barcode that will run this script
  112. // from anywhere on the system. Assumes barcode.php is running
  113. // on its final installation location
  114. function create_bash_script() {
  115. $error = true;
  116. $bc_path = __FILE__;
  117. $bash_path = dirname($bc_path) . DIRECTORY_SEPARATOR . "barcode";
  118. $bash_script = <<<EOF
  119. #!/usr/bin/env sh
  120. ##################################################
  121. # Gustavo Arnosti Neves - 2016 Jul 11
  122. # Simple bash script for global barcode executable
  123. # PHP cli-barcode-generator
  124. #
  125. # Please run "./barcode.php --create-bash" to update this script
  126. # You can then use sudo make install to copy it to /usr/local/bin
  127. #
  128. # This won't work on windows
  129. #
  130. BARCODE_LOCATION="$bc_path" # enter full path here
  131. /usr/bin/env php "\$BARCODE_LOCATION" "\$@"
  132. EOF;
  133. if (file_exists($bash_path)) {
  134. unlink($bash_path) or die("Could not remove old barcode script, are you running from it?");
  135. }
  136. $error = file_put_contents($bash_path, $bash_script) === true ? false : true;
  137. $error = chmod($bash_path, 0755) === true ? false : true;
  138. if ($error) {
  139. echo "\nAn error was detected during the process.\n";
  140. echo "Please check for permissions and try again.\n\n";
  141. exit(2);
  142. }
  143. echo "\nThe file \"$bash_path\" was successfully created.\n";
  144. echo "You may perform a system install to /usr/local/bin by issuing\n";
  145. echo "the command \"sudo make install\"\n\n";
  146. exit(0);
  147. }
  148. /////////////////// GETOPT STARTS
  149. use Ulrichsg\Getopt\Getopt;
  150. use Ulrichsg\Getopt\Option;
  151. use Ulrichsg\Getopt\Argument;
  152. // check if encoding callback
  153. function isEncoding($enc=null) {
  154. global $encodings_list;
  155. return in_array(strtoupper($enc), $encodings_list);
  156. }
  157. // check if format callback
  158. function isFormat($format=null) {
  159. global $formats_list;
  160. return in_array(strtoupper($format), $formats_list);
  161. }
  162. // check if empty callback
  163. function not_empty($str) {
  164. return (!empty($str));
  165. }
  166. // check if empty callback
  167. function isHexColor($str) {
  168. $str = str_replace('#', '', $str);
  169. if (! ctype_alnum($str) || (strlen($str) !== 6 && strlen($str) !== 3)) return false;
  170. return true;
  171. }
  172. function checkQuietExit($exitStat=0) {
  173. global $quiet;
  174. if ($quiet) ob_end_clean();
  175. exit($exitStat);
  176. }
  177. // define and configure options
  178. $getopt = new Getopt(array(
  179. (new Option('e', 'encoding', Getopt::REQUIRED_ARGUMENT))
  180. ->setDescription('Barcode encoding type selection, listed below')
  181. ->setArgument(new Argument(null, 'isEncoding', 'bar-type')),
  182. (new Option('f', 'format', Getopt::REQUIRED_ARGUMENT))
  183. ->setDescription('Output format for the barcode, listed below')
  184. ->setArgument(new Argument(null, 'isFormat', 'file-type')),
  185. (new Option('w', 'width', Getopt::REQUIRED_ARGUMENT))
  186. ->setDescription('Width factor for bars to make wider, defaults to 2')
  187. ->setArgument(new Argument(2, 'is_numeric', 'points')),
  188. (new Option('h', 'height', Getopt::REQUIRED_ARGUMENT))
  189. ->setDescription('Total height of the barcode, defaults to 30')
  190. ->setArgument(new Argument(30, 'is_numeric', 'points')),
  191. (new Option('c', 'color', Getopt::REQUIRED_ARGUMENT))
  192. ->setDescription('Hex code of the foreground color, defaults to black'._BC_HELP_NEWLINE."Eg. -c 54863b, or -c '#000'")
  193. ->setArgument(new Argument('#000000', 'isHexColor', 'hex-color')),
  194. (new Option('v', 'verbose'))
  195. ->setDescription('Prints verbose information to screen'._BC_HELP_NEWLINE."Use twice for timestamp")
  196. ->setDefaultValue(false),
  197. (new Option('q', 'quiet'))
  198. ->setDescription('Supress all messages, even errors')
  199. ->setDefaultValue(false),
  200. (new Option(null, 'help'))
  201. ->setDescription('Help Information, including encodings and formats'),
  202. (new Option(null, 'version'))
  203. ->setDescription('Display version information and exits'),
  204. (new Option(null, 'create-bash'))
  205. ->setDescription('Creates a shell script named \'barcode\' that can call this script')
  206. ));
  207. $getopt->setBanner("Usage: barcode -e <encoding> -f <output_format> [options] <barcode string> <output file>\n");
  208. try {
  209. $getopt->parse();
  210. if ($getopt['version']) {
  211. printVersion();
  212. exit(0);
  213. }
  214. if ($getopt['help']) {
  215. print_help($getopt);
  216. exit(0);
  217. }
  218. if ($getopt['create-bash']) {
  219. create_bash_script();
  220. exit(1);
  221. }
  222. $verbose = $getopt['verbose'];
  223. $quiet = $getopt['quiet'];
  224. $encoding = $getopt['encoding'];
  225. $format = $getopt['format'];
  226. $width = $getopt['width'];
  227. $height = $getopt['height'];
  228. $color = '#'.str_replace('#', '', $getopt['color']);
  229. $bc_string = $getopt->getOperand(0);
  230. $bc_file = $getopt->getOperand(1);
  231. } catch (UnexpectedValueException $e) {
  232. echo "Error: ".$e->getMessage()."\n";
  233. echo $getopt->getHelpText(_BC_PADDING);
  234. exit(1);
  235. }
  236. // check if we can proceed
  237. if (empty($encoding) || empty($format) || empty($bc_string) || empty($bc_file)) {
  238. echo "Error: Invalid parameters or options.\n";
  239. echo $getopt->getHelpText(_BC_PADDING);
  240. exit(1);
  241. }
  242. // check output directory
  243. $tgtDir = dirname($bc_file);
  244. if (! is_dir($tgtDir)) {
  245. echo "Error: Could not locate target directory!\nTarget Dir: $tgtDir\n";
  246. exit(1);
  247. }
  248. // Match case
  249. $encoding = strtoupper($encoding);
  250. $format = strtoupper($format);
  251. /////////////////// QUIET EXECUTION STARTS
  252. // From here on use checkQuietExit() to Exit
  253. if ($quiet) {
  254. ob_start();
  255. }
  256. /////////////////// GETOPT ENDS
  257. /////////////////// PRINT VERBOSE INFO
  258. vPrint(getVersionString(" - Verbose Execution"));
  259. vPrint(array("Output File", "$bc_file"));
  260. vPrint(array("Barcode String", "$bc_string"));
  261. vPrint(array("Barcode Encoding", "$encoding"));
  262. vPrint(array("Output Format", "$format"));
  263. vPrint(array("Width Factor", "$width"));
  264. vPrint(array("Height of Barcode", "$height"));
  265. vPrint(array("Hex Color", "$color"));
  266. function vPrint($input) {
  267. global $verbose;
  268. if ($verbose) {
  269. if ($verbose > 1) echo date(DATE_ATOM) . " | ";
  270. if (is_array($input) && count($input) > 1) {
  271. printf("%-17s : %-30s\n", $input[0], $input[1]);
  272. } else if (is_string($input)) {
  273. echo "$input\n";
  274. }
  275. }
  276. }
  277. /////////////////// CREATE BARCODE STARTS
  278. // get actual barcode type string
  279. $bc_type = constant('Picqer\Barcode\BarcodeGenerator::TYPE_'.$encoding);
  280. // add trailling zero if odd digits on Code128C
  281. $bc_string = strlen($bc_string) % 2 != 0 && $encoding === 'CODE_128_C'?
  282. '0'.$bc_string : $bc_string;
  283. // create appropriate generator
  284. $generator = null;
  285. if ($format === 'SVG') {
  286. $generator = new Picqer\Barcode\BarcodeGeneratorSVG();
  287. } else if ($format === 'PNG') {
  288. $color = hexToRgb($color);
  289. $generator = new Picqer\Barcode\BarcodeGeneratorPNG();
  290. } else if ($format === 'JPG') {
  291. $color = hexToRgb($color);
  292. $generator = new Picqer\Barcode\BarcodeGeneratorJPG();
  293. } else if ($format === 'HTML') {
  294. $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
  295. } else {
  296. echo "Error: Invalid taget format: $format\n";
  297. checkQuietExit(1);
  298. }
  299. // generate de barcode
  300. try {
  301. $bc_data = $generator->getBarcode($bc_string, $bc_type, $width, $height, $color);
  302. } catch (Exception $e) {
  303. echo "Error: ".$e->getMessage()."\n";
  304. checkQuietExit(1);
  305. }
  306. // save to file
  307. if (@file_put_contents($bc_file, $bc_data) === false) {
  308. echo "Error: could not save file $bc_file!\n";
  309. checkQuietExit(1);
  310. }
  311. // set permissions and group
  312. #chmod($bc_file, $_defPermission);
  313. #chgrp($bc_file, $_defGroup);
  314. /////////////////// CREATE BARCODE ENDS
  315. /////////////////// PRINT VERBOSE INFO ENDS
  316. vprint(array("Final Status", "Success"));
  317. checkQuietExit(0);
  318. ?>