blib/lib/oEdtk/Main.pm untested

filter: Statementstmt 0.0% 0 / 786 Branchbran 0.0% 0 / 224 Conditioncond 0.0% 0 / 153 MC/DCmcdc 0.0% 0 / 87 Subroutinesub 0.0% 0 / 97 Podpod 0.0% 0 / 70 totaltotal 0.0% 0 / 1417 CC 113 SCAR 36.3
CC
113
Cov
0%
oe_new_job
240.0
oe_compo_link
90.0
oe_new_job_output_file
90.0
CRAP 37.6
1 package oEdtk::Main;
2  
3 use strict;
4 use utf8;
5 use warnings;
6 use feature 'state';
7  
8 use Exporter;
9 our $VERSION = 2.1126;
10  
11 our @ISA = qw(Exporter);
12 our @EXPORT = qw(
13 date2time
14 prodEdtk_Current_Rec
15 prodEdtk_Previous_Rec
16 prodEtk_rec_cdata_join
17 recEdtk_erase
18 recEdtk_join_tmplte
19 recEdtk_post_process
20 recEdtk_redefine
21 oe_app_usage
22 oe_backgrounds_apps
23 oe_CAP_sans_accents
24 oe_char_xlate
25 oe_clean_addr
26 oe_clean_addr_line
27 oe_close_fo
28 oe_compo_link
29 oe_corporation_get
30 oe_corporation_set
31 oe_corporation_tag
32 oe_data_build
33 oe_date_biggest
34 oe_date_smallest
35 oe_define_TeX_output
36 oe_env_var_completion
37 oe_fmt_date
38 oe_get_handle_to_input_file
39 oe_ID_LDOC
40 oe_is_IDLDOC
41 oe_iso_country
42 oe_list_encodings
43 oe_new_ID_LDOC
44 oe_new_job
45 oe_new_job_input_file
46 oe_now_time
47 oe_num_sign_x
48 oe_num2txt_us
49 oe_open_fi_IN
50 oe_open_fo_OUT
51 oe_options
52 oe_params
53 oe_print_to_output_file
54 oe_process_ref_rec
55 oe_rec_motif
56 oe_rec_output
57 oe_rec_pre_process
58 oe_rec_process
59 oe_round
60 oe_set_sys_date
61 oe_simple_job
62 oe_to_date
63 oe_trimp_space
64 oe_trt_ref_rec
65 oe_uc_sans_accents
66 oe_unique_data_name
67 *OUT *IN @DATATAB $LAST_ENR
68 %motifs %ouTags %evalSsTrt
69 );
70  
71 use POSIX qw(mkfifo);
72 use Date::Calc qw(Add_Delta_Days Delta_Days Date_to_Time Today Gmtime Week_of_Year);
73 use Encode;
74 use File::Basename;
75 use Getopt::Long qw(GetOptionsFromArray);
76 use List::MoreUtils qw(uniq);
77 use List::Util qw(reduce);
78 use Math::Round qw(nearest);
79 use Sys::Hostname;
80 use Scalar::Util qw(openhandle);
81 use Carp qw(croak);
82 use Readonly;
83 use Data::UUID;
84  
85 use oEdtk;
86 require oEdtk::Outmngr;
87 require oEdtk::TexDoc;
88 use oEdtk::Dict;
89 use oEdtk::Config qw(config_read);
90 use oEdtk::Run qw(oe_status_to_msg oe_compo_run oe_after_compo oe_outmngr_output_run_tex);
91  
92 #use oEUser::Lib;
93  
94 #
95 # CODE - DOC AT THE END
96 #
97  
98 # GENERIC METHOD FOR EXTRACTING AND PROCESSING DATA
99  
100 our @DATATAB; # the array into which records are distributed
101 # rename to OE_DATATAB
102 our $LAST_ENR = ""; # WHAT ABOUT LAST_ENR ????
103 our $CURRENT_REC = ""; # current record
104 our $PREVIOUS_REC = ""; # previous record
105  
106 our %motifs; #make private
107 our %ouTags; #make private
108 our %evalSsTrt; #make private
109  
110 my $_ID_LDOC = ''; # initialize the unique document id (one per run)
111 my $_IDLDOC_FORMAT;
112 my $PUSH_VALUE = "";
113  
114 # Default option values (see oe_options).
115 Readonly my %DEFAULT_OPTIONS => (
116 index => 0,
117 massmail => 0,
118 edms => 0,
119 bpdf => 0,
120 cgi => 0,
121 input_code => 0
122 );
123  
124 # [PRIVATE] Default dump mode (0: off, 1: on). Leave it at 0.
125 # @see _dump()
126 Readonly::Scalar my $_DEFAULT_OUTPUT_DUMP_MODE => 0;
127  
128 # [PRIVATE] Default path of the output debug file.
129 # @see _dump()
130 Readonly::Scalar my $_DEFAULT_OUTPUT_DUMP_FILE => 'output.rec';
131  
132 # PLANNED : CONFIGURATION OF OUTPUT SYSTEM
133 # return "\\long\\gdef\\$name\{$value\}";
134 my ( $TAG_OPEN, $TAG_CLOSE, $TAG_COMMENT );
135  
136 sub oe_define_TeX_output() {
137  
138 # \\long\\gdef\\$name\{$value\}
139 # \long\gdef\NUMCONT{000014770}
140 # \long\gdef\PRENOM{MIREILLE}\long\gdef\DATE{01/08/2009}\long\gdef\NICY{10}\STARTGAR
141 $TAG_OPEN = "\\"; # a tag opening (open)
142 $TAG_CLOSE = ""; # a tag closing (close)
143 $TAG_COMMENT = "%"; # a comment (rem)
144  
145 # \long\gdef\xProdApp\}
146 1;
147 }
148  
149 oe_define_TeX_output(); # default values
150  
151 ################################################################################
152 ## GENERIC RECORD HELPERS, USED ELSEWHERE (XLS)
153 ################################################################################
154  
155 sub oe_rec_motif { # migrate oe_rec_motif
156 # FUNCTION TO DESCRIBE THE UNPACK PATTERN OF THE RECORD
157 #
158 # appel :
159 # oe_rec_motif ($keyRec, "A2 A10 A15 A10 A15 A*");
160 my $keyRec = shift;
161 my $motif = shift;
162 $motifs{$keyRec} = $motif;
163 1;
164 }
165  
166 sub oe_rec_pre_process { # migrate oe_rec_pre_process
167 # FUNCTION TO ATTACH A PRE-PROCESSING TO A RECORD
168 # this processing runs before the record is loaded into DATATAB
169 # the previous record content is always available in DATATAB
170 # the current record type is known in the execution context
171 #
172 # appel :
173 # oe_rec_pre_process ($keyRec, \&fonction);
174 my $keyRec = shift;
175 my $refFonction = shift;
176 $evalSsTrt{$keyRec}[0] = $refFonction;
177 1;
178 }
179  
180 sub oe_rec_output { # migrate oe_rec_output
181 # FUNCTION TO DESCRIBE THE RECORD OUTPUT FORMAT FOR SPRINTF
182 #
183 # appel :
184 # oe_rec_output ($keyRec, "<#GESTION=%s><#PENOCOD=%s><#LICCODC=%s><SK>%s");
185 my $keyRec = shift;
186 my $format = shift;
187 $ouTags{$keyRec} = $format;
188 1;
189 }
190  
191 sub recEdtk_erase { # migrate oe_rec_erase
192 # FUNCTION TO REMOVE THE PROCESSING OF A RECORD
193 #
194 # appel :
195 # recEdtk_erase ($keyRec);
196 my $keyRec = shift;
197 $evalSsTrt{$keyRec}[0] = "";
198 $evalSsTrt{$keyRec}[1] = "";
199 $evalSsTrt{$keyRec}[2] = "";
200 $motifs{$keyRec} = "";
201 $ouTags{$keyRec} = "-1";
202 1;
203 }
204  
205 sub recEdtk_redefine { # migrate oe_rec_redefine
206 # FUNCTION TO REDEFINE THE PROCESSING OF A RECORD
207 #
208 # appel :
209 # recEdtk_redefine ($keyRec, "A2 A10 A15 A10 A15 A*");
210 my $keyRec = shift;
211 my $motif = shift;
212 recEdtk_erase($keyRec);
213 oe_rec_motif( $keyRec, $motif );
214 1;
215 }
216  
217 sub recEdtk_join_tmplte { # migrate oe_rec_joined_descriptors
218 # FUNCTION TO COMPLETE THE UNPACK PATTERN DESCRIPTORS OF THE RECORD
219 # AND THE OUTPUT FORMAT IN PARALLEL
220 #
221 # appel :
222 # recEdtk_join_tmplte ("abc", 'A2', '<#tag=%s>');
223 # recEdtk_join_tmplte ($keyRec, $motif, $output);
224  
225 my $keyRec = shift;
226 my $motif = shift;
227 $motif ||= "A*";
228 my $output = shift;
229 $output ||= "%s";
230 $motifs{$keyRec} .= $motif;
231 $ouTags{$keyRec} .= $output;
232 $ouTags{$keyRec} =~ s/^\-1//
233 ; # when recEdtk_join_tmplte is used to set ouTags dynamically during oe_trt_ref_rec, the default ouTags value = '-1' (no processing) => remove it so as not to pollute the output
234 1;
235 }
236  
237 sub oe_rec_process { # migrate oe_rec_process
238 # FUNCTION TO ATTACH A PROCESSING TO A RECORD
239 # this processing runs right after the record is loaded into DATATAB
240 #
241 # appel :
242 # oe_rec_process ($keyRec, \&fonction);
243 my $keyRec = shift;
244 my $refFonction = shift;
245 $evalSsTrt{$keyRec}[1] = $refFonction;
246 1;
247 }
248  
249 sub recEdtk_post_process { # migrate recEdtk_post_process
250 # FUNCTION TO ATTACH A POST-PROCESSING TO A RECORD
251 # this processing runs right after the record is reformatted in format_sortie
252 # the record line is known in the execution context, in its "format_sortie" form
253 #
254 # appel :
255 # recEdtk_post_process ($keyRec, \&fonction);
256 my $keyRec = shift;
257 my $refFonction = shift;
258 $evalSsTrt{$keyRec}[2] = $refFonction;
259 1;
260 }
261  
262 ## no critic (ProhibitSubroutinePrototypes)
263 sub oe_process_ref_rec ($$\$;$$) { # migrate oe_process_ref_rec
264 # COMBINED ANALYSIS AND PROCESSING OF RECORDS
265 # it wraps the complete analysis and processing of the record (oe_trt_ref_rec)
266 # one call per key length, in decreasing order (from the strictest key to the least restrictive)
267 # APPEL :
268 # oe_process_ref_rec ($offsetKey, $lenKey, $ligne [,$offsetRec, $lenRec]);
269 # RETURNS: status
270 #
271 # example if (oe_process_ref_rec (0, 3, $ligne)){
272 # } elsif (oe_process_ref_rec (0, 2, $ligne)){
273 # etc.
274 my $offsetKey = shift;
275 my $lenKey = shift;
276 my $refLigne = shift;
277 my $offsetRec = shift; # optional
278 $offsetRec ||= 0;
279 my $lenRec = shift; # optional
280 $lenRec ||= "";
281  
282 if ( ${$refLigne} =~ m/^.{$offsetKey}(\w{$lenKey})/s
283 && oe_trt_ref_rec( $1, $refLigne, $offsetRec, $lenRec ) )
284 {
285 # the record has been identified and processed
286 # emit the record
287 print OUT ${$refLigne};
288 return 1;
289 }
290  
291 # OTHERWISE THE RECORD WAS NOT RECOGNIZED, THIS IS A FAILURE
292 return 0;
293 }
294  
295 ## no critic (ProhibitSubroutinePrototypes)
296 sub oe_trt_ref_rec ($\$;$$) { # migrate oe_trt_ref_rec
297 # MAIN RECORD PROCESSING
298 # GENERIC METHOD V0.2.1 27/04/2009 10:05:03 (reference passing becomes implicit)
299 # THE FUNCTION NEEDS THE RECORD TYPE AND THE REFERENCE TO A DATA LINE
300 # appel :
301 # oe_trt_ref_rec($Rec_ID, $ligne [,$offsetRec,$lenRec]);
302 # returns: status, $Rec_ID
303 my $Rec_ID = shift;
304 my $refLigne = shift;
305 my $offsetRec = shift; # OPTIONAL OFFSET OF DATA TO DROP AT THE START OF THE LINE
306 my $lenRec = shift; # OPTIONAL LENGTH OF DATA TO PROCESS
307 # DEFAULT VALUES
308 $ouTags{$Rec_ID} ||= "-1";
309 $motifs{$Rec_ID} ||= "";
310 $offsetRec ||= 0;
311 $lenRec ||= "";
312  
313 # IF THE EXTRACTION PATTERN OF THE RECORD TYPE IS UNKNOWN,
314 # AND IF THERE IS NO PRE-PROCESSING ATTACHED TO THE RECORD TYPE,
315 # THEN THE RECORD TYPE IS UNKNOWN
316 #
317 # THIS CHECK ALLOWS DEFINING A RECORD TYPE DYNAMICALLY BASED ON THE CONTEXT
318 # THAT IS, A RECORD OF TYPE "1" MAY HAVE DIFFERENT CHARACTERISTICS
319 # DEPENDING ON THE PREVIOUSLY PROCESSED RECORD TYPE.
320 # THESE CHARACTERISTICS CAN BE SET AT PRE-PROCESSING TIME.
321 #
322 if ( $motifs{$Rec_ID} eq "" && !( $evalSsTrt{$Rec_ID}[0] ) ) {
323 warn "INFO: oe_trt_ref_rec() > LINE $. REC. >$Rec_ID< (offset $offsetRec) UNKNOWN\n";
324 return 0;
325 }
326  
327 $PREVIOUS_REC = $CURRENT_REC;
328 $CURRENT_REC = $Rec_ID;
329  
330 # STEP 0 : EVAL PRE-PROCESSING of $refLigne
331 &{ $evalSsTrt{$Rec_ID}[0] }($refLigne) if $evalSsTrt{$Rec_ID}[0];
332  
333 # MAKE SURE TO FULLY CLEAR THE READ ARRAY OF THE PREVIOUS RECORD
334 undef @DATATAB;
335  
336 # OPTIONALLY DROP UNNEEDED DATA (OFFSET AND OUTSIDE USEFUL DATA (lenData))
337 ${$refLigne} =~ s/^.{$offsetRec}(.{1,$lenRec}).*/$1/ if ( $offsetRec > 0 );
338  
339 # SPLIT THE RECORD INTO FIELDS
340 @DATATAB = unpack( $motifs{$Rec_ID}, ${$refLigne} )
341 or die
342 "ERROR: oe_trt_ref_rec() > LINE $. typEnr >$Rec_ID< motif >$motifs{$Rec_ID}< UNKNOWN\n";
343  
344 # STEP 1 : EVAL FIELD PROCESSING
345 &{ $evalSsTrt{$Rec_ID}[1] } if $evalSsTrt{$Rec_ID}[1];
346  
347 # STRUCTURE THE RECORD FOR OUTPUT
348 if ( $ouTags{$Rec_ID} ne "-1" ) {
349 ${$refLigne} = "${TAG_OPEN}a${Rec_ID}${TAG_CLOSE}";
350 ${$refLigne} .= sprintf( $ouTags{$Rec_ID}, @DATATAB )
351 or die "ERROR: oe_trt_ref_rec() > LINE $. typEnr >$Rec_ID< ouTags >$ouTags{$Rec_ID}<\n";
352 ${$refLigne} .= "${TAG_OPEN}e${Rec_ID}${TAG_CLOSE}\n";
353 }
354 else {
355 ${$refLigne} = "";
356 }
357 $LAST_ENR = $Rec_ID;
358  
359 # STEP 2 : EVAL POST-PROCESSING
360 &{ $evalSsTrt{$Rec_ID}[2] } if $evalSsTrt{$Rec_ID}[2];
361  
362 # OPTIONALLY ADD EXTRA DATA
363 ${$refLigne} .= $PUSH_VALUE;
364 $PUSH_VALUE = "";
365 ${$refLigne} =~ s/\s{2,}/ /g; # CONCATENATION OF BLANKS
366 #$LAST_ENR=$Rec_ID;
367  
368 return 1, $Rec_ID;
369 }
370  
371 sub prodEtk_rec_cdata_join { # migrate prodEtk_rec_cdata_join
372 $PUSH_VALUE .= shift;
373 1;
374 }
375  
376 sub prodEdtk_Previous_Rec () { # migrate oe_previous_rec
377 return $PREVIOUS_REC;
378 }
379  
380 sub prodEdtk_Current_Rec () { # migrate oe_current_rec
381 return $CURRENT_REC;
382 }
383  
384 ################################################################################
385  
386 sub oe_round {
387  
388 # http://perl.enstimac.fr/allpod/fr-5.6.0/perlfaq4.pod
389 # http://perl.enstimac.fr/DocFr/perlfaq4.html
390 # http://www.linux-kheops.com/doc/perl/faq-perl-enstimac/perlfaq4.html
391 # Perl is not at fault. It is the same as in C. IEEE says we must do it this way. Perl numbers whose absolute value is an integer below 2**31 (on 32-bit machines) will generally behave as mathematical integers. Other numbers are not guaranteed.
392 my $value = shift;
393 my $multiple = shift;
394 my $decimal; #= shift;
395  
396 #if (!(defined $decimal)){$decimal = 2;} # decimal may be 0 (decimal converted to an integer)
397 if ( !( defined $multiple ) ) {
398 $multiple = .01;
399 } # $multiple may be 0 (decimal converted to an integer)
400 if ( $multiple =~ /^0\./ ) {
401 $decimal = length($multiple) - 2;
402 }
403 elsif ( $multiple =~ /^\./ ) {
404 $decimal = length($multiple) - 1;
405 }
406 else {
407 $decimal = 0;
408 }
409 my $motif = "%.0${decimal}f";
410  
411 #my $multiple=1/(10**$decimal);
412 $value = nearest( $multiple, $value );
413  
414 return sprintf( $motif, $value );
415 }
416  
417 # Signed-amount digit map. Read in the substitution below, where "$HX_VAL{$1}"
418 # interpolates as a hash element. Hoisted out of oe_num_sign_x, which rebuilt it
419 # on every call (17609 on the document path, ~13x the cost of a single lookup).
420 my %HX_VAL = (
421 'p' => 0,
422 'q' => 1,
423 'r' => 2,
424 's' => 3,
425 't' => 4,
426 'u' => 5,
427 'v' => 6,
428 'w' => 7,
429 'x' => 8,
430 'y' => 9,
431 );
432  
433 ## no critic (ProhibitSubroutinePrototypes)
434 sub oe_num_sign_x(\$;$) { # migrate oe_num_sign_x
435 # processing of alphanumeric signed amounts
436 # receives: a reference to an alphanumeric variable
437 # a number of decimals after the point (optional, 0 by default)
438  
439 my ( $refMontant, $decimal ) = @_;
440 ${$refMontant} ||= "";
441 $decimal ||= 0;
442  
443 # check the validity of the passed value
444 ${$refMontant} =~ s/\s+//g;
445 if ( ${$refMontant} eq "" || ${$refMontant} eq 0 ) {
446 ${$refMontant} = 0;
447 return 1;
448 }
449 elsif ( ${$refMontant} =~ /\D{2,}/ ) {
450 warn "INFO: value (${$refMontant}) not numeric.\n";
451 return -1;
452 }
453  
454 if ( ${$refMontant} =~ s/(\D{1})$/$HX_VAL{$1}/ ) {
455  
456 # a value with an alphanumeric negative sign 213y => -2139
457 ${$refMontant} = ( ${$refMontant} * (-1) );
458  
459 # warn "INFO: SIGNED AMOUNT";
460 }
461 elsif ( ${$refMontant} =~ /^-{1}/ ) {
462  
463 # a value with a negative sign -123456
464 }
465  
466 ${$refMontant} = ${$refMontant} / ( 10**$decimal );
467  
468 return ${$refMontant};
469 }
470  
471 sub date2time { # migrate oe_date_to_time
472 # DEPRECATED FUNCTION,
473 # USE THE SPECIALIZED LIBRARY: Date::Calc
474 my $date = shift; # a date in YYYYMMDD format
475  
476 my $tmpDate = "AAAAMMJJ";
477 my $decalage = 0;
478 my $jours = -1;
479 my $time = time;
480 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday ) = gmtime($time);
481 my $nowDate = sprintf( "%4.0f%02.0f%02.0f", $year + 1900, $mon + 1, $mday );
482  
483 if ( $nowDate > $date ) {
484  
485 # date is older
486 $decalage = -1;
487 }
488 elsif ( $nowDate < $date ) {
489  
490 # date is newer
491 $decalage = +1;
492 }
493  
494 while ( $date ne $tmpDate ) {
495 $jours++;
496  
497 # a day has 86400 seconds
498 ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday ) =
499 gmtime( $time + ( $decalage * $jours * 86400 ) );
500 $tmpDate = sprintf( "%4.0f%02.0f%02.0f", $year + 1900, $mon + 1, $mday );
501 }
502  
503 return ( $time + ( $decalage * $jours * 86400 ) ), ( $decalage * $jours );
504 }
505  
506 sub oe_now_time() { # migrate oe_now_time
507 # DEPRECATED FUNCTION,
508 # USE THE SPECIALIZED LIBRARY: Date::Calc -> Today
509  
510 my $time = time;
511 my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday ) = gmtime($time);
512 $time = sprintf(
513 "%4.0f%02.0f%02.0f%02.0f%02.0f%02.0f",
514 $year + 1900,
515 $mon + 1, $mday, $hour, $min, $sec
516 );
517  
518 return $time;
519 }
520  
521 # ISO COUNTRY DICTIONARY
522 my $_DICO_COUNTRY;
523  
524 # ABBREVIATIONS DICTIONARY.
525 my $_DICO_POST;
526  
527 # translation dictionary for characters (discouraged, but sometimes needed).
528 my $_DICO_CHAR;
529  
530 {
531 my $_LAST_ISO = "";
532  
533 sub oe_iso_country {
534  
535 # returns the country code in country_dico.ini coding or the last known value
536 my $country = shift;
537 if ( !defined($_DICO_COUNTRY) ) {
538 my $cfg = config_read();
539 $_DICO_COUNTRY =
540 oEdtk::Dict->new( $cfg->{'EDTK_DICO_COUNTRY'}, { section => $cfg->{'EDTK_LANG'} } );
541 }
542 $_LAST_ISO = $_DICO_COUNTRY->translate($country) if defined($country);
543 return $_LAST_ISO;
544 }
545 }
546  
547 sub oe_char_xlate { # to migrate into the dictionary?
548 my $scalar = shift;
549  
550 if ( !defined($_DICO_CHAR) ) {
551 my $section = shift || 'DEFAULT';
552 my $cfg = config_read();
553 $_DICO_CHAR = oEdtk::Dict->new( $cfg->{'EDTK_DICO_XLAT'}, { section => $section } );
554 }
555 $scalar = $_DICO_CHAR->substitue($scalar);
556  
557 return $scalar;
558 }
559  
560 ## no critic (ProhibitSubroutinePrototypes)
561 sub oe_clean_addr_line(\$) { # migrate oe_clean_addr_line
562 # THIS FUNCTION CLEANS ADDRESS LINES TO BUILD THE RECIPIENT ADDRESS BLOCKS
563 # it works directly on the variable reference but also returns the resulting string
564 my $rLine = shift;
565  
566 # default value in case the field is undef
567 if ( !defined($$rLine) || length($$rLine) == 0 ) {
568 $$rLine = '';
569 return $$rLine;
570 }
571  
572 chomp($$rLine); # to be sure there is no trailing newline at the end of the field
573 oe_trimp_space($rLine);
574  
575 $$rLine = oe_char_xlate( $$rLine, 'ADDRESS' );
576  
577 # TODO: a regex that replaces everything that is not 0-9, -, degrees or \w with blanks...
578  
579 # THE NEXT LINE MUST BE ENABLED ONLY AFTER TESTING, FOR NOW HANDLED BY oe_char_xlate
580 #$$rLine =~ s/\\+/\//g; # we remove/replace backslashes which are escape characters and which apparently are not counted in the size check (sprintf("%.38s",...)
581 $$rLine =~ s/^\s+//
582 ; # remove consecutive blanks at the start of the string (an oe_trimp_space was done first...) LEFT TRIM
583 $$rLine =~ s/\s+$//; # remove consecutive blanks at the end of the string (...) RIGHT TRIM
584 $$rLine =~
585 s/^0\s+//; # remove lone zeros at the start of the string (done last, after the LEFT TRIM)
586 $$rLine =~ s/\s+/ /; # collapse consecutive blanks
587  
588 # Use the given dictionary to translate words.
589 if ( length($$rLine) > 38 ) {
590 if ( !defined($_DICO_POST) ) {
591 my $cfg = config_read();
592 $_DICO_POST = oEdtk::Dict->new( $cfg->{'EDTK_DICO_POST'} );
593 }
594 my @words = split( / /, $$rLine );
595 $$rLine = join( ' ', map { $_DICO_POST->translate($_) } @words );
596 }
597 $$rLine = sprintf( "%.38s", $$rLine ); # make sure not to exceed 38 characters per line
598  
599 return $$rLine;
600 }
601  
602 ## no critic (ProhibitSubroutinePrototypes)
603 sub oe_CAP_sans_accents (\$) {
604  
605 # THIS FUNCTION CONVERTS ACCENTED UPPERCASE CHARACTERS INTO NON-ACCENTED UPPERCASE CHARACTERS
606 # using localization causes a bug in the "sort" command.
607 # We do not rely on the ability to restore the default behavior by escaping
608 # (the no locale directive, or when leaving the block enclosing the use locale directive)
609 # so as to adopt a standard and simplified operating mode.
610 # NB: localization slows sorting down considerably.
611 # (cf. Perl documentation about localization: perllocale)
612 #
613 # the function is called with an implicit reference passing
614 # oe_char_no_accents($chaine);
615  
616 my $refChaine = shift;
617 ${$refChaine} ||= "";
618 ${$refChaine} =~ s/[ÀÂÄ]/A/g;
619 ${$refChaine} =~ s/[ÉÈÊË]/E/g;
620 ${$refChaine} =~ s/[ÌÎÏ]/I/g;
621 ${$refChaine} =~ s/[ÒÔÖÕ]/O/g;
622 ${$refChaine} =~ s/[ÚÙÛÜ]/U/g;
623 ${$refChaine} =~ s/Ç/C/g;
624  
625 # the uc command is not included; it can be done before calling oe_CAP_sans_accents
626 # - either keep accented lowercase letters, or capitalize everything
627 ## ${$refChaine}= uc ${$refChaine};
628  
629 return ${$refChaine};
630 }
631  
632 ## no critic (ProhibitSubroutinePrototypes)
633 sub oe_uc_sans_accents (\$) { # migrate oe_uc_sans_accents
634 # THIS FUNCTION CONVERTS ACCENTED CHARACTERS INTO NON-ACCENTED UPPERCASE CHARACTERS
635 # using localization causes a bug in the "sort" command.
636 # We do not rely on the ability to restore the default behavior by escaping
637 # (the no locale directive, or when leaving the block enclosing the use locale directive)
638 # so as to adopt a standard and simplified operating mode.
639 # NB: localization slows sorting down considerably.
640 # (cf. Perl documentation about localization: perllocale)
641 #
642 # the function is called with an implicit reference passing
643 # oe_uc_sans_accents($chaine);
644  
645 my $refChaine = shift;
646 ${$refChaine} ||= "";
647 ${$refChaine} =~ s/[àâä]/a/ig;
648 ${$refChaine} =~ s/[éèêë]/e/ig;
649 ${$refChaine} =~ s/[ìîï]/i/ig;
650 ${$refChaine} =~ s/[òôöõ]/o/ig;
651 ${$refChaine} =~ s/[úùûü]/u/ig;
652 ${$refChaine} =~ s/ç/c/ig;
653 ${$refChaine} = uc ${$refChaine};
654  
655 return ${$refChaine};
656 }
657  
658 ## no critic (ProhibitSubroutinePrototypes)
659 sub oe_trimp_space(\$) { # migrate oe_trimp_space
660 # REMOVE CONSECUTIVE SPACES (TRAILING BLANK) BY GROUPING
661 # the parameter must be a reference, example: oe_trimp_space($chaine)
662 # returns the number of removed characters
663 my $rChaine = shift;
664 ${$rChaine} ||= "";
665 ${$rChaine} =~ s/\s{2,}/ /go;
666  
667 return ${$rChaine};
668 }
669  
670 sub oe_list_encodings {
671 my @list = Encode->encodings();
672 warn "INFO: available encodings on this machine are : @list\n";
673 }
674  
675 # migrate oe_open_fi_IN
676 sub oe_open_fi_IN { # BASIC INPUT FILE HANDLING
677 my ( $fi, $enc ) = @_;
678  
679 # An explicit encoding wins; otherwise EDTK_OUT_ENCODING from the config.
680 # An absent key keeps M behaviour: an open with no encoding layer.
681 $enc = oe_config_compo()->{'EDTK_OUT_ENCODING'} unless defined $enc;
682 my $mode = $enc ? "<:encoding($enc)" : '<';
683 open( IN, $mode, $fi ) or die "ERROR: opening $fi, return code $!\n"; ## no critic (InputOutput::ProhibitBarewordFileHandles)
684  
685 1;
686 }
687  
688 # migrate oe_open_fo_OUT
689 sub oe_open_fo_OUT { # BASIC OUTPUT FILE HANDLING
690 my ( $fo, $enc ) = @_;
691  
692 $enc = oe_config_compo()->{'EDTK_OUT_ENCODING'} unless defined $enc;
693 my $mode = $enc ? ">:encoding($enc)" : '>';
694 open( OUT, $mode, $fo ) or die "ERROR: opening $fo - return code $!\n"; ## no critic (InputOutput::ProhibitBarewordFileHandles)
695  
696 1;
697 }
698  
699 sub oe_close_fo { # migrate oe_close_fo
700 my $f = shift;
701  
702 close(OUT) or die "ERROR: closing $f - return code $!\n";
703 1;
704 }
705  
706 ## no critic (ProhibitSubroutinePrototypes)
707 sub oe_to_date(\$) { # migrate oe_to_date
708 # RECEIVES A REFERENCE TO A DATE IN YYYYMMDD FORMAT
709 # FORMATS AS DD/MM/YYYY
710 my $refVar = shift;
711 ${$refVar} ||= "";
712 ${$refVar} =~ s/(\d{4})(\d{2})(\d{2})(.*)/$3\/$2\/$1/o;
713  
714 return ${$refVar};
715 }
716  
717 sub oe_fmt_date { # migrate oe_fmt_date
718 my $date = shift;
719  
720 die "ERROR: Unexpected date format: \"$date\"\n"
721 if $date !~ /^\s*(\d{1,2})\/(\d{1,2})\/(\d{2}|\d{4})\s*$/;
722  
723 return sprintf( "%02s/%02s/%s", $1, $2, $3 );
724 }
725  
726 # Convert a date in DD/MM/YYYY format to YYYYMMDD format.
727 sub oe_date_convert { # oe_date_format
728 my $date = shift;
729  
730 if ( $date !~ /^\s*(\d{1,2})\/(\d{1,2})\/(\d{4})\s*$/ ) {
731 return;
732 }
733 return sprintf( "%d%02d%02d", $3, $2, $1 );
734 }
735  
736 sub oe_date_compare {
737 my ( $date1, $date2 ) = @_;
738  
739 if ( $date1 eq '' ) {
740 $date1 = $date2;
741 }
742  
743 my $wdate1 = oe_date_convert($date1);
744 my $wdate2 = oe_date_convert($date1);
745  
746 if ( !defined($wdate1) ) {
747 warn "INFO: Unexpected date format: \"$date1\" should be dd/mm/yyyy. Date ignored\n";
748 return 1;
749 }
750 if ( !defined($wdate2) ) {
751 warn "INFO: Unexpected date format: \"$date2\" should be dd/mm/yyyy. Date ignored\n";
752 return -1;
753 }
754 return $wdate1 <=> $wdate2;
755 }
756  
757 sub oe_date_smallest {
758 my ( $date1, $date2 ) = @_;
759  
760 if ( oe_date_compare( $date1, $date2 ) <= 0 ) {
761 return $date1;
762 }
763 else {
764 return $date2;
765 }
766 }
767  
768 sub oe_date_biggest {
769 my ( $date1, $date2 ) = @_;
770  
771 if ( oe_date_compare( $date1, $date2 ) <= 0 ) {
772 return $date2;
773 }
774 else {
775 return $date1;
776 }
777 }
778  
779 ## no critic (ProhibitSubroutinePrototypes)
780 sub oe_num2txt_us(\$) {
781  
782 # process amounts in Text format
783 # the decimal separator "," is turned into "." for the load commands
784 # the thousands separator "." or " " is removed
785 # receives: an alphanumeric variable formatted for display
786 # $value = oe_num2txt_us($value);
787 # or by reference
788 # oe_num2txt_us($value);
789  
790 my $refValue = shift;
791 ${$refValue} ||= "";
792  
793 if ( ${$refValue} ) {
794 ${$refValue} =~ s/\s+//g; # remove blanks
795 ${$refValue} =~ s/\.//g; # remove thousands separators
796 ${$refValue} =~ s/\,/\./g; # replace the decimal separator
797 ${$refValue} =~ s/(.*)(\-)$/$2$1/; # optionally move the negative sign to the front
798  
799 }
800 else {
801 ${$refValue} = 0;
802 }
803  
804 return ${$refValue};
805 }
806  
807 sub oe_include_build {
808 my ( $name, $path ) = @_;
809  
810 #import oEdtk::TexDoc;
811  
812 my $tag = oEdtk::TexDoc->new();
813 $tag->include( $name, $path );
814 return $tag;
815 }
816  
817 sub oe_data_build { #oe_xdata_build
818 my ( $name, $val ) = @_;
819  
820 my $tag = oEdtk::TexTag->new( $name, $val );
821 return $tag->emit();
822 }
823  
824 sub oe_app_usage() { # migrate oe_app_usage
825 my $app = "";
826 $0 =~ /([\w-]+[\.plmex]*$)/;
827 $1 ? $app = "application.pl" : $app = $1;
828 print STDOUT <<"EOF";
829  
830 Usage: $app </source/input/file.dat> [job] [options]
831 Usage: $app --noinputfiles [job] [options]
832 options :
833 --massmail to confirm mass treatment
834 --edms to confirm edms treatment
835 --cgi
836 these values depend on ED_REFIDDOC config table
837 (example : omgr treatment confirmation)
838  
839 --input_code input caracters encoding
840 (ie : --input_code=iso-8859-1)
841 --noinputfiles no data file needed for treatment
842 --help this message
843  
844 EOF
845  
846 # --notracking halt tracking, do not track
847 oe_list_encodings();
848 exit 1;
849 }
850  
851 # XXX Global variable used to remember stuff from oe_new_job() when we
852 # are in oe_compo_link(). It would be *much* better to keep state in an
853 # object instance instead.
854 my $_RUN_PARAMS;
855  
856 sub oe_new_job {
857 @ARGV =
858 ( @ARGV, @_ ); # optionally override options with the oe_new_job parameters for GetOptions
859 my $cfg = config_read('COMPO');
860 my $params = {};
861  
862 # DEFAULT OPTION VALUES.
863 my %defaults = (
864  
865 # xls => 0,
866 # tex => 0,
867 index => 0,
868 massmail => 0,
869 edms => 0,
870 cgi => 0,
871 input_code => 0
872 );
873  
874 # examples of adding parameters at launch
875 # oe_new_job('--index');
876 # oe_new_job("--input_code=utf8");
877  
878 GetOptions( \%defaults, 'help', 'index', 'massmail', 'edms', 'cgi', 'noinputfiles',
879 'input_code=s' );
880 while ( my ( $key, $val ) = each(%defaults) ) {
881 if ( !defined( $params->{$key} ) ) {
882 $params->{$key} = $val;
883 }
884 }
885  
886 if ( $^O ne 'MSWin32' ) {
887 $defaults{'fifo'} = 1;
888 }
889 else {
890 $defaults{'fifo'} = 0;
891 }
892  
893 $params->{'doclib'} = _omngr_doclib();
894 $params->{'idldoc'} = oe_ID_LDOC();
895  
896 $params->{'outfile'} = $cfg->{'EDTK_PRGNAME'} . ".txt"; # should be tied to TexMode
897 $params->{'output_code'} = $cfg->{'EDTK_OUT_ENCODING'} || 'utf8';
898 $params->{'output_code'} = ">:encoding(" . $params->{'output_code'} . ")";
899 if ( $params->{'input_code'} ) {
900 $params->{'input_code'} = "<:encoding(" . $params->{'input_code'} . ")";
901 }
902 else {
903 $params->{'input_code'} = "<";
904 }
905  
906 my $fi;
907 if ( $defaults{help} ) {
908 &oe_app_usage();
909 exit 0;
910 }
911 elsif ( $defaults{noinputfiles} ) {
912 $fi = 0;
913 warn "INFO: no input file for this treatment\n";
914 }
915 elsif ( $#ARGV == -1 ) { # TO KEEP COMPATIBILITY
916 &oe_app_usage();
917 exit 0;
918 }
919 else {
920 $fi = $ARGV[0]; # TO KEEP COMPATIBILITY
921 open( IN, $params->{'input_code'}, $fi ) ## no critic (InputOutput::ProhibitBarewordFileHandles)
922 or die "ERROR: Cannot open \"$fi\" for reading: $!\n";
923 warn "INFO: input perl data is $fi (encode \'"
924 . $params->{'input_code'}
925 . "\' $ARGV[-1])\n";
926 }
927  
928 # Override default setting if EDTK_COMPO_ASYNC is set in edtk.ini.
929 my $async = $cfg->{'EDTK_COMPO_ASYNC'};
930 if ( defined($async) && $async =~ /^yes$/i ) {
931 $params->{'fifo'} = 1;
932 }
933 elsif ( defined($async) && $async =~ /^no$/i ) {
934 $params->{'fifo'} = 0;
935 }
936  
937 if ( $params->{'fifo'} && $^O eq 'MSWin32' ) {
938 warn "INFO: FIFO mode is not possible under Windows, ignoring.\n";
939 $params->{'fifo'} = 0;
940 }
941  
942 # If we are in FIFO mode and there is a left-over text file, the mkfifo()
943 # call would fail. If we are not in FIFO mode and there's a left-over FIFO,
944 # we would hang indefinitely, so make sure to remove this file first.
945 unlink( $params->{'outfile'} );
946  
947 # Handle options passed in the EDTK_OPTIONS environment variable.
948 if ( exists( $ENV{'EDTK_OPTIONS'} ) ) {
949 my @opts = split( ',', $ENV{'EDTK_OPTIONS'} );
950 foreach my $opt (@opts) {
951 $params->{$opt} = 1;
952 }
953 }
954  
955 if ( $params->{'fifo'} ) {
956 warn "INFO: Creating FIFO for output data file (" . $params->{'outfile'} . ")\n";
957 mkfifo( $params->{'outfile'}, oct('700') ) or die "ERROR: Could not create fifo : $!\n";
958 my $pid = oe_compo_run( $cfg->{'EDTK_PRGNAME'}, $params );
959 $params->{'pid'} = $pid;
960 }
961  
962 open( OUT, $params->{'output_code'}, $params->{'outfile'} ) ## no critic (InputOutput::ProhibitBarewordFileHandles)
963 or die "ERROR: Cannot open \'" . $params->{'outfile'} . "\' for writing: $!\n";
964 warn "INFO: input compo data is "
965 . $params->{'outfile'}
966 . " (encode \'"
967 . $params->{'output_code'} . "\')\n";
968  
969 # Remember for later use in oe_compo_link() & oEdtk::Main.
970 $_RUN_PARAMS = $params;
971  
972 if ( defined $cfg->{'EDTK_COMPO_INCLUDE'} && $cfg->{'EDTK_COMPO_INCLUDE'} =~ /yes/i ) {
973 print OUT oe_include_build( $cfg->{'EDTK_PRGNAME'} . "." . $cfg->{'EDTK_EXT_COMPO'},
974 'EDTK_DIR_SCRIPT' );
975 }
976 print OUT oe_data_build( oe_corporation_tag() );
977 print OUT oe_data_build( 'xIdLdoc', $params->{'idldoc'} );
978 print OUT oe_data_build('xDebFlux');
979 print OUT oe_data_build( 'xAppRef', $cfg->{'EDTK_PRGNAME'} );
980 print OUT oe_data_build( 'xDOCLIB', $params->{'doclib'} );
981  
982 my $env = $cfg->{'EDTK_TYPE_ENV'};
983 if ( $env ne 'Production' ) {
984  
985 # Generate the 'TEST EDITION' watermark.
986 print OUT oe_data_build( 'xWaterM', $cfg->{'EDTK_WATERMARKTEXT'} || ' ' );
987 print OUT oe_data_build('xTstApp');
988 }
989 else {
990 # No watermark.
991 print OUT oe_data_build('xProdApp');
992 }
993 print OUT oe_data_build( 'xTYPPROD', substr( $env, 0, 1 ) );
994 print OUT oe_data_build( 'xHOST', hostname() );
995  
996 # Do we want to generate an index file?
997 if ( $params->{'index'} ) {
998 print OUT oe_data_build('xStOmgr');
999 print OUT oe_data_build( 'xHost', hostname() );
1000 }
1001 print OUT $TAG_COMMENT;
1002 print OUT "\n";
1003 }
1004  
1005 # True when the dissemination-plan URL is configured and carries a non-blank
1006 # value: the one switch that lets a 'call-plan' run reach the service. Sites
1007 # that do not run a dissemination plan leave the key absent, so the call stays
1008 # inert (the mainline behaviour).
1009 sub _dissemination_plan_url_set {
1010 my $cfg = shift;
1011 my $url = $cfg->{'DISSEMINATION_PLAN_URL'};
1012 return ( defined $url && $url =~ /\S/ ) ? 1 : 0;
1013 }
1014  
1015 sub oe_compo_link { # migrate oe_close_files oe_compo_link
1016 # IF THE INPUT STREAM HAS LESS THAN 1 LINE (variable $.), EXIT WITH ERROR
1017 # if ($. == 0) {
1018 # # INVALID STREAM, STOP
1019 # die "ERROR: uncomplete datastream\n $message \n\n";
1020 #}
1021  
1022 my @opt = @_;
1023  
1024 my $cfg = config_read('COMPO');
1025 my $params = $_RUN_PARAMS;
1026 $params->{'corp'} = oe_corporation_set();
1027 if (@opt) {
1028 foreach (@opt) {
1029 $_ =~ s/\-+//g;
1030 $params->{$_} = 1;
1031 }
1032 }
1033  
1034 print OUT oe_data_build('xFinFlux');
1035 close(OUT) or die "ERROR: closing output $!\n";
1036 if ( $params->{'noinputfiles'} ) {
1037 }
1038 else {
1039 close(IN) or die "ERROR: closing input $!\n";
1040 }
1041  
1042 if ( $params->{'fifo'} ) {
1043  
1044 # Disable signal handler.
1045 $SIG{'CHLD'} = 'DEFAULT';
1046 if ( !defined( $params->{'cldstatus'} ) ) {
1047  
1048 # Wait for the LaTeX process to terminate.
1049 my $pid = $params->{'pid'};
1050 warn "INFO: Waiting for the LaTeX process to terminate ($pid)...\n";
1051 my $kid = waitpid( $pid, 0 );
1052 if ( $kid <= 0 ) {
1053 die "ERROR: Could not collect child process status: $!\n";
1054 }
1055 $params->{'cldstatus'} = $?;
1056 }
1057 my $status = $params->{'cldstatus'};
1058 if ( $status != 0 ) {
1059 my $msg = oe_status_to_msg($status);
1060 die "ERROR: LaTeX process failed: $msg\n";
1061 }
1062 warn "INFO: The LaTeX process terminated successfully.\n";
1063 }
1064 else {
1065 # Run the LaTeX process.
1066 oe_compo_run( $cfg->{'EDTK_PRGNAME'}, $params );
1067 }
1068 oe_after_compo( $cfg->{'EDTK_PRGNAME'}, $params );
1069  
1070 # Dissemination plan: only when the caller opted in (and did not veto),
1071 # and the service URL is configured. The delegate loads oEUser on demand,
1072 # so a missing companion distribution never breaks the oEdtk load.
1073 if ( $params->{'call-plan'} && !defined $params->{'nocallplan'} ) {
1074 if ( _dissemination_plan_url_set($cfg) ) {
1075 require oEdtk::DisseminationPlan;
1076 my $app = $params->{'app-ref'};
1077 my $id_lot = $params->{'idldoc'};
1078 defined $app or croak "ERROR: no 'app-ref' in params\n";
1079 defined $id_lot or croak "ERROR: no 'idldoc' in params\n";
1080 oEdtk::DisseminationPlan::idx1_app_idlot( $cfg, $app, $id_lot,
1081 $params->{'forced-paper'} );
1082 }
1083 else {
1084 warn "INFO: not calling the dissemination plan (DISSEMINATION_PLAN_URL absent)\n";
1085 }
1086 }
1087  
1088 return 1;
1089 }
1090  
1091 ## no critic (ProhibitSubroutinePrototypes)
1092 sub oe_env_var_completion (\$) {
1093  
1094 # expand paths by replacing environment variables with their real values
1095 # all nesting levels defined in the environment variables are expanded
1096 # requires the environment variables to be defined beforehand
1097 my $rValue = shift;
1098 if ( $^O eq "MSWin32" ) {
1099  
1100 # environment variables may themselves contain variables
1101 while ( ${$rValue} =~ /\$/g ) {
1102 ${$rValue} =~ s/\$(\w+)/${ENV{$1}}/g;
1103 }
1104 ${$rValue} =~ s/(\/)/\\/g;
1105  
1106 }
1107 else {
1108 # CHECK COMPATIBILITY UNDER *NIX
1109 while ( ${$rValue} =~ /\$/g ) {
1110 ${$rValue} =~ s/\$(\w+)/${ENV{$1}}/g;
1111 }
1112 }
1113 return ${$rValue};
1114 }
1115  
1116 # Maximum length accepted for a forced document id (a 36-char UUID; S70, D1).
1117 use constant IDLDOC_MAX_LEN => 36;
1118  
1119 sub oe_ID_LDOC {
1120 my $force_ID = shift;
1121  
1122 # document batch id: a 36-char UUID by default (S70, D1). A forced id (the
1123 # -iddoc option, or the witnesses' SETIDLOT) still wins. The id is generated
1124 # only once per run: several calls in the same instance return the same id.
1125 # EDTK_IDLDOC_FORMAT=LEGACY (or the alias =old) restores the 16-digit
1126 # YWWWDHHMMSSPPPP.r format.
1127 if ( $_ID_LDOC eq '' ) {
1128  
1129 if ( defined $force_ID ) {
1130 if ( length $force_ID > IDLDOC_MAX_LEN ) {
1131 die "ERROR: forced ID_LDOC too long (>" . IDLDOC_MAX_LEN . " car) : $force_ID \n";
1132 }
1133 $_ID_LDOC = $force_ID;
1134  
1135 }
1136 elsif ( _idldoc_format() eq 'LEGACY' ) {
1137 $_ID_LDOC = _idldoc_legacy_new();
1138  
1139 }
1140 else {
1141 oe_new_ID_LDOC();
1142  
1143 }
1144  
1145 }
1146  
1147 return $_ID_LDOC;
1148 }
1149  
1150 # The mainline (M) 16-digit id YWWWDHHMMSSPPPP.r, kept for
1151 # EDTK_IDLDOC_FORMAT=LEGACY (or its 'old' alias).
1152 sub _idldoc_legacy_new {
1153 my $time = time;
1154 my ( $year, $month, $day, $hour, $min, $sec, $doy, $dow, $dst ) = Gmtime($time);
1155 my ( $week, ) = Week_of_Year( $year, $month, $day );
1156  
1157 my $pid = "$$";
1158 my $rnd = int( rand(10) );
1159 if ( length $pid > 5 ) {
1160 $pid = $pid / ( 10**( ( length $pid ) - 5 ) );
1161 }
1162  
1163 return sprintf( "%1d%02d%1d%02d%02d%02d%05d%1d",
1164 $year % 10, $week, $dow, $hour, $min, $sec, $pid, $rnd );
1165 }
1166  
1167 # EDTK_IDLDOC_FORMAT: 'UUID' (default) or 'LEGACY' (the 16-digit mainline id).
1168 # 'old' is an accepted spelling of 'LEGACY' (case-insensitive), normalised here
1169 # so oe_ID_LDOC tests a single value. Read once per process: config_read is
1170 # not cached, and oe_ID_LDOC is called from contexts that carry no $cfg
1171 # (Tracking, EDMS, ...).
1172 sub _idldoc_format {
1173 unless ( defined $_IDLDOC_FORMAT ) {
1174 my $cfg = eval { config_read('COMPO') } || {};
1175 my $val = ref $cfg ? $cfg->{'EDTK_IDLDOC_FORMAT'} : undef;
1176 my $fmt = ( defined $val && $val =~ /\S/ ) ? uc($val) : 'UUID';
1177 $fmt = 'LEGACY' if $fmt eq 'OLD';
1178 $_IDLDOC_FORMAT = $fmt;
1179 }
1180 return $_IDLDOC_FORMAT;
1181 }
1182  
1183 # A document batch id (idldoc). Since S70/D1 it is a 36-char UUID; the legacy
1184 # 16-digit YWWWDHHMMSSPPPP.r form is still produced under
1185 # EDTK_IDLDOC_FORMAT=LEGACY (or its 'old' alias). Kept in this module so the
1186 # CLI tools that classify a user-supplied id (see lib/index_Block_refs.pl)
1187 # share one definition.
1188 sub oe_is_IDLDOC {
1189 my $value = shift;
1190 return 0 unless defined $value;
1191 return $value =~ /^[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$/
1192 || $value =~ /^\d{16}$/;
1193 }
1194  
1195 {
1196 my $_app_typ_trt; # batching processing type,
1197 # value accessible only through the _app_typ_trt method
1198  
1199 sub _app_typ_trt {
1200  
1201 # designation of the batching processing type (Output Management)
1202 # if the function is called with a parameter, assign it to $_app_typ_trt
1203 # if the function is called alone, just return the normalized value
1204 # by default the value is 'U' for 'undef'
1205 # THE VALUE CANNOT BE CHANGED DURING PROCESSING, EXCEPT to switch to Test or Debug
1206 # possible values:
1207 # - 'M' -> Mass processing with batching
1208 # - 'G' -> reGrouping processing, batching pending
1209 # - 'L' -> Local edition processing without batching
1210 # - 'H' -> homologation processing without batching
1211 # - 'T' -> test/homologation processing, batching test possible
1212 # - 'D' -> Debug mode, keep intermediate files
1213 # - 'U' -> 'undef' processing without batching
1214  
1215 # Run types (Mass/Grouped/Local/Homol/Test/Debug/Undef) handled in 3 groups:
1216 # - MTD -> do batching
1217 # - G -> batching pending
1218 # - LHU -> do no batching
1219 # - D -> does not delete intermediate files
1220 # - U -> default mode
1221 # - H -> mode tied to the 'Homologation' extension (-V2)
1222  
1223 # New run handling based on EDTK_TYPE_ENV:
1224 # EDTK_TYPE_ENV = Production -> cleanup, if indexed mode: determine the trt from EDTK_REFIDDOC
1225 # EDTK_TYPE_ENV = Integration -> cleanup, banner, if indexed mode: determine the trt from EDTK_REFIDDOC
1226 # EDTK_TYPE_ENV = Test -> banner, if indexed mode: determine the trt from EDTK_REFIDDOC
1227 # EDTK_TYPE_ENV = Development -> cleanup, banner, 'short' processing
1228  
1229 my $xTypTrt = shift || '';
1230 if ( defined $_app_typ_trt && $xTypTrt !~ /^[TD]/i ) { return $_app_typ_trt; }
1231  
1232 # only the Test and Debug types allow changing $_app_typ_trt if it is already set
1233  
1234 if ( $xTypTrt !~ /^([MGLHTDU])/i ) {
1235 $_app_typ_trt = 'U';
1236  
1237 }
1238 elsif ( $xTypTrt =~ /^([MGL])/i ) {
1239 $_app_typ_trt = $1;
1240  
1241 }
1242 elsif ( $xTypTrt =~ /^([HTD])/i ) {
1243 $_app_typ_trt = $1;
1244 }
1245  
1246 warn
1247 "INFO: OM processing type = $_app_typ_trt (Mass/Grouped/Local/Homol/Test/Debug/Undef)\n";
1248 return $_app_typ_trt;
1249 }
1250 }
1251  
1252 {
1253 my $_DOCLIB; # DCLIB DESIGNATION for batching
1254 # value accessible only through the _omngr_doclib method
1255  
1256 sub _omngr_doclib {
1257 if ( defined $_DOCLIB ) { return $_DOCLIB; }
1258  
1259 my $doclib = shift;
1260 if ( !defined $doclib ) {
1261 my $cfg = config_read('ENVDESC');
1262 my $ext = shift || $cfg->{'EDTK_EXT_DEFAULT'};
1263 $_DOCLIB = "DCLIB_" . oe_ID_LDOC() . "." . $ext;
1264  
1265 #$_DOCLIB =~ s/\./_/;
1266 }
1267 else {
1268 $_DOCLIB = $doclib;
1269 }
1270  
1271 return $_DOCLIB;
1272 }
1273 }
1274  
1275 #sub user_corp_file_prefixe($;$){
1276 # my($filename, $directories, $suffix) = fileparse(shift);
1277 # my $sep = shift || '.';
1278 # my @prefix = split (/$sep/, $filename);
1279 # oe_corporation_set ($prefix[0]);
1280 # # warn "$filename \$prefix[0] $prefix[0] -> ". oe_corporation_set()."\n";
1281 #1;
1282 #}
1283  
1284 sub oe_corporation_tag() {
1285 return ( sprintf( "x%.7s", oe_corporation_set() ) );
1286 }
1287  
1288 my $_xCORPOR;
1289 my $_DICT;
1290  
1291 sub oe_corporation_get() {
1292 return $_xCORPOR;
1293 }
1294  
1295 sub oe_corporation_set {
1296  
1297 # DICTIONARY USE:
1298 # - if the parameter is known in the dictionary => dictionary value
1299 # - if the parameter is unknown => default value (edtk.ini / EDTK_CORP)
1300 # - if no parameter => last known value
1301 my $parametre = shift;
1302  
1303 if ( !defined($_DICT) ) {
1304 my $cfg = config_read();
1305 $_xCORPOR = $cfg->{'EDTK_CORP'}; # Default value
1306 $_DICT = oEdtk::Dict->new( $cfg->{'EDTK_DICO'}, { invert => 1 } );
1307 }
1308  
1309 my $entity;
1310 if ( defined($parametre) ) {
1311 $entity = $parametre;
1312 }
1313 else {
1314 $entity = $_xCORPOR;
1315 }
1316  
1317 $entity = $_DICT->translate( $entity, 1 );
1318  
1319 if ( defined($entity) ) {
1320  
1321 # if the value was found in the dictionary
1322 $_xCORPOR = $entity;
1323 }
1324  
1325 # warn "\$entity $entity \$_xCORPOR $_xCORPOR\n";
1326 return $_xCORPOR;
1327 }
1328  
1329 { # in progress, not operational yet (recovery from the generator)
1330 my $cpt_sub_call = 0; # constant variable local to the function
1331 my %hListeId;
1332  
1333 sub oe_unique_data_name {
1334  
1335 # define a unique identifier over n characters
1336 # the first 6 characters of the passed key are extracted
1337 # if the id is already known, take the first 4 and add a 3-digit counter (matches the call sequence)
1338 # if it is still not unique, take the first 3 characters and complete the 3-digit counter with a character
1339 # receives: - the total number of characters to return
1340 # - an identifier
1341 # - optional: a reference to a counter value (3 numeric)
1342  
1343 my ( $nb_car, $id, $cpt_value ) = @_;
1344 if ( $nb_car lt 6 ) { $nb_car = 6; }
1345  
1346 if ($cpt_value) { $cpt_sub_call = $cpt_value }
1347 else { $cpt_sub_call++ }
1348  
1349 my $debut = $nb_car - 2;
1350 my $motif = "%-" . $debut . "." . $debut . "s%0.2d"; # "%-4.4s%0.2d"
1351 warn "$motif / $id\n";
1352 $id = sprintf( "$motif", $id );
1353 $id =~ s/\s/x/g;
1354  
1355 if ( exists( $hListeId{$id} ) ) {
1356 $debut = $nb_car - 3;
1357 $motif = "%-" . $debut . "." . $debut . "s%0.3d"; # "%-3.3s%0.3d"
1358 $id = sprintf( $motif, $id, $cpt_sub_call );
1359  
1360 my $cpt = 97; # for the character "a"
1361 while ( exists( $hListeId{$id} ) ) {
1362 $debut = $nb_car - 4;
1363 $motif = "%-" . $debut . "." . $debut . "s%0.3d"; # "%-3.3s%0.3d"
1364 $id = sprintf( $motif, $id, $cpt_sub_call, chr( $cpt++ ) );
1365 die "ERROR: cannot create a unique key" if ( $cpt >= 123 );
1366  
1367 # use Log::Log4perl;
1368 # Log::Log4perl->init("log.conf"); => read log.conf
1369 # $logger = Log::Log4perl->get_logger("");
1370 # $logger->logdie("cannot create a unique key") if ($cpt >= 123);
1371 # $logger->trace("..."); # Log a trace message
1372 # $logger->debug("..."); # Log a debug message
1373 # $logger->info("..."); # Log a info message
1374 # $logger->warn("..."); # Log a warn message / $logger->error_warn("..."); (includes the call to warn() )
1375 # $logger->error("..."); # Log a error message / $logger->logdie ("..."); (includes the call to die() )
1376 # $logger->fatal("..."); # Log a fatal message
1377 }
1378 }
1379 $hListeId{$id} = 1;
1380 return $id;
1381 }
1382 }
1383  
1384 {
1385 my $_backup_date;
1386  
1387 sub oe_set_sys_date {
1388 my $requested_date = shift;
1389  
1390 my $time = time;
1391 my ( $year, $month, $day, $hour, $min, $sec, $doy, $dow, $dst ) = Gmtime($time);
1392  
1393 my $commande = sprintf( "date %s", $requested_date );
1394 warn "INFO: $commande\n";
1395  
1396 eval { system($commande); };
1397  
1398 # if ($?){
1399 if ($@) {
1400 warn "ERROR: command failed $commande : $@\n";
1401 return -1;
1402 }
1403  
1404 if ( !defined $_backup_date ) {
1405 $_backup_date = sprintf( "%02s-%02s-%02s", $day, $month, $year );
1406 }
1407 return $_backup_date;
1408 }
1409  
1410 sub _restore_sys_date {
1411 oe_set_sys_date($_backup_date) if ( defined $_backup_date );
1412 1;
1413 }
1414 }
1415  
1416 # Return the handle to the output file, croaking if it was not opened yet.
1417 sub _oe_get_handle_to_output_file {
1418 my $fh = openhandle(*OUT);
1419 if ( !defined $fh ) {
1420 croak
1421 "You tried to use the handle to the output file. However, the output file has not been opened yet!";
1422 }
1423 return $fh;
1424 }
1425  
1426 # Return the handle to the input file (the file that holds the Infinite flux).
1427 # @note The IN handle should not be accessed directly from outside this module
1428 # (all the more so as a global variable!).
1429 # @TODO write a function oe_read_from_input_file().
1430 sub oe_get_handle_to_input_file {
1431 my $fh = openhandle(*IN);
1432 if ( !defined $fh ) {
1433 croak
1434 "You tried to use the handle to the input file. However, the input file has not been opened yet!";
1435 }
1436 return $fh;
1437 }
1438  
1439 # Print a text into the output file.
1440 # @param [string] $in_text text to print.
1441 # @note all actions on the output file should go through an "output adaptor"
1442 # implemented as a plugin (a class implementing an interface).
1443 sub oe_print_to_output_file {
1444 my $in_text = shift;
1445 croak 'in_text undef' if !defined $in_text;
1446 my $fh = _oe_get_handle_to_output_file();
1447 return print $fh $in_text;
1448 }
1449  
1450 # Print a text into the "output debug file".
1451 # @param [string] $in_text text to print.
1452 # @note the behaviour of this function can be configured through the
1453 # environment variables listed below:
1454 # - MNT_OUTPUT_DUMP_MODE: activate or deactivate the recording (0: off, 1: on).
1455 # - MNT_OUTPUT_DUMP_PATH: the path to the file used to store the recorded data.
1456 # both environment variables have default values (see
1457 # $_DEFAULT_OUTPUT_DUMP_MODE and $_DEFAULT_OUTPUT_DUMP_FILE).
1458 sub _dump {
1459 my ($in_text) = @_;
1460  
1461 my $dump_mode =
1462 exists $ENV{MNT_OUTPUT_DUMP_MODE} && defined $ENV{MNT_OUTPUT_DUMP_MODE}
1463 ? $ENV{MNT_OUTPUT_DUMP_MODE}
1464 : $_DEFAULT_OUTPUT_DUMP_MODE;
1465 if ( !$dump_mode ) {
1466 return;
1467 }
1468  
1469 my $dump_path =
1470 exists $ENV{MNT_OUTPUT_DUMP_PATH} && defined $ENV{MNT_OUTPUT_DUMP_PATH}
1471 ? $ENV{MNT_OUTPUT_DUMP_PATH}
1472 : $_DEFAULT_OUTPUT_DUMP_FILE;
1473 use open ':encoding(iso-8859-15)';
1474 open( my $fd, '>>', $dump_path )
1475 or die sprintf(
1476 'The module "%s::Main" is configured to record all text written to the output file. Can not open the dump file "%s": %s.',
1477 __PACKAGE__, $dump_path, $! );
1478 printf $fd "%s\n", $in_text;
1479 close($fd)
1480 or die sprintf(
1481 'The module "%s::Main" is configured to record all text written to the output file. Can not close the dump file "%s": %s.',
1482 __PACKAGE__, $dump_path, $! );
1483 }
1484  
1485 # Dictionary of the applications' backgrounds.
1486 my $_DICO_BACKGROUNDS;
1487  
1488 sub oe_backgrounds_apps {
1489 my ($section) = @_;
1490  
1491 my $cfg = config_read();
1492 if ( !defined($_DICO_BACKGROUNDS) ) {
1493 $_DICO_BACKGROUNDS =
1494 oEdtk::Dict->new( $cfg->{'EDTK_APPS_BACKGROUNDS'}, { section => $section } );
1495 }
1496 return $_DICO_BACKGROUNDS->translate( $cfg->{EDTK_PRGNAME} );
1497 }
1498  
1499 # Clean up an address line in place to build the recipient address blocks.
1500 # It works on the reference to the variable and also returns the resulting string.
1501 ## no critic (ProhibitSubroutinePrototypes)
1502 sub oe_clean_addr(\$) {
1503 my $rLine = shift;
1504  
1505 # default value when the field is undef
1506 if ( !defined($$rLine) || length($$rLine) == 0 ) {
1507 $$rLine = '';
1508 return $$rLine;
1509 }
1510  
1511 chomp($$rLine); # make sure there is no trailing newline
1512 oe_trimp_space($rLine);
1513  
1514 $$rLine = oe_char_xlate( $$rLine, 'ADDRESS' );
1515  
1516 # TODO: a regular expression turning every non 0-9\-\w character into blanks... XXX
1517  
1518 $$rLine =~ s/^\s+//; # left trim: drop leading blanks
1519 $$rLine =~ s/\s+$//; # right trim: drop trailing blanks
1520 $$rLine =~ s/^0\s+//; # drop a lone leading zero (after the trims)
1521 $$rLine =~ s/\s+/ /; # collapse consecutive blanks
1522 $$rLine =~ s/(\s{1}\W{1}){2}/$1/; # drop a blank followed by a non-alphanumeric
1523 $$rLine =~ s/\W+$//; # drop trailing non-alphanumeric characters
1524  
1525 return $$rLine;
1526 }
1527  
1528 # Production type: the first letter of the EDTK_TYPE_ENV configuration value.
1529 sub oe_typ_prod {
1530 my ($cfg) = @_;
1531 $cfg //= config_read();
1532 my $env = $cfg->{'EDTK_TYPE_ENV'} // croak 'Env. var. EDTK_TYPE_ENV undef';
1533 return substr( $env, 0, 1 );
1534 }
1535  
1536 # Create a new "job definition" and, if needed, run asynchronously the process
1537 # that produces the output (pdf) file. When run asynchronously the "job
1538 # definition" is a "FIFO file", otherwise it is a text file (.txt).
1539 # The job file name carries the application name (e.g. "PRACI-AC014.txt") and is
1540 # reachable through the global file handle OUT.
1541 # @param [array] a list of command line options: --help, --index, --edms,
1542 # --bpdf, --cgi, --noinputfiles, --input_code=s (e.g. utf8).
1543 # @note the input data file (generated by Infinite) is opened and reachable
1544 # through the global file handle IN.
1545 sub oe_new_job_input_file {
1546 my $params = oe_params();
1547  
1548 if ( $params->{'input_code'} ) {
1549 $params->{'input_code'} = "<:encoding(" . $params->{'input_code'} . ")";
1550 }
1551 else {
1552 $params->{'input_code'} = "<";
1553 }
1554  
1555 my $fi;
1556 if ( $params->{help} ) {
1557 oe_app_usage();
1558 exit 0;
1559 }
1560 elsif ( $params->{noinputfiles} ) {
1561 $fi = 0;
1562 warn "INFO: no input file for this treatment\n";
1563 }
1564 elsif ( !scalar @ARGV ) { # TO KEEP COMPATIBILITY
1565 oe_app_usage();
1566 exit 0;
1567 }
1568 else {
1569 $fi = $ARGV[0]; # TO KEEP COMPATIBILITY
1570 $params->{'inputfile'} = $fi;
1571  
1572 open( IN, $params->{input_code}, $fi ) ## no critic (InputOutput::ProhibitBarewordFileHandles)
1573 or die sprintf( 'Cannot open the input file "%s": %s', $fi, $! );
1574 warn "INFO: input perl data is $fi (encode '" . $params->{'input_code'} . "' $ARGV[-1])\n";
1575 }
1576  
1577 return;
1578 }
1579  
1580 sub oe_new_job_output_file {
1581 my $params = oe_params();
1582 my $cfg = oe_config_compo();
1583  
1584 $params->{'outfile'} = $cfg->{'EDTK_PRGNAME'} . ".txt"; # should be tied to TexMode
1585 $params->{'output_code'} = $cfg->{'EDTK_OUT_ENCODING'} || 'utf8';
1586 $params->{'output_code'} = ">:encoding(" . $params->{'output_code'} . ")";
1587  
1588 # Override default setting if EDTK_COMPO_ASYNC is set in edtk.ini.
1589  
1590 if ( exists $cfg->{'EDTK_COMPO_ASYNC'}
1591 && defined $cfg->{'EDTK_COMPO_ASYNC'}
1592 && $cfg->{'EDTK_COMPO_ASYNC'} )
1593 {
1594 my $async = $cfg->{'EDTK_COMPO_ASYNC'};
1595 if ( $async =~ /^yes$/i ) {
1596 $params->{'fifo'} = 1;
1597 }
1598 elsif ( $async =~ /^no$/i ) {
1599 $params->{'fifo'} = 0;
1600 }
1601 else {
1602 die sprintf
1603 'Unexpected value for configuration tag EDTK_COMPO_ASYNC: "%s"',
1604 $async;
1605 }
1606 }
1607  
1608 if ( $params->{'fifo'} ) {
1609 if ( ( exists $cfg->{EDTK_FIFO_MODE} )
1610 && ( $cfg->{EDTK_FIFO_MODE} eq 'NONE' ) )
1611 {
1612 warn "INFO: Deactivating FIFO MODE, as requested in the configuration";
1613 $params->{'fifo'} = 0;
1614 }
1615 elsif ( $^O eq 'MSWin32' ) {
1616 warn "INFO: FIFO mode is not possible under Windows, ignoring.\n";
1617 $params->{'fifo'} = 0;
1618 }
1619 }
1620  
1621 # In FIFO mode a left-over text file makes mkfifo() fail; without FIFO mode a
1622 # left-over FIFO would hang us indefinitely, so remove it first.
1623 if ( -e $params->{'outfile'} ) {
1624 unlink( $params->{'outfile'} )
1625 or die( sprintf 'Cannot remove the file "%s": %s', $params->{'outfile'}, $! );
1626 }
1627  
1628 # start the LaTeX engine when the FIFO mode is activated.
1629 if ( $params->{'fifo'} ) {
1630 mkfifo( $params->{'outfile'}, oct(700) )
1631 or die
1632 sprintf( 'ERROR: Could not create fifo in file "%s": %s', $params->{'outfile'}, $! );
1633 my $pid = oe_compo_run( $cfg->{'EDTK_PRGNAME'}, $params );
1634 $params->{'pid'} = $pid;
1635 }
1636  
1637 # create the output file "/path/to/lateX/file.tex".
1638 _dump( sprintf "\n%%\n%% ==> %s <==\n%%\n%%", $params->{outfile} );
1639 open( OUT, $params->{output_code}, $params->{outfile} ) ## no critic (InputOutput::ProhibitBarewordFileHandles)
1640 or die sprintf 'Can not open the output file "%s": %s', $params->{outfile}, $!;
1641 warn sprintf( 'INFO: input compo data is "%s" (encode is "%s".',
1642 $params->{'outfile'}, $params->{'output_code'} );
1643 return;
1644 }
1645  
1646 sub oe_watermark {
1647 my ($cfg) = @_;
1648 $cfg //= config_read('COMPO');
1649 return $cfg->{'EDTK_WATERMARKTEXT'} || q{ }; # XXX //?
1650 }
1651  
1652 # Getter (no argument) / setter (a hash ref) for the run parameters.
1653 sub oe_params {
1654 my ($params) = @_;
1655 state $_RUN_PARAMS;
1656 if ( defined $params ) {
1657 $_RUN_PARAMS = $params;
1658 }
1659 else {
1660 return $_RUN_PARAMS;
1661 }
1662 }
1663  
1664 # The COMPO configuration, read once per run.
1665 sub oe_config_compo {
1666 state $_RUN_CFG = config_read();
1667 return $_RUN_CFG;
1668 }
1669  
1670 sub oe_options {
1671 my (@args) = @_;
1672 my $params = oe_params(); # read (getter)
1673 my $cfg = oe_config_compo();
1674 return ( $params, $cfg ) if defined $params;
1675 $params = {};
1676  
1677 # load all configuration parameters that describe the publication
1678 # environment: EDTK_BIN_COMPO, EDTK_COMPO, EDTK_COMPO_CMD_PDF...
1679 my $defaults = {%DEFAULT_OPTIONS};
1680 GetOptionsFromArray(
1681 [ @ARGV, @args ], $defaults, 'help', 'index',
1682 'massmail', 'edms', 'bpdf', 'cgi',
1683 'noinputfiles', 'input_code=s', 'iddoc=s', 'nocallplan',
1684 'forced-paper'
1685 );
1686 while ( my ( $key, $val ) = each( %{$defaults} ) ) {
1687 $params->{$key} //= $val;
1688 }
1689 $params->{'doclib'} = _omngr_doclib();
1690 if ( exists $params->{'iddoc'} ) {
1691 $_ID_LDOC = $params->{'iddoc'};
1692 }
1693 $params->{'idldoc'} = oe_ID_LDOC();
1694  
1695 $params->{'type-prod'} = oe_typ_prod($cfg);
1696 $params->{'HOST-NAME'} = hostname();
1697 $params->{'app-ref'} = $cfg->{'EDTK_PRGNAME'};
1698 if ( $params->{'index'} ) {
1699 $params->{'activate-lotissement'} = 1;
1700 $params->{'Host-name'} = hostname();
1701 }
1702 $defaults->{'fifo'} = ( $^O eq 'MSWin32' ) ? 0 : 1;
1703 my $env = $cfg->{'EDTK_TYPE_ENV'} // croak "Env. var. 'EDTK_TYPE_ENV' undef";
1704 if ( $env eq 'Production' ) {
1705 $params->{'type-app'} = 'prod';
1706 }
1707 else {
1708 $params->{'watermark'} = oe_watermark($cfg);
1709 $params->{'type-app'} = 'test';
1710 }
1711  
1712 # handle options passed in the EDTK_OPTIONS environment variable.
1713 if ( exists( $ENV{'EDTK_OPTIONS'} ) ) {
1714 my @opts = split( ',', $ENV{'EDTK_OPTIONS'} );
1715 foreach my $opt (@opts) {
1716 $params->{$opt} = 1;
1717 }
1718 }
1719  
1720 oe_params($params); # write (setter)
1721 return ( $params, $cfg );
1722 }
1723  
1724 # Historical name kept as an alias of oe_ID_LDOC (same format until S70).
1725 # The true generator: a fresh UUID on every call (fork F semantics, S70/D1).
1726 # oe_ID_LDOC is the memoized entry point; oe_new_ID_LDOC is exported for the
1727 # callers that genuinely want a new id.
1728 sub oe_new_ID_LDOC {
1729 $_ID_LDOC = Data::UUID->new->create_str();
1730 return $_ID_LDOC;
1731 }
1732  
1733 sub oe_simple_job {
1734 my (@args) = @_;
1735 oe_options(@args);
1736 oe_new_job_input_file();
1737 oe_new_job_output_file();
1738 return ( oe_params(), config_read() );
1739 }
1740  
1741 END {
1742 _restore_sys_date;
1743  
1744 # duplicate with oEdtk.pm :
1745 #warn "(c) 2005-2020 grechary\@cpan.org - edtk\@free.fr - oEdtk v$VERSION\n";
1746 }
1747  
1748 1;
1749  
1750 =head1 NAME
1751  
1752 oEdtk::Main - core helpers for the oEdtk document pipeline
1753  
1754 =head1 SYNOPSIS
1755  
1756 use oEdtk::Main;
1757  
1758 oe_simple_job(@ARGV); # options, input and output files
1759 oe_rec_motif($key, $pattern); # describe a record
1760 oe_process_ref_rec($off, $len, \$line);
1761  
1762 =head1 DESCRIPTION
1763  
1764 The central module of the toolkit. It provides the record template engine
1765 (describe a record, match it in a line, unpack and process it), the address,
1766 text, date and number helpers, the input/output file handling, the
1767 document-batch id generation, and the job run lifecycle (option parsing,
1768 FIFO/LaTeX composition, dissemination). The exported globals C<*IN>, C<*OUT>,
1769 C<@DATATAB> and the C<%motifs>, C<%ouTags>, C<%evalSsTrt> hashes carry the run
1770 state.
1771  
1772 =head1 FUNCTIONS
1773  
1774 =head2 date2time
1775  
1776 date2time($date);
1777  
1778 Deprecated: turn a C<YYYYMMDD> date into an epoch time through C<gmtime>.
1779  
1780 =head2 prodEdtk_Current_Rec
1781  
1782 my $key = prodEdtk_Current_Rec();
1783  
1784 Return the current record identifier.
1785  
1786 =head2 prodEdtk_Previous_Rec
1787  
1788 my $key = prodEdtk_Previous_Rec();
1789  
1790 Return the previous record identifier.
1791  
1792 =head2 prodEtk_rec_cdata_join
1793  
1794 prodEtk_rec_cdata_join($text);
1795  
1796 Append C<$text> to the pending push value.
1797  
1798 =head2 recEdtk_erase
1799  
1800 recEdtk_erase($key);
1801  
1802 Remove every piece of processing registered for the record C<$key>.
1803  
1804 =head2 recEdtk_join_tmplte
1805  
1806 recEdtk_join_tmplte($key, $pattern, $output);
1807  
1808 Register a record's unpack pattern and output format together.
1809  
1810 =head2 recEdtk_post_process
1811  
1812 recEdtk_post_process($key, $code);
1813  
1814 Attach the post-reformat processing C<$code> for the record C<$key>.
1815  
1816 =head2 recEdtk_redefine
1817  
1818 recEdtk_redefine($key, $pattern);
1819  
1820 Reset and redefine the unpack pattern of the record C<$key>.
1821  
1822 =head2 oe_app_usage
1823  
1824 oe_app_usage();
1825  
1826 Print the application usage and exit.
1827  
1828 =head2 oe_backgrounds_apps
1829  
1830 my $set = oe_backgrounds_apps($section);
1831  
1832 Look up the application's background set from C<EDTK_APPS_BACKGROUNDS>.
1833  
1834 =head2 oe_CAP_sans_accents
1835  
1836 oe_CAP_sans_accents(\$string);
1837  
1838 Strip the accents from C<$string> and uppercase it, in place.
1839  
1840 =head2 oe_char_xlate
1841  
1842 my $out = oe_char_xlate($string);
1843  
1844 Apply the character-translation dictionary to C<$string>.
1845  
1846 =head2 oe_clean_addr
1847  
1848 oe_clean_addr(\$string);
1849  
1850 A stricter address cleanup (extra trims and C<\W> removal), in place.
1851  
1852 =head2 oe_clean_addr_line
1853  
1854 oe_clean_addr_line(\$string);
1855  
1856 Clean a 38-character address line (trim, translate, C<EDTK_DICO_POST>), in
1857 place.
1858  
1859 =head2 oe_close_fo
1860  
1861 oe_close_fo($fh);
1862  
1863 Close the output file handle.
1864  
1865 =head2 oe_compo_link
1866  
1867 oe_compo_link(@options);
1868  
1869 Close the files, run (or wait for) LaTeX, and run the post-composition step.
1870  
1871 =head2 oe_corporation_get
1872  
1873 my $corp = oe_corporation_get();
1874  
1875 Return the current corporation.
1876  
1877 =head2 oe_corporation_set
1878  
1879 oe_corporation_set($value);
1880  
1881 Translate and set the corporation from C<$value>.
1882  
1883 =head2 oe_corporation_tag
1884  
1885 my $tag = oe_corporation_tag();
1886  
1887 Return the corporation tag.
1888  
1889 =head2 oe_data_build
1890  
1891 oe_data_build($name, $value);
1892  
1893 Emit a document tag string for C<$name> and C<$value>.
1894  
1895 =head2 oe_date_biggest
1896  
1897 my $date = oe_date_biggest($d1, $d2);
1898  
1899 Return the later of two C<DD/MM/YYYY> dates.
1900  
1901 =head2 oe_date_smallest
1902  
1903 my $date = oe_date_smallest($d1, $d2);
1904  
1905 Return the earlier of two C<DD/MM/YYYY> dates.
1906  
1907 =head2 oe_define_TeX_output
1908  
1909 oe_define_TeX_output();
1910  
1911 Set the output tag delimiters (default backslash, empty, percent).
1912  
1913 =head2 oe_env_var_completion
1914  
1915 oe_env_var_completion(\$path);
1916  
1917 Expand C<$ENV> references inside the path C<$path>, in place.
1918  
1919 =head2 oe_fmt_date
1920  
1921 my $date = oe_fmt_date($date);
1922  
1923 Normalise a C<DD/MM/YY> or C<DD/MM/YYYY> date.
1924  
1925 =head2 oe_get_handle_to_input_file
1926  
1927 my $fh = oe_get_handle_to_input_file();
1928  
1929 Return the input file handle, croaking when it is not open.
1930  
1931 =head2 oe_ID_LDOC
1932  
1933 my $id = oe_ID_LDOC($force);
1934  
1935 Return the memoised document-batch id, optionally forcing a value.
1936  
1937 =head2 oe_is_IDLDOC
1938  
1939 my $ok = oe_is_IDLDOC($value);
1940  
1941 Return true when C<$value> is a valid document-batch id.
1942  
1943 =head2 oe_iso_country
1944  
1945 my $label = oe_iso_country($country);
1946  
1947 Translate a country through the ISO dictionary.
1948  
1949 =head2 oe_list_encodings
1950  
1951 oe_list_encodings();
1952  
1953 Print the encodings available from C<Encode>.
1954  
1955 =head2 oe_new_ID_LDOC
1956  
1957 my $id = oe_new_ID_LDOC();
1958  
1959 Generate a fresh document-batch id (a UUID).
1960  
1961 =head2 oe_new_job
1962  
1963 oe_new_job();
1964  
1965 Legacy job bootstrap: parse the options, open the input, create the output and
1966 emit the header tags.
1967  
1968 =head2 oe_new_job_input_file
1969  
1970 oe_new_job_input_file();
1971  
1972 Open the input file using the run parameters.
1973  
1974 =head2 oe_now_time
1975  
1976 my $stamp = oe_now_time();
1977  
1978 Deprecated: return a C<YYYYMMDDHHMMSS> timestamp.
1979  
1980 =head2 oe_num_sign_x
1981  
1982 my $value = oe_num_sign_x(\$amount, $decimals);
1983  
1984 Decode an alphanumeric signed amount (a trailing C<p>..C<y> letter), in place.
1985  
1986 =head2 oe_num2txt_us
1987  
1988 oe_num2txt_us(\$amount);
1989  
1990 Normalise a display-formatted amount (comma to dot), in place.
1991  
1992 =head2 oe_open_fi_IN
1993  
1994 oe_open_fi_IN($file, $encoding);
1995  
1996 Open the input file (C<IN>), optionally with a given encoding.
1997  
1998 =head2 oe_open_fo_OUT
1999  
2000 oe_open_fo_OUT($file, $encoding);
2001  
2002 Open the output file (C<OUT>), optionally with a given encoding.
2003  
2004 =head2 oe_options
2005  
2006 my ($params, $cfg) = oe_options(@args);
2007  
2008 Parse the command-line options into the run parameters and return them along
2009 with the configuration.
2010  
2011 =head2 oe_params
2012  
2013 my $params = oe_params($params);
2014  
2015 Get, or set, the run parameters.
2016  
2017 =head2 oe_print_to_output_file
2018  
2019 oe_print_to_output_file($text);
2020  
2021 Print C<$text> to the output file.
2022  
2023 =head2 oe_process_ref_rec
2024  
2025 oe_process_ref_rec($key_off, $key_len, \$line, $rec_off, $rec_len);
2026  
2027 Match a record key in C<$line> and process the referenced record.
2028  
2029 =head2 oe_rec_motif
2030  
2031 oe_rec_motif($key, $pattern);
2032  
2033 Register the unpack pattern of the record C<$key>.
2034  
2035 =head2 oe_rec_output
2036  
2037 oe_rec_output($key, $format);
2038  
2039 Register the C<sprintf> output format of the record C<$key>.
2040  
2041 =head2 oe_rec_pre_process
2042  
2043 oe_rec_pre_process($key, $code);
2044  
2045 Attach the pre-processing C<$code> for the record C<$key>.
2046  
2047 =head2 oe_rec_process
2048  
2049 oe_rec_process($key, $code);
2050  
2051 Attach the post-load processing C<$code> for the record C<$key>.
2052  
2053 =head2 oe_round
2054  
2055 my $value = oe_round($value, $multiple);
2056  
2057 Round C<$value> to a multiple, inferring the decimals.
2058  
2059 =head2 oe_set_sys_date
2060  
2061 oe_set_sys_date($date);
2062  
2063 Set the system date, remembering the original for restoration at exit.
2064  
2065 =head2 oe_simple_job
2066  
2067 my ($params, $cfg) = oe_simple_job(@args);
2068  
2069 Convenience bootstrap: options, then the input and output files.
2070  
2071 =head2 oe_to_date
2072  
2073 oe_to_date(\$date);
2074  
2075 Rewrite a C<YYYYMMDD> date as C<DD/MM/YYYY>, in place.
2076  
2077 =head2 oe_trimp_space
2078  
2079 oe_trimp_space(\$string);
2080  
2081 Collapse consecutive spaces in C<$string>, in place.
2082  
2083 =head2 oe_trt_ref_rec
2084  
2085 oe_trt_ref_rec($id, \$line, $rec_off, $rec_len);
2086  
2087 The core record processor: pre-process, unpack, process, reformat and
2088 post-process the referenced record.
2089  
2090 =head2 oe_uc_sans_accents
2091  
2092 oe_uc_sans_accents(\$string);
2093  
2094 Strip the accents from C<$string> and uppercase it, in place.
2095  
2096 =head2 oe_unique_data_name
2097  
2098 my $name = oe_unique_data_name($n, $id, $counter);
2099  
2100 Generate a unique name of C<$n> characters.
2101  
2102 =head1 EXPORTED VARIABLES
2103  
2104 =head2 *IN
2105  
2106 The input file handle.
2107  
2108 =head2 *OUT
2109  
2110 The output file handle.
2111  
2112 =head2 @DATATAB
2113  
2114 The array into which the records are distributed.
2115  
2116 =head2 $LAST_ENR
2117  
2118 The last processed record marker.
2119  
2120 =head2 %motifs
2121  
2122 The record-to-unpack-pattern table.
2123  
2124 =head2 %ouTags
2125  
2126 The record-to-output-tag table.
2127  
2128 =head2 %evalSsTrt
2129  
2130 The record-to-post-processing table.
2131  
2132 =head1 AUTHOR
2133  
2134 The oEdtk team.
2135  
2136 =cut