-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathfpdm.php
More file actions
2236 lines (1889 loc) · 78.9 KB
/
Copy pathfpdm.php
File metadata and controls
2236 lines (1889 loc) · 78.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*******************************************************************************
* FPDM *
* *
*@file fpdm.php *
*@name A free PDF form filling tool *
*@package fpdftk *
*@version 2.9 *
*@date 2017-05-11 *
*@author 0livier *
*@todo in the importance order, natively by fpdm *
* -stream inline support (content change,repack,offset/size calculations) *
* -pdf inline protection *
* -flatten support *
* -extends filling to another form fields types (checkboxes,combos..) *
*@note *
* V2.9 (11.05.2017) fixed an issue with some PDFs *
* V2.8 (31.12.2011) added UTF-8 support *
* V2.7 (29.12.2011) compatibility with PDFs generated by pdftk *
* V2.6 (25.12.2010) OpenOffice 3 compatibility issues for Florian *
* see tracking issue here: http://www.fpdf.org/?go=forum&i=53697&t=53697 *
* V2.5 (06.12.2010) pdftk support for flatten mode and more...special *
* christmas release to the fpdf fanclub even if the red guy is busy *
* V2.4 (01.12.2010) Hack for malformed stream definitions, new parsing and *
* stream core with advanced verbose output. Fix() bonus for corrupted pdfs. *
* V2.3 (28.11.2010) stream type was lost when /length defined after /Filter *
* V2.2 (27.11.2010) Stream filter improved:decode now handles multi filters! * *
* V2.1 (25.11.2010) Only filter support for streams, trailer detection was *
* too restrictive. fixes FDF error occuring when empty array data is given. *
* V2.0 (05.11.2010) Load support for inline text fields datas or FDF content *
* V1.1 (04.11.2010) Works now under php4 for backward compat. *
* V1.0 (03.11.2010) First working release *
*******************************************************************************/
global $FPDM_FILTERS, $FPDM_REGEXPS; //needs explicit global scope, otherwise autoloading will be incomplete.
$FPDM_FILTERS=array(); //holds all supported filters
$FPDM_REGEXPS= array(
//FIX: parse checkbox definition
"/AS"=>"/\/AS\s+\/(\w+)$/",
"name"=>"/\/(\w+)/",
// "/AP_D_SingleLine"=>"/\/D\s+\/(\w+)\s+\d+\s+\d+\s+R\s+\/(\w+)$/",
//ENDFIX
"/Type"=>"/\/Type\s+\/(\w+)$/",
"/Subtype" =>"/^\/Subtype\s+\/(\w+)$/"
);
//Major stream filters come from FPDI's stuff but I've added some :)
if (!defined('FPDM_DIRECT')) {
$FPDM_FILTERS = array("LZWDecode", "ASCIIHexDecode", "ASCII85Decode", "FlateDecode", "Standard" );
}
// require_once("filters/FilterASCIIHex.php");
// require_once("filters/FilterASCII85.php");
// require_once("filters/FilterFlate.php");
// require_once("filters/FilterLZW.php");
// require_once("filters/FilterStandard.php");
$__tmp = version_compare(phpversion(), "5") == -1 ? array('FPDM') : array('FPDM', false);
if (!call_user_func_array('class_exists', $__tmp)) {
define('FPDM_VERSION',2.9);
define('FPDM_INVALID',0);
define('FPDM_STATIC',1);
define('FPDM_COMMON',2);
define('FPDM_VERBOSE',3);
define('FPDM_CACHE',dirname(__FILE__).'/export/cache/'); //cache directory for fdf temporary files needed by pdftk.
define('FPDM_PASSWORD_MAX_LEN',15); //Security to prevent shell overflow.
class FPDM {
//@@@@@@@@@
var $useCheckboxParser = false; //boolean: allows activation of custom checkbox parser (not available in original FPDM source)
var $pdf_source = ''; //string: full pathname to the input pdf , a form file
var $fdf_source = ''; //string: full pathname to the input fdf , a form data file
var $pdf_output = ''; //string: full pathname to the resulting filled pdf
var $pdf_entries = array(); //array: Holds the content of the pdf file as array
var $fdf_content = ''; //string: holds the content of the fdf file
var $fdf_parse_needed = false;//boolean: false will use $fields data else extract data from fdf content
var $value_entries = array(); //array: a map of values to faliclitate access and changes
var $positions = array(); //array, stores what object id is at a given position n ($positions[n]=<obj_id>)
var $offsets = array(); //array of offsets for objects, index is the object's id, starting at 1
var $pointer = 0; //integer, Current line position in the pdf file during the parsing
var $shifts = array(); //array, Shifts of objects in the order positions they appear in the pdf, starting at 0.
var $shift = 0; //integer, Global shift file size due to object values size changes
var $streams = ''; //Holds streams configuration found during parsing
var $streams_filter = ''; //Regexp to decode filter streams
var $safe_mode = false; //boolean, if set, ignore previous offsets do no calculations for the new xref table, seek pos directly in file
var $check_mode = false; //boolean, Use this to track offset calculations errors in corrupteds pdfs files for sample
var $halt_mode = false; //if true, stops when offset error is encountered
var $info = array(); //array, holds the info properties
var $fields = array(); //array that holds fields-Data parsed from FDF
var $verbose = false; //boolean , a debug flag to decide whether or not to show internal process
var $verbose_level = 1; //integer default is 1 and if greater than 3, shows internal parsing as well
var $support = ''; //string set to 'native' for fpdm or 'pdftk' for pdf toolkit
var $flatten_mode = false; //if true, flatten field data as text and remove form fields (NOT YET SUPPORTED BY FPDM)
var $compress_mode = false; //boolean , pdftk feature only to compress streams
var $uncompress_mode = false; //boolean pdftk feature only to uncompress streams
var $security = array(); //Array holding securtity settings
//(password owner nad user, encrypt (set to 40 or 128 or 0), allow <permissions>] see pdfk help
var $needAppearancesTrue = false; //boolean, indicates if /NeedAppearances is already set to true
var $isUTF8 = false; //boolean (true for UTF-8, false for ISO-8859-1)
/**
* Constructor
*
*@example Common use:
*@param string $pdf_source Source-Filename
*@param string $fdf_source Source-Filename
*@param boolean $verbose , optional false per default
*/
function __construct() {
//==============
$args=func_get_args();
$num_args=func_num_args();
$FDF_FILE=($num_args>=FPDM_COMMON);
$VERBOSE_FLAG=($num_args>=FPDM_VERBOSE);
$verbose=false;
//We are not joking here, let's have a polymorphic constructor!
switch($num_args) {
case FPDM_INVALID:
$this->Error("Invalid instantiation of FPDM, requires at least one param");
break;
case FPDM_STATIC:
if($args[0] =='[_STATIC_]') break; //static use, caller is anonymous function defined in _set_field_value
//else this is the pdf_source then, fdf content is loaded using Load() function
default:
case FPDM_VERBOSE: //Use the verbose value provided
if($VERBOSE_FLAG) $verbose=$args[2];
case FPDM_COMMON: //Common use
$this->pdf_source = $args[0];//Blank pdf form
if($FDF_FILE) {
$this->fdf_source = $args[1];//Holds the data of the fields to fill the form
$this->fdf_parse_needed=true;
}
//calculation and map
$this->offsets=array();
$this->pointer=0;
$this->shift=0;
$this->shifts=array();
$this->n=0;
//Stream filters
$filters=$this->getFilters("|");
$this->streams_filter="/(\/($filters))+/";
//$this->dumpContent($this->streams_filter);
$this->info=array();
//Debug modes
$this->verbose=$verbose;
$this->verbose_level=($verbose&&is_int($verbose)) ? $verbose : 1;
$this->safe_mode=false;
$this->check_mode=false; //script will takes much more time if you do so
$this->halt_mode=true;
$this->support='native'; //may ne overriden
$this->security=array('password'=>array('owner'=>null,'user'=>null),'encrypt'=>0,'allow'=>array());
//echo "<br>filesize:".filesize($this->pdf_source);
$this->load_file('PDF');
if($FDF_FILE) $this->load_file('FDF');
}
}
/**
*Loads a form data to be merged
*
*@note this overrides fdf input source if it was previously defined
*@access public
*@param string|array $fdf_data a FDF file content or $pdf_data an array containing the values for the fields to change
**/
function Load($data,$isUTF8=false) {
//------------------------
$this->isUTF8 = $isUTF8;
$this->load_file('FDF',$data);
}
/**
*Loads a file according to its type
*
*@access private
*@param string type 'PDF' or 'FDF'
*@param String|array content the data content of FDF files only or directly the fields values as array
**/
function load_file($type,$content=NULL) {
//------------------------------------
switch($type) {
case "PDF" :
if($content)
$this->Error("load_file do not accept PDF content, only FDF content sorry");
else
$this->pdf_entries = $this->getEntries($this->pdf_source,'PDF');
break;
case "FDF" :
if(!is_null($content)) {
if(is_array($content)) {
$this->fields=$content;
$this->fdf_parse_needed=false;
//$this->dumpEntries($content,"PDF fields content");
} else if(is_string($content)){ //String
$this->fdf_content = $content; //TODO: check content
$this->fdf_parse_needed=true;
} else
$this->Error('Invalid content type for this FDF file!');
} else {
$this->fdf_content = $this->getContent($this->fdf_source,'FDF');
$this->fdf_parse_needed=true;
}
break;
default:
$this->Error("Invalid file type $type");
}
}
/**
*Set a mode and play with your power debug toys
*
*@access public
*@note for big boys only coz it may hurt
*@param string $mode a choice between 'safe','check','verbose','halt' or 'verbose_level'
*@param string|int $value an integer for verbose_level
**/
function set_modes($mode,$value) {
//-------------------------------
switch($mode) {
case 'safe':
$this->safe_mode=$value;
break;
case 'check':
$this->check_mode=$value;
break;
case 'flatten':
$this->flatten_mode=$value;
break;
case 'compress_mode':
$this->compress_mode=$value;
if($value) $this->uncompress_mode=false;
break;
case 'uncompress_mode':
$this->uncompress_mode=$value;
if($value) $this->compress_mode=false;
break;
case 'verbose':
$this->verbose=$value;
break;
case 'halt':
$this->halt_mode=$value;
break;
case 'verbose_level':
$this->verbose_level=$value;
break;
default:
$this->Error("set_modes error, Invalid mode '<i>$mode</i>'");
}
}
/**
*Retrieves informations of the pdf
*
*@access public
*@note To track PDF versions and so on...
*@param Boolean output
**/
function Info($asArray=false) {
//----------------------
$info=$this->info;
$info["Reader"]=($this->support == "native") ? 'FPDF-Merge '.FPDM_VERSION: $this->support;
$info["Fields"]=$this->fields;
$info["Modes"]=array(
'safe'=>($this->safe_mode)? 'Yes' :'No',
'check'=>($this->check_mode) ? 'Yes': 'No',
'flatten'=>($this->flatten_mode) ? 'Yes': 'No',
'compress_mode'=>($this->compress_mode) ? 'Yes': 'No',
'uncompress_mode'=>($this->uncompress_mode) ? 'Yes': 'No',
'verbose'=>$this->verbose,
'verbose_level'=>$this->verbose_level,
'halt'=>$this->halt_mode
);
if($asArray) {
return $info;
} else {
$this->dumpEntries($info);
}
}
/**
*Changes the support
*
*@access public
*@internal fixes xref table offsets
*@note special playskool toy for Christmas dedicated to my impatient fanclub (Grant, Kris, nejck,...)
*@param String support Allow to use external support that has more advanced features (ie 'pdftk')
**/
function Plays($cool) {
//----------------------
if($cool=='pdftk') //Use a coolest support as ..
$this->support='pdftk';//..Per DeFinition This is Kool!
else
$this->support='native';
}
/**
*Fixes a corrupted PDF file
*
*@access public
*@internal fixes xref table offsets
*@note Real work is not made here but by Merge that should be launched after to complete the work
**/
function Fix() {
//---------------
if(!$this->fields) $this->fields=array(); //Default: No field data
$this->set_modes('check',true); //Compare xref table offsets with objects offsets in the pdf file
$this->set_modes('halt',false); //Do no stop on errors so fix is applied during merge process
}
//######## pdftk's output configuration #######
/**
*Decides to use the compress filter to restore compression.
*@note This is only useful when you want to repack PDF that was previously edited in a text editor like vim or emacs.
**/
function Compress() {
//-------------------
$this->set_modes('compress',true);
$this->support="pdftk";
}
/**
*Decides to remove PDF page stream compression by applying the uncompress filter.
*@note This is only useful when you want to edit PDF code in a text editor like vim or emacs.
**/
function Uncompress() {
//---------------------
$this->set_modes('uncompress',true);
$this->support="pdftk";
}
/**
*Activates the flatten output to remove form from pdf file keeping field datas.
**/
function Flatten() {
//-----------------
$this->set_modes('flatten',true);
$this->support="pdftk";
}
/***
*Defines a password type
*@param String type , 'owner' or 'user'
**/
function Password($type,$code) {
//------------------------------
switch($type) {
case 'owner':
case 'user':
$this->security["password"]["$type"]=$code;
break;
default:
$this->Error("Unsupported password type ($type), specify 'owner' or 'user' instead.");
}
$this->support="pdftk";
}
/**
*Defines the encrytion to the given bits
*@param integer $bits 0, 40 or 128
**/
function Encrypt($bits) {
//-----------------------
switch($bits) {
case 0:
case 40:
case 128:
$this->security["encrypt"]=$bits;
break;
default:
$this->Error("Unsupported encrypt value of $bits, only 0, 40 and 128 are supported");
}
$this->support="pdftk";
}
/**
*Allow permissions
*
*@param Array permmissions If no arg is given, show help.
* Permissions are applied to the output PDF only if an encryption
* strength is specified or an owner or user password is given. If
* permissions are not specified, they default to 'none,' which
* means all of the following features are disabled.
*
* The permissions section may include one or more of the following
* features:
*
* Printing
* Top Quality Printing
*
* DegradedPrinting
* Lower Quality Printing
*
* ModifyContents
* Also allows Assembly
*
* Assembly
*
* CopyContents
* Also allows ScreenReaders
*
* ScreenReaders
*
* ModifyAnnotations
* Also allows FillIn
*
* FillIn
*
* AllFeatures
* Allows the user to perform all of the above, and top
* quality printing.
**/
function Allow($permissions=null) {
//--------------------------
$perms_help=array(
'Printing'=>'Top Quality Printing',
'DegradedPrinting'=>'Lower Quality Printing',
'ModifyContents' =>'Also allows Assembly',
'Assembly' => '',
'CopyContents' => 'Also allows ScreenReaders',
'ScreenReaders' => '',
'ModifyAnnotations'=>'Also allows FillIn',
'FillIn'=>'',
'AllFeatures'=> "All above"
);
if(is_null($permissions)) {
echo '<br>Info Allow permissions:<br>';
print_r($perms_help);
}else {
if(is_string($permissions)) $permissions=array($permissions);
$perms=array_keys($perms_help);
$this->security["allow"]=array_intersect($permissions, $perms);
$this->support="pdftk";
}
}
//#############################
/**
*Merge FDF file with a PDF file
*
*@access public
*@note files has been provided during the instantiation of this class
*@internal flatten mode is not yet supported
*@param Boolean flatten Optional, false by default, if true will use pdftk (requires a shell) to flatten the pdf form
**/
function Merge($flatten=false,$read_only=false) {
//------------------------------
if($flatten) $this->Flatten();
if($this->support == "native") {
if($this->fdf_parse_needed) {
$fields=$this->parseFDFContent();
}else {
$fields=$this->fields;
}
$count_fields=count($fields);
if($this->verbose&&($count_fields==0))
$this->dumpContent("The FDF content has either no field data or parsing may failed","FDF parser: ");
$fields_value_definition_lines=array();
$count_entries=$this->parsePDFEntries($fields_value_definition_lines);
if($count_entries) {
$this->value_entries=$fields_value_definition_lines;
if($this->verbose) {
$this->dumpContent("$count_entries Field entry values found for $count_fields field values to fill","Merge info: ");
}
//==== Alterate work is made here: change values ============
if($count_fields) {
foreach($fields as $name => $value) {
$this->set_field_value("current",$name,$value,$read_only);
// $value=''; //Strategy applies only to current value, clear others
// $this->set_field_value("default",$name,$value);
// $this->set_field_value("tooltip",$name,$value);
}
}
//===========================================================
//===== Cross refs/size fixes (offsets calculations for objects have been previously be done in set_field_value) =======
//Update cross reference table to match object size changes
$this->fix_xref_table();
//update the pointer to the cross reference table
$this->fix_xref_start();
}else
$this->Error("PDF file is empty!");
} //else pdftk's job is done in Output, not here.
}
/**
*Warns verbose/output conflicts
*
*@access private
*@param string $dest a output destination
**/
function Close($dest) {
//----------------
$this->Error("Output: Verbose mode should be desactivated, it is incompatible with this output mode $dest");
}
/**
*Get current pdf content (without any offset fixes)
*
*@access private
*@param String pdf_file, if given , use the content as buffer (note file will be deleted after!)
*@return string buffer the pdf content
**/
function get_buffer($pdf_file=''){
//---------------------
if($pdf_file == '') {
$buffer=implode("\n",$this->pdf_entries);
}else {
$buffer=$this->getContent($pdf_file,'PDF');
//@unlink($pdf_file);
}
return $buffer;
}
/**
*Output PDF to some destination
*
*@access public
*@note reproduces the fpdf's behavior
*@param string dest the destination
*@param string name the filename
**/
function Output($dest='', $name=''){
//-----------------------------------
$pdf_file='';
if($this->support == "pdftk") {
//As PDFTK can only merge FDF files not data directly,
require_once("lib/url.php"); //we will need a url support because relative urls for pdf inside fdf files are not supported by PDFTK...
require_once("export/fdf/fdf.php"); //...conjointly with my patched/bridged forge_fdf that provides fdf file generation support from array data.
require_once("export/pdf/pdftk.php");//Of course don't forget to bridge to PDFTK!
$tmp_file=false;
$pdf_file=resolve_path(fix_path(dirname(__FILE__).'/'.$this->pdf_source)); //string: full pathname to the input pdf , a form file
if($this->fdf_source) { //FDF file provided
$fdf_file=resolve_path(fix_path(dirname(__FILE__).'/'.$this->fdf_source));
}else {
$pdf_url=getUrlfromDir($pdf_file); //Normaly http scheme not local file
if($this->fdf_parse_needed) { //fdf source was provided
$pdf_data=$this->parseFDFContent();
}else { //fields data was provided as an array, we have to generate the fdf file
$pdf_data=$this->fields;
}
$fdf_file=fix_path(FPDM_CACHE)."fields".rnunid().".fdf";
$tmp_file=true;
$ret=output_fdf($pdf_url,$pdf_data,$fdf_file);
if(!$ret["success"])
$this->Error("Output failed as something goes wrong (Pdf was $pdf_url) <br> during internal FDF generation of file $fdf_file, <br>Reason is given by {$ret['return']}");
}
//Serializes security options (not deeply tested)
$security='';
if(!is_null($this->security["password"]["owner"])) $security.=' owner_pw "'.substr($this->security["password"]["owner"],0,FPDM_PASSWORD_MAX_LEN).'"';
if(!is_null($this->security["password"]["user"])) $security.=' user_pw "'.substr($this->security["password"]["user"],0,FPDM_PASSWORD_MAX_LEN).'"';
if($this->security["encrypt"]!=0) $security.=' encrypt_'.$this->security["encrypt"].'bit';
if(count($this->security["allow"])>0) {
$permissions=$this->security["allow"];
$security.=' allow ';
foreach($permissions as $permission)
$security.=' '.$permission;
}
//Serialize output modes
$output_modes='';
if($this->flatten_mode) $output_modes.=' flatten';
if($this->compress_mode) $output_modes.=' compress';
if($this->uncompress_mode) $output_modes.=' uncompress';
$ret=pdftk($pdf_file,$fdf_file,array("security"=>$security,"output_modes"=>$output_modes));
if($tmp_file) @unlink($fdf_file); //Clear cache
if($ret["success"]) {
$pdf_file=$ret["return"];
}else
$this->Error($ret["return"]);
}
//$this->buffer=$this->get_buffer($pdf_file);
$dest=strtoupper($dest);
if($dest=='')
{
if($name=='')
{
$name='doc.pdf';
$dest='I';
}
else
$dest='F';
}
//Abort to avoid to polluate output
if($this->verbose&&(($dest=='I')||($dest=='D'))) {
$this->Close($dest);
}
switch($dest)
{
case 'I':
//Send to standard output
if(ob_get_length())
$this->Error('Some data has already been output, can\'t send PDF file');
if(php_sapi_name()!='cli')
{
//We send to a browser
header('Content-Type: application/pdf');
if(headers_sent())
$this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Length: '.strlen($this->get_buffer()));
header('Content-Disposition: inline; filename="'.$name.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
}
echo $this->get_buffer();
break;
case 'D':
//Download file
if(ob_get_length())
$this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Type: application/x-download');
if(headers_sent())
$this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Length: '.strlen($this->get_buffer()));
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
//header("Pragma: "); // HTTP/1.0
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public,no-cache');
ini_set('zlib.output_compression','0');
echo $this->get_buffer();
break;
case 'F':
//Save to local file
if($this->verbose) $this->dumpContent("Write file $name","Output");
$f=fopen($name,'wb');
if(!$f)
$this->Error('Unable to create output file: '.$name.' (currently opened under Acrobat Reader?)');
fwrite($f,$this->get_buffer(),strlen($this->get_buffer()));
fclose($f);
break;
case 'S':
//Return as a string
return $this->get_buffer();
default:
$this->Error('Incorrect output destination: '.$dest);
}
return '';
}
/**
*Decodes and returns the binary form of a field hexified value
*
*@note static method due to callback..
*@param string value the hexified string
*@return string call the binary string
**/
function pdf_decode_field_value($value) {
//----------------------------------------
$call=$this->static_method_call('_hex2bin',$value);
return $call;
}
/**
*Encodes and returns the headecimal form of a field binary value
*
*@note static method due to callback..
*@param string value the binary string
*@return string call the hexified string
**/
function pdf_encode_field_value($value) {
//---------------------------------------
$value=$this->static_method_call('_bin2hex',$value);
return $value;
}
/**
*Universal Php4/5 static call helper
*
*@param String $method a name of a method belonging to this class
*@return mixed the return value of the called method
**/
function static_method_call($method) {
//---------------------------------------------
$params_call=func_get_args();
array_shift($params_call);
//var_dump($params_call);
return call_user_func_array(array($this,$method),$params_call);
}
/**
*Changes a field value that can be in hex <> or binary form ()
*
*@param $matches the regexp matches of the line that contains the value to change
*@param String $value the new value for the field property
**/
function replace_value($matches,$value) {
//----------------------------------------------
array_shift($matches);
if(($value!='')&&($matches[1]=="<")) //Value must be hexified..
$value=$this->pdf_encode_field_value($value);
$matches[2]=$value;
$value_type_code=$matches[0]; //Should be V, DV or TU
$matches[0]="/".$value_type_code." ";
$value=implode("",$matches);
//echo(htmlentities($value));
return $value;
}
/**
*Core to change the value of a field property, inline.
*
*@access private
*@param int $line the lien where the field property value is defined in the pdf file
*@param string $value the new value to set
*@return int $shift the size change of the field property value
**/
function _set_field_value($line,$value) {
//----------------------------------------
$verbose_set=($this->verbose&&($this->verbose_level>1));
//get the line content
$CurLine =$this->pdf_entries[$line];
$OldLen=strlen($CurLine);
//My PHP4/5 static call hack, only to make the callback $this->replace_value($matches,"$value") possible!
$callback_code='$THIS=new FPDM("[_STATIC_]");return $THIS->replace_value($matches,"'.$value.'");';
$field_regexp='/^\/(\w+)\s?(\<|\()([^\)\>]*)(\)|\>)/';
if(preg_match($field_regexp,$CurLine)) {
//modify it according to the new value $value
$CurLine = preg_replace_callback(
$field_regexp,
create_function('$matches',$callback_code),
$CurLine
);
}else {
if($verbose_set) echo("<br>WARNING:".htmlentities("Can not access to the value: $CurLine using regexp $field_regexp"));
}
$NewLen=strlen($CurLine);
$Shift=$NewLen-$OldLen;
$this->shift=$this->shift+$Shift;
//Saves
$this->pdf_entries[$line]=$CurLine;
return $Shift;
}
function _encode_value($str) {
if($this->isUTF8)
$str="\xFE\xFF".iconv('UTF-8','UTF-16BE',$str);
return $this->_bin2hex($str);
}
function _set_field_value2($line,$value,$append,$read_only) {
$CurLine=$this->pdf_entries[$line];
$OldLen=strlen($CurLine);
if($append)
{
$CurLine .= ' /V <'.$this->_encode_value($value).'>';
}
else
{
if(preg_match('#/V\s?[<(]([^>)]*)[>)]#', $CurLine, $a, PREG_OFFSET_CAPTURE))
{
$len=strlen($a[1][0]);
$pos1=$a[1][1];
$pos2=$pos1+$len;
$CurLine=substr($CurLine,0,$pos1-1).'<'.$this->_encode_value($value).'>'.substr($CurLine,$pos2+1);
}
else
$this->Error('/V not found');
}
if ($read_only) {
$CurLine .= ' /Ff 1';
}
$NewLen=strlen($CurLine);
$Shift=$NewLen-$OldLen;
$this->shift=$this->shift+$Shift;
$this->pdf_entries[$line]=$CurLine;
return $Shift;
}
/**
*Changes the value of a field property, inline.
*
*@param string $type supported values for type are 'default' , 'current' or 'tooltip'
*@param string $name name of the field annotation to change the value
*@param string $value the new value to set
**/
function set_field_value($type,$name,$value,$read_only=false) {
//------------------------------------
$verbose_set=($this->verbose&&($this->verbose_level>1));
//Get the line(s) of the misc field values
if(isset($this->value_entries["$name"])) {
$object_id=$this->value_entries["$name"]["infos"]["object"];
if($type=="tooltip") {
$offset_shift=$this->set_field_tooltip($name,$value);
} elseif ($this->useCheckboxParser && isset($this->value_entries["$name"]['infos']['checkbox_state'])) { //FIX: set checkbox value
$offset_shift=$this->set_field_checkbox($name, $value);
//ENDFIX
} else {//if(isset($this->value_entries["$name"]["values"]["$type"])) {
// echo $this->value_entries["$name"]["values"]["$type"];
/* $field_value_line=$this->value_entries["$name"]["values"]["$type"];
$field_value_maxlen=$this->value_entries["$name"]["constraints"]["maxlen"];
if($field_value_maxlen) //Truncates the size if needed
$value=substr($value, 0, $field_value_maxlen);
if($verbose_set) echo "<br>Change $type value of the field $name at line $field_value_line to '<i>$value</i>'";
$offset_shift=$this->_set_field_value($field_value_line,$value);*/
if(isset($this->value_entries[$name]["values"]["current"]))
$offset_shift=$this->_set_field_value2($this->value_entries[$name]["values"]["current"],$value,false,$read_only);
else
$offset_shift=$this->_set_field_value2($this->value_entries[$name]["infos"]["name_line"],$value,true,$read_only);
}
// }else
// $this->Error("set_field_value failed as invalid valuetype $type for object $object_id");
//offset size shift will affect the next objects offsets taking into accound the order they appear in the file--
$this->apply_offset_shift_from_object($object_id,$offset_shift);
} else
$this->Error("field $name not found");
}
/**
*Changes the tooltip value of a field property, inline.
*
*@param string $name name of the field annotation to change the value
*@param string $value the new value to set
*@return int offset_shift the size variation
**/
function set_field_tooltip($name,$value) {
//------------------------------------
$offset_shift=0;
$verbose_set=($this->verbose&&($this->verbose_level>1));
//Get the line(s) of the misc field values
if(isset($this->value_entries["$name"])) {
$field_tooltip_line=$this->value_entries["$name"]["infos"]["tooltip"];
if($field_tooltip_line) {
if($verbose_set) echo "<br>Change tooltip of the field $name at line $field_tooltip_line to value [$value]";
$offset_shift=$this->_set_field_value($field_tooltip_line,$value);
}else {
if($verbose_set) echo "<br>Change toolpip value aborted, the field $name has no tooltip definition.";
}
} else
$this->Error("set_field_tooltip failed as the field $name does not exist");
return $offset_shift;
}
//FIX: parse checkbox definition
/**
*Changes the checkbox state.
*
*@param string $name name of the field to change the state
*@param string $value the new state to set
*@return int offset_shift the size variation
**/
public function set_field_checkbox($name, $value)
{
//------------------------------------
$offset_shift=0;
$verbose_set=($this->verbose&&($this->verbose_level>1));
//Get the line(s) of the misc field values
if (isset($this->value_entries["$name"])) {
if (isset($this->value_entries["$name"]["infos"]["checkbox_state_line"])
&& isset($this->value_entries["$name"]["infos"]["checkbox_no"])
&& isset($this->value_entries["$name"]["infos"]["checkbox_yes"])) {
$field_checkbox_line=$this->value_entries["$name"]["infos"]["checkbox_state_line"];
if ($field_checkbox_line) {
if ($verbose_set) {
echo "<br>Change checkbox of the field $name at line $field_checkbox_line to value [$value]";
}
$state = $this->value_entries["$name"]["infos"]["checkbox_no"];
if ($value) {
$state = $this->value_entries["$name"]["infos"]["checkbox_yes"];
}
$CurLine =$this->pdf_entries[$field_checkbox_line];
$OldLen=strlen($CurLine);
$CurLine = '/AS /'.$state;
$NewLen=strlen($CurLine);
$Shift=$NewLen-$OldLen;
$this->shift=$this->shift+$Shift;
//Saves
$this->pdf_entries[$field_checkbox_line]=$CurLine;
return $Shift;
// $offset_shift=$this->_set_field_value($field_checkbox_line, $state);
} else {
if ($verbose_set) {
echo "<br>Change checkbox value aborted, parsed checkbox definition incomplete.";
}
}
} else {
if ($verbose_set) {
echo "<br>Change checkbox value aborted, the field $name has no checkbox definition.";
}
}
} else {
$this->Error("set_field_checkbox failed as the field $name does not exist");
}
return $offset_shift;
}
//ENDFIX
/**
*Dumps the line entries
*
*@note for debug purposes
*@access private
*@param array entries the content to dump
*@param string tag an optional tag to highlight
*@param boolean halt decides to stop or not this script
**/
function dumpEntries($entries,$tag="",$halt=false) {
//------------------------------------------------------------
if($tag) echo "<br><h4>$tag</h4><hr>";