Project

General

Profile

1
<?php
2
// --------------------------------------------------------------------------------
3
// PhpConcept Library - Zip Module 2.8.2
4
// --------------------------------------------------------------------------------
5
// License GNU/LGPL - Vincent Blavet - August 2009
6
// http://www.phpconcept.net
7
// --------------------------------------------------------------------------------
8
//
9
// Presentation :
10
//   PclZip is a PHP library that manage ZIP archives.
11
//   So far tests show that archives generated by PclZip are readable by
12
//   WinZip application and other tools.
13
//
14
// Description :
15
//   See readme.txt and http://www.phpconcept.net
16
//
17
// Warning :
18
//   This library and the associated files are non commercial, non professional
19
//   work.
20
//   It should not have unexpected results. However if any damage is caused by
21
//   this software the author can not be responsible.
22
//   The use of this software is at the risk of the user.
23
//
24
// --------------------------------------------------------------------------------
25
// $Id: pclzip.lib.php 2 2017-07-02 15:14:29Z Manuela $
26
// --------------------------------------------------------------------------------
27

    
28
// --------------------------------------------------------------------------------
29
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
30
// --------------------------------------------------------------------------------
31

    
32
    // Global variables
33
    $g_pclzip_version = "2.8.2";
34

    
35
/* --- include global constants definitions if realy needed --------------------------- */
36
/* this part is set deprecated and for compatibility only                               */
37
    if (!defined('PCLZIP_ERR_NO_ERROR')) {
38
        include __DIR__.'/Constants.php';
39
    }
40
/* --- zlib compatibility for 32bit Ubuntu -------------------------------------------- */
41
/* this part is never needed on 64bit servers                                           */
42
    if (!function_exists('gzopen')) {
43
        if (!function_exists('gzopen64')) {
44
            throw new Exception('Loading '.basename(__FILE__).' aborted: Missing zlib extensions');
45
        } else {
46
            function gzopen($sfn,$m)
47
            {
48
                return gzopen64($sfn,$m);
49
            }
50
        }
51
    }
52
/* ==================================================================================== */
53
/** --------------------------------------------------------------------------------------
54
 * Class : PclZip
55
 * Description :
56
 *   PclZip is the class that represent a Zip archive.
57
 *   The public methods allow the manipulation of the archive.
58
 * Attributes :
59
 *   Attributes must not be accessed directly.
60
 * Methods :
61
 *   PclZip() : Object creator
62
 *   create() : Creates the Zip archive
63
 *   listContent() : List the content of the Zip archive
64
 *   extract() : Extract the content of the archive
65
 *   properties() : List the properties of the archive
66
 */
67

    
68
class PclZip
69
{
70

    
71
  // Constants
72
    const READ_BLOCK_SIZE = 2048;
73

    
74
  // File list separator
75
  // In version 1.x of PclZip, the separator for file list is a space
76
  // (which is not a very smart choice, specifically for windows paths !).
77
  // A better separator should be a comma (,). This constant gives you the
78
  // abilty to change that.
79
  // However notice that changing this value, may have impact on existing
80
  // scripts, using space separated filenames.
81
  // Recommanded values for compatibility with older versions :
82
  // const SEPARATOR = ' ';
83
  // Recommanded values for smart separation of filenames.
84
    const SEPARATOR = ',';
85

    
86
  // Error configuration
87
  // 0 : PclZip Class integrated error handling
88
  // 1 : PclError external library error handling. By enabling this
89
  //     you must ensure that you have included PclError library.
90
  // [2,...] : reserved for futur use
91
    const ERROR_EXTERNAL = 0;
92

    
93
  // Optional static temporary directory
94
  //       By default temporary files are generated in the script current
95
  //       path.
96
  //       If defined :
97
  //       - MUST BE terminated by a '/'.
98
  //       - MUST be a valid, already created directory
99
  //       Samples :
100
  //       - const TEMPORARY_DIR = '/temp/';
101
  //       - const TEMPORARY_DIR = 'C:/Temp/';
102
    const TEMPORARY_DIR = '';
103

    
104
  // Optional threshold ratio for use of temporary files
105
  //       Pclzip sense the size of the file to add/extract and decide to
106
  //       use or not temporary file. The algorythm is looking for
107
  //       memory_limit of PHP and apply a ratio.
108
  //       threshold = memory_limit * ratio.
109
  //       Recommended values are under 0.5. Default 0.47.
110
  //       Samples :
111
  //       - const TEMPORARY_FILE_RATIO = 0.5;
112
    const TEMPORARY_FILE_RATIO = 0.47;
113

    
114
// Error codes ---------------------------------------------------------------------
115
//    -1 : Unable to open file in binary write mode
116
//    -2 : Unable to open file in binary read mode
117
//    -3 : Invalid parameters
118
//    -4 : File does not exist
119
//    -5 : Filename is too long (max. 255)
120
//    -6 : Not a valid zip file
121
//    -7 : Invalid extracted file size
122
//    -8 : Unable to create directory
123
//    -9 : Invalid archive extension
124
//    -10 : Invalid archive format
125
//    -11 : Unable to delete file (unlink)
126
//    -12 : Unable to rename file (rename)
127
//    -13 : Invalid header checksum
128
//    -14 : Invalid archive size
129
    const ERR_USER_ABORTED            =     2;
130
    const ERR_NO_ERROR                =     0;
131
    const ERR_WRITE_OPEN_FAIL         =    -1;
132
    const ERR_READ_OPEN_FAIL          =    -2;
133
    const ERR_INVALID_PARAMETER       =    -3;
134
    const ERR_MISSING_FILE            =    -4;
135
    const ERR_FILENAME_TOO_LONG       =    -5;
136
    const ERR_INVALID_ZIP             =    -6;
137
    const ERR_BAD_EXTRACTED_FILE      =    -7;
138
    const ERR_DIR_CREATE_FAIL         =    -8;
139
    const ERR_BAD_EXTENSION           =    -9;
140
    const ERR_BAD_FORMAT              =   -10;
141
    const ERR_DELETE_FILE_FAIL        =   -11;
142
    const ERR_RENAME_FILE_FAIL        =   -12;
143
    const ERR_BAD_CHECKSUM            =   -13;
144
    const ERR_INVALID_ARCHIVE_ZIP     =   -14;
145
    const ERR_MISSING_OPTION_VALUE    =   -15;
146
    const ERR_INVALID_OPTION_VALUE    =   -16;
147
    const ERR_ALREADY_A_DIRECTORY     =   -17;
148
    const ERR_UNSUPPORTED_COMPRESSION =   -18;
149
    const ERR_UNSUPPORTED_ENCRYPTION  =   -19;
150
    const ERR_INVALID_ATTRIBUTE_VALUE =   -20;
151
    const ERR_DIRECTORY_RESTRICTION   =   -21;
152
    // Options values --------------------------------------------------------------
153
    const OPT_PATH                    = 77001;
154
    const OPT_ADD_PATH                = 77002;
155
    const OPT_REMOVE_PATH             = 77003;
156
    const OPT_REMOVE_ALL_PATH         = 77004;
157
    const OPT_SET_CHMOD               = 77005;
158
    const OPT_EXTRACT_AS_STRING       = 77006;
159
    const OPT_NO_COMPRESSION          = 77007;
160
    const OPT_BY_NAME                 = 77008;
161
    const OPT_BY_INDEX                = 77009;
162
    const OPT_BY_EREG                 = 77010;
163
    const OPT_BY_PREG                 = 77011;
164
    const OPT_COMMENT                 = 77012;
165
    const OPT_ADD_COMMENT             = 77013;
166
    const OPT_PREPEND_COMMENT         = 77014;
167
    const OPT_EXTRACT_IN_OUTPUT       = 77015;
168
    const OPT_REPLACE_NEWER           = 77016;
169
    const OPT_STOP_ON_ERROR           = 77017;
170
//    Having big trouble with crypt. Need to multiply 2 long int
171
//    which is not correctly supported by PHP ...
172
//    const OPT_CRYPT', 77018 );
173
    const OPT_EXTRACT_DIR_RESTRICTION = 77019;
174
    const OPT_TEMP_FILE_THRESHOLD     = 77020;
175
    const OPT_ADD_TEMP_FILE_THRESHOLD = 77020; // alias for OPT_TEMP_FILE_THRESHOLD
176
    const OPT_TEMP_FILE_ON            = 77021;
177
    const OPT_ADD_TEMP_FILE_ON        = 77021; // alias for OPT_TEMP_FILE_ON
178
    const OPT_TEMP_FILE_OFF           = 77022;
179
    const OPT_ADD_TEMP_FILE_OFF       = 77022; // alias for OPT_TEMP_FILE_OFF
180
// File description attributes -----------------------------------------------------
181
    const ATT_FILE_NAME               = 79001;
182
    const ATT_FILE_NEW_SHORT_NAME     = 79002;
183
    const ATT_FILE_NEW_FULL_NAME      = 79003;
184
    const ATT_FILE_MTIME              = 79004;
185
    const ATT_FILE_CONTENT            = 79005;
186
    const ATT_FILE_COMMENT            = 79006;
187
// Call backs values ---------------------------------------------------------------
188
    const CB_PRE_EXTRACT              = 78001;
189
    const CB_POST_EXTRACT             = 78002;
190
    const CB_PRE_ADD                  = 78003;
191
    const CB_POST_ADD                 = 78004;
192
// For futur use -------------------------------------------------------------------
193
//    const CB_PRE_LIST    = 78005;
194
//    const CB_POST_LIST   = 78006;
195
//    const CB_PRE_DELETE  = 78007;
196
//    const CB_POST_DELETE = 78008;
197

    
198
/** @var string  Filename of the zip file */
199
    protected $zipname      = '';
200

    
201
/** @var integer  File descriptor of the zip file */
202
    protected $zip_fd       = 0;
203

    
204
/** @var integer  Internal error handling */
205
    protected $error_code   = 1;
206

    
207
/** @var string  Internal error message */
208
    protected $error_string = '';
209

    
210
/**
211
 *  @var integer  Current status of the magic_quotes_runtime
212
 *  @description  This value store the php configuration for magic_quotes
213
 *                  The class can then disable the magic_quotes and reset it after
214
 */
215
    protected $magic_quotes_status = -1;
216

    
217
  // --------------------------------------------------------------------------------
218
  // Function : PclZip()
219
  // Description :
220
  //   Creates a PclZip object and set the name of the associated Zip archive
221
  //   filename.
222
  //   Note that no real action is taken, if the archive does not exist it is not
223
  //   created. Use create() for that.
224
  // --------------------------------------------------------------------------------
225
    public function __construct($p_zipname)
226
    {
227
        // Set the attributes
228
        $this->zipname             = $p_zipname;
229
        $this->zip_fd              = 0;
230
        $this->magic_quotes_status = -1;
231

    
232
    }
233

    
234
  // --------------------------------------------------------------------------------
235
  // Function :
236
  //   create($p_filelist, $p_add_dir="", $p_remove_dir="")
237
  //   create($p_filelist, $p_option, $p_option_value, ...)
238
  // Description :
239
  //   This method supports two different synopsis. The first one is historical.
240
  //   This method creates a Zip Archive. The Zip file is created in the
241
  //   filesystem. The files and directories indicated in $p_filelist
242
  //   are added in the archive. See the parameters description for the
243
  //   supported format of $p_filelist.
244
  //   When a directory is in the list, the directory and its content is added
245
  //   in the archive.
246
  //   In this synopsis, the function takes an optional variable list of
247
  //   options. See bellow the supported options.
248
  // Parameters :
249
  //   $p_filelist : An array containing file or directory names, or
250
  //                 a string containing one filename or one directory name, or
251
  //                 a string containing a list of filenames and/or directory
252
  //                 names separated by spaces.
253
  //   $p_add_dir : A path to add before the real path of the archived file,
254
  //                in order to have it memorized in the archive.
255
  //   $p_remove_dir : A path to remove from the real path of the file to archive,
256
  //                   in order to have a shorter path memorized in the archive.
257
  //                   When $p_add_dir and $p_remove_dir are set, $p_remove_dir
258
  //                   is removed first, before $p_add_dir is added.
259
  // Options :
260
  //   OPT_ADD_PATH :
261
  //   OPT_REMOVE_PATH :
262
  //   OPT_REMOVE_ALL_PATH :
263
  //   OPT_COMMENT :
264
  //   CB_PRE_ADD :
265
  //   CB_POST_ADD :
266
  // Return Values :
267
  //   0 on failure,
268
  //   The list of the added files, with a status of the add action.
269
  //   (see PclZip::listContent() for list entry format)
270
  // --------------------------------------------------------------------------------
271
    public function create($p_filelist)
272
    {
273
        $v_result=1;
274
        // Reset the error handler
275
        $this->privErrorReset();
276
        // Set default values
277
        $v_options = array();
278
        $v_options[self::OPT_NO_COMPRESSION] = false;
279
        // Look for variable options arguments
280
        $v_size = func_num_args();
281
        // Look for arguments
282
        if ($v_size > 1) {
283
            // Get the arguments
284
            $v_arg_list = func_get_args();
285
            // Remove from the options list the first argument
286
            array_shift($v_arg_list);
287
            $v_size--;
288
            // Look for first arg
289
            if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
290
                // Parse the options
291
                $v_result = $this->privParseOptions(
292
                    $v_arg_list,
293
                    $v_size,
294
                    $v_options,
295
                    array (
296
                        self::OPT_REMOVE_PATH => 'optional',
297
                        self::OPT_REMOVE_ALL_PATH => 'optional',
298
                        self::OPT_ADD_PATH => 'optional',
299
                        self::CB_PRE_ADD => 'optional',
300
                        self::CB_POST_ADD => 'optional',
301
                        self::OPT_NO_COMPRESSION => 'optional',
302
                        self::OPT_COMMENT => 'optional',
303
                        self::OPT_TEMP_FILE_THRESHOLD => 'optional',
304
                        self::OPT_TEMP_FILE_ON => 'optional',
305
                        // self::OPT_CRYPT => 'optional',
306
                        self::OPT_TEMP_FILE_OFF => 'optional'
307
                    )
308
                );
309
                if ($v_result != 1) {
310
                    return 0;
311
                }
312
            } else {
313
            // Look for 2 args
314
            // Here we need to support the first historic synopsis of the
315
            // method.
316
                // Get the first argument
317
                $v_options[self::OPT_ADD_PATH] = $v_arg_list[0];
318
                // Look for the optional second argument
319
                if ($v_size == 2) {
320
                    $v_options[self::OPT_REMOVE_PATH] = $v_arg_list[1];
321
                } else if ($v_size > 2) {
322
                    $this->privErrorLog(
323
                        self::ERR_INVALID_PARAMETER,
324
                        "Invalid number / type of arguments"
325
                    );
326
                    return 0;
327
                }
328
            }
329
        }
330
        // Look for default option values
331
        $this->privOptionDefaultThreshold($v_options);
332
        // Init
333
        $v_string_list    = array();
334
        $v_att_list       = array();
335
        $v_filedescr_list = array();
336
        $p_result_list    = array();
337
        // Look if the $p_filelist is really an array
338
        if (is_array($p_filelist)) {
339
            // Look if the first element is also an array
340
            // This will mean that this is a file description entry
341
            if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
342
                $v_att_list = $p_filelist;
343
            } else {
344
                // The list is a list of string names
345
                $v_string_list = $p_filelist;
346
            }
347
        } else if (is_string($p_filelist)) {
348
            // Look if the $p_filelist is a string
349
            // Create a list from the string
350
            $v_string_list = explode(self::SEPARATOR, $p_filelist);
351
        } else {
352
            // Invalid variable type for $p_filelist
353
            $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
354
            return 0;
355
        }
356
        // Reformat the string list
357
        if (sizeof($v_string_list) != 0) {
358
            foreach ($v_string_list as $v_string) {
359
                if ($v_string != '') {
360
                  $v_att_list[][self::ATT_FILE_NAME] = $v_string;
361
                } else { }
362
            }
363
        }
364
        // For each file in the list check the attributes
365
        $v_supported_attributes = array (
366
            self::ATT_FILE_NAME           => 'mandatory',
367
            self::ATT_FILE_NEW_SHORT_NAME => 'optional',
368
            self::ATT_FILE_NEW_FULL_NAME  => 'optional',
369
            self::ATT_FILE_MTIME          => 'optional',
370
            self::ATT_FILE_CONTENT        => 'optional',
371
            self::ATT_FILE_COMMENT        => 'optional',
372
        );
373
        foreach ($v_att_list as $v_entry) {
374
            $v_result = $this->privFileDescrParseAtt(
375
                $v_entry,
376
                $v_filedescr_list[],
377
                $v_options,
378
                $v_supported_attributes
379
            );
380
            if ($v_result != 1) {
381
                return 0;
382
            }
383
        }
384
        // Expand the filelist (expand directories)
385
        $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
386
        if ($v_result != 1) {
387
            return 0;
388
        }
389
        // Call the create fct
390
        $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
391
        if ($v_result != 1) {
392
            return 0;
393
        }
394
        return $p_result_list;
395
    }
396
  // --------------------------------------------------------------------------------
397

    
398
  // --------------------------------------------------------------------------------
399
  // Function :
400
  //   add($p_filelist, $p_add_dir="", $p_remove_dir="")
401
  //   add($p_filelist, $p_option, $p_option_value, ...)
402
  // Description :
403
  //   This method supports two synopsis. The first one is historical.
404
  //   This methods add the list of files in an existing archive.
405
  //   If a file with the same name already exists, it is added at the end of the
406
  //   archive, the first one is still present.
407
  //   If the archive does not exist, it is created.
408
  // Parameters :
409
  //   $p_filelist : An array containing file or directory names, or
410
  //                 a string containing one filename or one directory name, or
411
  //                 a string containing a list of filenames and/or directory
412
  //                 names separated by spaces.
413
  //   $p_add_dir : A path to add before the real path of the archived file,
414
  //                in order to have it memorized in the archive.
415
  //   $p_remove_dir : A path to remove from the real path of the file to archive,
416
  //                   in order to have a shorter path memorized in the archive.
417
  //                   When $p_add_dir and $p_remove_dir are set, $p_remove_dir
418
  //                   is removed first, before $p_add_dir is added.
419
  // Options :
420
  //   self::OPT_ADD_PATH :
421
  //   self::OPT_REMOVE_PATH :
422
  //   self::OPT_REMOVE_ALL_PATH :
423
  //   self::OPT_COMMENT :
424
  //   self::OPT_ADD_COMMENT :
425
  //   self::OPT_PREPEND_COMMENT :
426
  //   self::CB_PRE_ADD :
427
  //   self::CB_POST_ADD :
428
  // Return Values :
429
  //   0 on failure,
430
  //   The list of the added files, with a status of the add action.
431
  //   (see self::listContent() for list entry format)
432
  // --------------------------------------------------------------------------------
433
    public function add($p_filelist)
434
    {
435
        $v_result = 1;
436
        // Reset the error handler
437
        $this->privErrorReset();
438
        // Set default values
439
        $v_options = array();
440
        $v_options[self::OPT_NO_COMPRESSION] = false;
441
        // Look for variable options arguments
442
        $v_size = func_num_args();
443
        // Look for arguments
444
        if ($v_size > 1) {
445
            // Get the arguments
446
            $v_arg_list = func_get_args();
447
            // Remove form the options list the first argument
448
            array_shift($v_arg_list);
449
            $v_size--;
450
            // Look for first arg
451
            if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
452
                // Parse the options
453
                $v_result = $this->privParseOptions(
454
                    $v_arg_list,
455
                    $v_size,
456
                    $v_options,
457
                    array (
458
                        self::OPT_REMOVE_PATH         => 'optional',
459
                        self::OPT_REMOVE_ALL_PATH     => 'optional',
460
                        self::OPT_ADD_PATH            => 'optional',
461
                        self::CB_PRE_ADD              => 'optional',
462
                        self::CB_POST_ADD             => 'optional',
463
                        self::OPT_NO_COMPRESSION      => 'optional',
464
                        self::OPT_COMMENT             => 'optional',
465
                        self::OPT_ADD_COMMENT         => 'optional',
466
                        self::OPT_PREPEND_COMMENT     => 'optional',
467
                        self::OPT_TEMP_FILE_THRESHOLD => 'optional',
468
                        self::OPT_TEMP_FILE_ON        => 'optional',
469
                        //self::OPT_CRYPT               => 'optional',
470
                        self::OPT_TEMP_FILE_OFF       => 'optional'
471
                    )
472
                );
473
                if ($v_result != 1) {
474
                    return 0;
475
                }
476
            } else {
477
                // Look for 2 args
478
                // Here we need to support the first historic synopsis of the
479
                // method.
480
                // Get the first argument
481
                $v_options[self::OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
482
                // Look for the optional second argument
483
                if ($v_size == 2) {
484
                    $v_options[self::OPT_REMOVE_PATH] = $v_arg_list[1];
485
                } else if ($v_size > 2) {
486
                    // Error log
487
                    $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
488
                    return 0;
489
                }
490
            }
491
        }
492
        // Look for default option values
493
        $this->privOptionDefaultThreshold($v_options);
494
        // Init
495
        $v_string_list = array();
496
        $v_att_list = array();
497
        $v_filedescr_list = array();
498
        $p_result_list = array();
499
        // Look if the $p_filelist is really an array
500
        if (is_array($p_filelist)) {
501
            // Look if the first element is also an array
502
            // This will mean that this is a file description entry
503
            if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
504
                $v_att_list = $p_filelist;
505
            } else {
506
                // The list is a list of string names
507
                $v_string_list = $p_filelist;
508
            }
509
        } else if (is_string($p_filelist)) {
510
            // Look if the $p_filelist is a string
511
            // Create a list from the string
512
            $v_string_list = explode(self::SEPARATOR, $p_filelist);
513
        } else {
514
        // Invalid variable type for $p_filelist
515
            $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
516
            return 0;
517
        }
518
        // Reformat the string list
519
        if (sizeof($v_string_list) != 0) {
520
            foreach ($v_string_list as $v_string) {
521
                $v_att_list[][self::ATT_FILE_NAME] = $v_string;
522
            }
523
        }
524
        // For each file in the list check the attributes
525
        $v_supported_attributes = array(
526
            self::ATT_FILE_NAME           => 'mandatory',
527
            self::ATT_FILE_NEW_SHORT_NAME => 'optional',
528
            self::ATT_FILE_NEW_FULL_NAME  => 'optional',
529
            self::ATT_FILE_MTIME          => 'optional',
530
            self::ATT_FILE_CONTENT        => 'optional',
531
            self::ATT_FILE_COMMENT        => 'optional'
532
        );
533
        foreach ($v_att_list as $v_entry) {
534
            $v_result = $this->privFileDescrParseAtt(
535
                $v_entry,
536
                $v_filedescr_list[],
537
                $v_options,
538
                $v_supported_attributes
539
            );
540
            if ($v_result != 1) {
541
                return 0;
542
            }
543
        }
544
        // Expand the filelist (expand directories)
545
        $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
546
        if ($v_result != 1) {
547
            return 0;
548
        }
549
        // Call the create fct
550
        $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
551
        if ($v_result != 1) {
552
            return 0;
553
        }
554
        return $p_result_list;
555
    }
556
  // --------------------------------------------------------------------------------
557

    
558
  // --------------------------------------------------------------------------------
559
  // Function : listContent()
560
  // Description :
561
  //   This public method, gives the list of the files and directories, with their
562
  //   properties.
563
  //   The properties of each entries in the list are (used also in other functions) :
564
  //     filename : Name of the file. For a create or add action it is the filename
565
  //                given by the user. For an extract function it is the filename
566
  //                of the extracted file.
567
  //     stored_filename : Name of the file / directory stored in the archive.
568
  //     size : Size of the stored file.
569
  //     compressed_size : Size of the file's data compressed in the archive
570
  //                       (without the headers overhead)
571
  //     mtime : Last known modification date of the file (UNIX timestamp)
572
  //     comment : Comment associated with the file
573
  //     folder : true | false
574
  //     index : index of the file in the archive
575
  //     status : status of the action (depending of the action) :
576
  //              Values are :
577
  //                ok : OK !
578
  //                filtered : the file / dir is not extracted (filtered by user)
579
  //                already_a_directory : the file can not be extracted because a
580
  //                                      directory with the same name already exists
581
  //                write_protected : the file can not be extracted because a file
582
  //                                  with the same name already exists and is
583
  //                                  write protected
584
  //                newer_exist : the file was not extracted because a newer file exists
585
  //                path_creation_fail : the file is not extracted because the folder
586
  //                                     does not exist and can not be created
587
  //                write_error : the file was not extracted because there was a
588
  //                              error while writing the file
589
  //                read_error : the file was not extracted because there was a error
590
  //                             while reading the file
591
  //                invalid_header : the file was not extracted because of an archive
592
  //                                 format error (bad file header)
593
  //   Note that each time a method can continue operating when there
594
  //   is an action error on a file, the error is only logged in the file status.
595
  // Return Values :
596
  //   0 on an unrecoverable failure,
597
  //   The list of the files in the archive.
598
  // --------------------------------------------------------------------------------
599
    public function listContent()
600
    {
601
        $v_result = 1;
602
        // Reset the error handler
603
        $this->privErrorReset();
604
        // Check archive
605
        if (!$this->privCheckFormat()) {
606
            return(0);
607
        }
608
        // Call the extracting fct
609
        $p_list = array();
610
        if (($v_result = $this->privList($p_list)) != 1) {
611
            unset($p_list);
612
            return(0);
613
        }
614
        return $p_list;
615
    }
616
  // --------------------------------------------------------------------------------
617

    
618
  // --------------------------------------------------------------------------------
619
  // Function :
620
  //   extract($p_path="./", $p_remove_path="")
621
  //   extract([$p_option, $p_option_value, ...])
622
  // Description :
623
  //   This method supports two synopsis. The first one is historical.
624
  //   This method extract all the files / directories from the archive to the
625
  //   folder indicated in $p_path.
626
  //   If you want to ignore the 'root' part of path of the memorized files
627
  //   you can indicate this in the optional $p_remove_path parameter.
628
  //   By default, if a newer file with the same name already exists, the
629
  //   file is not extracted.
630
  //
631
  //   If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions
632
  //   are used, the path indicated in PCLZIP_OPT_ADD_PATH is append
633
  //   at the end of the path value of PCLZIP_OPT_PATH.
634
  // Parameters :
635
  //   $p_path : Path where the files and directories are to be extracted
636
  //   $p_remove_path : First part ('root' part) of the memorized path
637
  //                    (if any similar) to remove while extracting.
638
  // Options :
639
  //   PCLZIP_OPT_PATH :
640
  //   PCLZIP_OPT_ADD_PATH :
641
  //   PCLZIP_OPT_REMOVE_PATH :
642
  //   PCLZIP_OPT_REMOVE_ALL_PATH :
643
  //   PCLZIP_CB_PRE_EXTRACT :
644
  //   PCLZIP_CB_POST_EXTRACT :
645
  // Return Values :
646
  //   0 or a negative value on failure,
647
  //   The list of the extracted files, with a status of the action.
648
  //   (see PclZip::listContent() for list entry format)
649
  // --------------------------------------------------------------------------------
650
    public function extract()
651
    {
652
        $v_result = 1;
653
        // Reset the error handler
654
        $this->privErrorReset();
655
        // Check archive
656
        if (!$this->privCheckFormat()) {
657
            return(0);
658
        }
659
        // Set default values
660
        $v_options         = array();
661
        $v_path            = '';
662
        $v_remove_path     = "";
663
        $v_remove_all_path = false;
664
        // Look for variable options arguments
665
        $v_size = func_num_args();
666
        // Default values for option
667
        $v_options[self::OPT_EXTRACT_AS_STRING] = false;
668
        // Look for arguments
669
        if ($v_size > 0) {
670
            // Get the arguments
671
            $v_arg_list = func_get_args();
672
            // Look for first arg
673
            if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
674
                // Parse the options
675
                $v_result = $this->privParseOptions(
676
                    $v_arg_list,
677
                    $v_size,
678
                    $v_options,
679
                    array (
680
                        self::OPT_PATH                    => 'optional',
681
                        self::OPT_REMOVE_PATH             => 'optional',
682
                        self::OPT_REMOVE_ALL_PATH         => 'optional',
683
                        self::OPT_ADD_PATH                => 'optional',
684
                        self::CB_PRE_EXTRACT              => 'optional',
685
                        self::CB_POST_EXTRACT             => 'optional',
686
                        self::OPT_SET_CHMOD               => 'optional',
687
                        self::OPT_BY_NAME                 => 'optional',
688
                        self::OPT_BY_EREG                 => 'optional',
689
                        self::OPT_BY_PREG                 => 'optional',
690
                        self::OPT_BY_INDEX                => 'optional',
691
                        self::OPT_EXTRACT_AS_STRING       => 'optional',
692
                        self::OPT_EXTRACT_IN_OUTPUT       => 'optional',
693
                        self::OPT_REPLACE_NEWER           => 'optional',
694
                        self::OPT_STOP_ON_ERROR           => 'optional',
695
                        self::OPT_EXTRACT_DIR_RESTRICTION => 'optional',
696
                        self::OPT_TEMP_FILE_THRESHOLD     => 'optional',
697
                        self::OPT_TEMP_FILE_ON            => 'optional',
698
                        self::OPT_TEMP_FILE_OFF           => 'optional'
699
                    )
700
                );
701
                if ($v_result != 1) {
702
                    return 0;
703
                }
704
                // Set the arguments
705
                if (isset($v_options[self::OPT_PATH])) {
706
                    $v_path = $v_options[self::OPT_PATH];
707
                }
708
                if (isset($v_options[self::OPT_REMOVE_PATH])) {
709
                    $v_remove_path = $v_options[self::OPT_REMOVE_PATH];
710
                }
711
                if (isset($v_options[self::OPT_REMOVE_ALL_PATH])) {
712
                    $v_remove_all_path = $v_options[self::OPT_REMOVE_ALL_PATH];
713
                }
714
                if (isset($v_options[self::OPT_ADD_PATH])) {
715
                    // Check for '/' in last path char
716
                    if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
717
                        $v_path .= '/';
718
                    }
719
                    $v_path .= $v_options[self::OPT_ADD_PATH];
720
                }
721
            } else {
722
                // Look for 2 args
723
                // Here we need to support the first historic synopsis of the
724
                // method.
725
                // Get the first argument
726
                $v_path = $v_arg_list[0];
727
                // Look for the optional second argument
728
                if ($v_size == 2) {
729
                    $v_remove_path = $v_arg_list[1];
730
                } else if ($v_size > 2) {
731
                    // Error log
732
                    $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
733
                    return 0;
734
                }
735
            }
736
        }
737
        // Look for default option values
738
        $this->privOptionDefaultThreshold($v_options);
739
        // Trace
740
        // Call the extracting fct
741
        $p_list = array();
742
        $v_result = $this->privExtractByRule(
743
            $p_list,
744
            $v_path,
745
            $v_remove_path,
746
            $v_remove_all_path,
747
            $v_options
748
        );
749
        if ($v_result < 1) {
750
            unset($p_list);
751
            return(0);
752
        }
753
        return $p_list;
754
    }
755
  // --------------------------------------------------------------------------------
756

    
757

    
758
  // --------------------------------------------------------------------------------
759
  // Function :
760
  //   extractByIndex($p_index, $p_path="./", $p_remove_path="")
761
  //   extractByIndex($p_index, [$p_option, $p_option_value, ...])
762
  // Description :
763
  //   This method supports two synopsis. The first one is historical.
764
  //   This method is doing a partial extract of the archive.
765
  //   The extracted files or folders are identified by their index in the
766
  //   archive (from 0 to n).
767
  //   Note that if the index identify a folder, only the folder entry is
768
  //   extracted, not all the files included in the archive.
769
  // Parameters :
770
  //   $p_index : A single index (integer) or a string of indexes of files to
771
  //              extract. The form of the string is "0,4-6,8-12" with only numbers
772
  //              and '-' for range or ',' to separate ranges. No spaces or ';'
773
  //              are allowed.
774
  //   $p_path : Path where the files and directories are to be extracted
775
  //   $p_remove_path : First part ('root' part) of the memorized path
776
  //                    (if any similar) to remove while extracting.
777
  // Options :
778
  //   OPT_PATH :
779
  //   OPT_ADD_PATH :
780
  //   OPT_REMOVE_PATH :
781
  //   OPT_REMOVE_ALL_PATH :
782
  //   OPT_EXTRACT_AS_STRING : The files are extracted as strings and
783
  //     not as files.
784
  //     The resulting content is in a new field 'content' in the file
785
  //     structure.
786
  //     This option must be used alone (any other options are ignored).
787
  //   CB_PRE_EXTRACT :
788
  //   CB_POST_EXTRACT :
789
  // Return Values :
790
  //   0 on failure,
791
  //   The list of the extracted files, with a status of the action.
792
  //   (see PclZip::listContent() for list entry format)
793
  // --------------------------------------------------------------------------------
794
  //function extractByIndex($p_index, options...)
795
    public function extractByIndex($p_index)
796
    {
797
        $v_result = 1;
798
        // Reset the error handler
799
        $this->privErrorReset();
800
        // Check archive
801
        if (!$this->privCheckFormat()) {
802
            return(0);
803
        }
804
        // Set default values
805
        $v_options         = array();
806
        $v_path            = '';
807
        $v_remove_path     = "";
808
        $v_remove_all_path = false;
809
        // Look for variable options arguments
810
        $v_size = func_num_args();
811
        // Default values for option
812
        $v_options[self::OPT_EXTRACT_AS_STRING] = false;
813
        // Look for arguments
814
        if ($v_size > 1) {
815
            // Get the arguments
816
            $v_arg_list = func_get_args();
817
            // Remove form the options list the first argument
818
            array_shift($v_arg_list);
819
            $v_size--;
820
            // Look for first arg
821
            if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
822
                // Parse the options
823
                $v_result = $this->privParseOptions(
824
                    $v_arg_list,
825
                    $v_size,
826
                    $v_options,
827
                    array(
828
                        self::OPT_PATH                    => 'optional',
829
                        self::OPT_REMOVE_PATH             => 'optional',
830
                        self::OPT_REMOVE_ALL_PATH         => 'optional',
831
                        self::OPT_EXTRACT_AS_STRING       => 'optional',
832
                        self::OPT_ADD_PATH                => 'optional',
833
                        self::CB_PRE_EXTRACT              => 'optional',
834
                        self::CB_POST_EXTRACT             => 'optional',
835
                        self::OPT_SET_CHMOD               => 'optional',
836
                        self::OPT_REPLACE_NEWER           => 'optional',
837
                        self::OPT_STOP_ON_ERROR           => 'optional',
838
                        self::OPT_EXTRACT_DIR_RESTRICTION => 'optional',
839
                        self::OPT_TEMP_FILE_THRESHOLD     => 'optional',
840
                        self::OPT_TEMP_FILE_ON            => 'optional',
841
                        self::OPT_TEMP_FILE_OFF           => 'optional'
842
                    )
843
                );
844
                if ($v_result != 1) {
845
                    return 0;
846
                }
847
                // Set the arguments
848
                if (isset($v_options[self::OPT_PATH])) {
849
                    $v_path = $v_options[self::OPT_PATH];
850
                }
851
                if (isset($v_options[self::OPT_REMOVE_PATH])) {
852
                    $v_remove_path = $v_options[self::OPT_REMOVE_PATH];
853
                }
854
                if (isset($v_options[self::OPT_REMOVE_ALL_PATH])) {
855
                    $v_remove_all_path = $v_options[self::OPT_REMOVE_ALL_PATH];
856
                }
857
                if (isset($v_options[self::OPT_ADD_PATH])) {
858
                    // Check for '/' in last path char
859
                    if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
860
                        $v_path .= '/';
861
                    }
862
                    $v_path .= $v_options[self::OPT_ADD_PATH];
863
                }
864
                if (!isset($v_options[self::OPT_EXTRACT_AS_STRING])) {
865
                    $v_options[self::OPT_EXTRACT_AS_STRING] = FALSE;
866
                } else { }
867
            } else {
868
                // Look for 2 args
869
                // Here we need to support the first historic synopsis of the
870
                // method.
871
                // Get the first argument
872
                $v_path = $v_arg_list[0];
873
                // Look for the optional second argument
874
                if ($v_size == 2) {
875
                    $v_remove_path = $v_arg_list[1];
876
                } else if ($v_size > 2) {
877
                    // Error log
878
                    $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
879
                    return 0;
880
                }
881
            }
882
        }
883
        // Trace - Trick
884
        // Here I want to reuse extractByRule(), so I need to parse the $p_index with privParseOptions()
885
        $v_arg_trick = array (self::OPT_BY_INDEX, $p_index);
886
        $v_options_trick = array();
887
        $v_result = $this->privParseOptions(
888
            $v_arg_trick,
889
            sizeof($v_arg_trick),
890
            $v_options_trick,
891
            array(self::OPT_BY_INDEX => 'optional' )
892
        );
893
        if ($v_result != 1) {
894
            return 0;
895
        }
896
        $v_options[self::OPT_BY_INDEX] = $v_options_trick[self::OPT_BY_INDEX];
897
        // Look for default option values
898
        $this->privOptionDefaultThreshold($v_options);
899
        // Call the extracting fct
900
        $p_list = 0;
901
        if (($v_result = $this->privExtractByRule(
902
                $p_list,
903
                $v_path,
904
                $v_remove_path,
905
                $v_remove_all_path,
906
                $v_options
907
            )) < 1
908
        ) { return(0); }
909
        return $p_list;
910
    }
911
  // --------------------------------------------------------------------------------
912

    
913
  // --------------------------------------------------------------------------------
914
  // Function :
915
  //   delete([$p_option, $p_option_value, ...])
916
  // Description :
917
  //   This method removes files from the archive.
918
  //   If no parameters are given, then all the archive is emptied.
919
  // Parameters :
920
  //   None or optional arguments.
921
  // Options :
922
  //   PCLZIP_OPT_BY_INDEX :
923
  //   PCLZIP_OPT_BY_NAME :
924
  //   PCLZIP_OPT_BY_EREG :
925
  //   PCLZIP_OPT_BY_PREG :
926
  // Return Values :
927
  //   0 on failure,
928
  //   The list of the files which are still present in the archive.
929
  //   (see PclZip::listContent() for list entry format)
930
  // --------------------------------------------------------------------------------
931
    public function delete()
932
    {
933
        $v_result = 1;
934
        // Reset the error handler
935
        $this->privErrorReset();
936
        // Check archive
937
        if (!$this->privCheckFormat()) {
938
            return(0);
939
        }
940
        // Set default values
941
        $v_options = array();
942
        // Look for variable options arguments
943
        $v_size = func_num_args();
944
        // Look for arguments
945
        if ($v_size > 0) {
946
            // Get the arguments
947
            $v_arg_list = func_get_args();
948
            // Parse the options
949
            $v_result = $this->privParseOptions(
950
                $v_arg_list,
951
                $v_size,
952
                $v_options,
953
                array(
954
                    self::OPT_BY_NAME  => 'optional',
955
                    self::OPT_BY_EREG  => 'optional',
956
                    self::OPT_BY_PREG  => 'optional',
957
                    self::OPT_BY_INDEX => 'optional'
958
                )
959
            );
960
            if ($v_result != 1) {
961
                return 0;
962
            }
963
        }
964
        // Magic quotes trick
965
        $this->privDisableMagicQuotes();
966
        // Call the delete fct
967
        $v_list = array();
968
        if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
969
            $this->privSwapBackMagicQuotes();
970
            unset($v_list);
971
            return(0);
972
        }
973
        // Magic quotes trick
974
        $this->privSwapBackMagicQuotes();
975
        return $v_list;
976
    }
977
  // --------------------------------------------------------------------------------
978

    
979
  // --------------------------------------------------------------------------------
980
  // Function : deleteByIndex()
981
  // Description :
982
  //   ***** Deprecated *****
983
  //   delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered.
984
  // --------------------------------------------------------------------------------
985
    public function deleteByIndex($p_index)
986
    {
987
        $p_list = $this->delete(self::OPT_BY_INDEX, $p_index);
988
        return $p_list;
989
    }
990
  // --------------------------------------------------------------------------------
991

    
992
  // --------------------------------------------------------------------------------
993
  // Function : properties()
994
  // Description :
995
  //   This method gives the properties of the archive.
996
  //   The properties are :
997
  //     nb : Number of files in the archive
998
  //     comment : Comment associated with the archive file
999
  //     status : not_exist, ok
1000
  // Parameters :
1001
  //   None
1002
  // Return Values :
1003
  //   0 on failure,
1004
  //   An array with the archive properties.
1005
  // --------------------------------------------------------------------------------
1006
    public function properties()
1007
    {
1008
        // Reset the error handler
1009
        $this->privErrorReset();
1010
        // Magic quotes trick
1011
        $this->privDisableMagicQuotes();
1012
        // Check archive
1013
        if (!$this->privCheckFormat()) {
1014
            $this->privSwapBackMagicQuotes();
1015
            return(0);
1016
        }
1017
        // Default properties
1018
        $v_prop = array(
1019
            'comment' => '',
1020
            'nb'      => 0,
1021
            'status'  => 'not_exist'
1022
        );
1023
        // Look if file exists
1024
        if (@is_file($this->zipname)) {
1025
            // Open the zip file
1026
            if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) {
1027
                $this->privSwapBackMagicQuotes();
1028
                // Error log
1029
                $this->privErrorLog(self::ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
1030
                return 0;
1031
            }
1032
            // Read the central directory informations
1033
            $v_central_dir = array();
1034
            if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
1035
                $this->privSwapBackMagicQuotes();
1036
                return 0;
1037
            }
1038
            // Close the zip file
1039
            $this->privCloseFd();
1040
            // Set the user attributes
1041
            $v_prop['comment'] = $v_central_dir['comment'];
1042
            $v_prop['nb']      = $v_central_dir['entries'];
1043
            $v_prop['status']  = 'ok';
1044
        }
1045
        // Magic quotes trick
1046
        $this->privSwapBackMagicQuotes();
1047
        return $v_prop;
1048
    }
1049
  // --------------------------------------------------------------------------------
1050

    
1051
  // --------------------------------------------------------------------------------
1052
  // Function : duplicate()
1053
  // Description :
1054
  //   This method creates an archive by copying the content of an other one. If
1055
  //   the archive already exist, it is replaced by the new one without any warning.
1056
  // Parameters :
1057
  //   $p_archive : The filename of a valid archive, or
1058
  //                a valid PclZip object.
1059
  // Return Values :
1060
  //   1 on success.
1061
  //   0 or a negative value on error (error code).
1062
  // --------------------------------------------------------------------------------
1063
    public function duplicate($p_archive)
1064
    {
1065
        $v_result = 1;
1066
        // Reset the error handler
1067
        $this->privErrorReset();
1068
        // Look if the $p_archive is a PclZip object
1069
        if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) {
1070
            // Duplicate the archive
1071
            $v_result = $this->privDuplicate($p_archive->zipname);
1072
        } else if (is_string($p_archive)) {
1073
            // Look if the $p_archive is a string (so a filename)
1074
            // Check that $p_archive is a valid zip file
1075
            // TBC : Should also check the archive format
1076
            if (!is_file($p_archive)) {
1077
                // Error log
1078
                $this->privErrorLog(self::ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
1079
                $v_result = self::ERR_MISSING_FILE;
1080
            } else {
1081
                // Duplicate the archive
1082
                $v_result = $this->privDuplicate($p_archive);
1083
            }
1084
        } else {
1085
            // Invalid variable
1086
            // Error log
1087
            $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
1088
            $v_result = self::ERR_INVALID_PARAMETER;
1089
        }
1090
        return $v_result;
1091
    }
1092
  // --------------------------------------------------------------------------------
1093

    
1094
  // --------------------------------------------------------------------------------
1095
  // Function : merge()
1096
  // Description :
1097
  //   This method merge the $p_archive_to_add archive at the end of the current
1098
  //   one ($this).
1099
  //   If the archive ($this) does not exist, the merge becomes a duplicate.
1100
  //   If the $p_archive_to_add archive does not exist, the merge is a success.
1101
  // Parameters :
1102
  //   $p_archive_to_add : It can be directly the filename of a valid zip archive,
1103
  //                       or a PclZip object archive.
1104
  // Return Values :
1105
  //   1 on success,
1106
  //   0 or negative values on error (see below).
1107
  // --------------------------------------------------------------------------------
1108
    public function merge($p_archive_to_add)
1109
    {
1110
        $v_result = 1;
1111
        // Reset the error handler
1112
        $this->privErrorReset();
1113
        // Check archive
1114
        if (!$this->privCheckFormat()) {
1115
            return(0);
1116
        }
1117
        // Look if the $p_archive_to_add is a PclZip object
1118
        if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) {
1119
            // Merge the archive
1120
            $v_result = $this->privMerge($p_archive_to_add);
1121
        } else if (is_string($p_archive_to_add)) {
1122
            // Look if the $p_archive_to_add is a string (so a filename)
1123
            // Create a temporary archive
1124
            $oClass = __CLASS__;
1125
            $v_object_archive = new $oClass($p_archive_to_add);
1126
            // Merge the archive
1127
            $v_result = $this->privMerge($v_object_archive);
1128
        } else {
1129
            // Invalid variable
1130
            // Error log
1131
            $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
1132
            $v_result = self::ERR_INVALID_PARAMETER;
1133
        }
1134
        return $v_result;
1135
    }
1136
  // --------------------------------------------------------------------------------
1137

    
1138

    
1139

    
1140
  // --------------------------------------------------------------------------------
1141
  // Function : errorCode()
1142
  // Description :
1143
  // Parameters :
1144
  // --------------------------------------------------------------------------------
1145
    public function errorCode()
1146
    {
1147
        if (self::ERROR_EXTERNAL == 1) {
1148
            return(PclErrorCode());
1149
        } else {
1150
            return($this->error_code);
1151
        }
1152
    }
1153
  // --------------------------------------------------------------------------------
1154

    
1155
  // --------------------------------------------------------------------------------
1156
  // Function : errorName()
1157
  // Description :
1158
  // Parameters :
1159
  // --------------------------------------------------------------------------------
1160
    public function errorName($p_with_code=false)
1161
    {
1162
        $aFullList = array_flip($this->getClassConstants());
1163
        $sRetval = isset($aFullList[$this->error_code])
1164
                   ? __CLASS__.'::'.$aFullList[$this->error_code]
1165
                   : 'Unknown code';
1166
        $sRetval .= $p_with_code ? ' ('.$this->error_code.')' : '';
1167
        return $sRetval;
1168
    }
1169
  // --------------------------------------------------------------------------------
1170

    
1171
  // --------------------------------------------------------------------------------
1172
  // Function : errorInfo()
1173
  // Description :
1174
  // Parameters :
1175
  // --------------------------------------------------------------------------------
1176
    public function errorInfo($p_full=false)
1177
    {
1178
        if (self::ERROR_EXTERNAL == 1) {
1179
            return(PclErrorString());
1180
        } else {
1181
            if ($p_full) {
1182
                return($this->errorName(true)." : ".$this->error_string);
1183
            } else {
1184
                return($this->error_string." [code ".$this->error_code."]");
1185
            }
1186
        }
1187
    }
1188
  // --------------------------------------------------------------------------------
1189

    
1190
// --------------------------------------------------------------------------------
1191
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
1192
// *****                                                        *****
1193
// *****       THESES FUNCTIONS MUST NOT BE USED DIRECTLY       *****
1194
// --------------------------------------------------------------------------------
1195

    
1196

    
1197

    
1198
  // --------------------------------------------------------------------------------
1199
  // Function : privCheckFormat()
1200
  // Description :
1201
  //   This method check that the archive exists and is a valid zip archive.
1202
  //   Several level of check exists. (futur)
1203
  // Parameters :
1204
  //   $p_level : Level of check. Default 0.
1205
  //              0 : Check the first bytes (magic codes) (default value))
1206
  //              1 : 0 + Check the central directory (futur)
1207
  //              2 : 1 + Check each file header (futur)
1208
  // Return Values :
1209
  //   true on success,
1210
  //   false on error, the error code is set.
1211
  // --------------------------------------------------------------------------------
1212
    protected function privCheckFormat($p_level=0)
1213
    {
1214
        $v_result = true;
1215
        // Reset the file system cache
1216
        clearstatcache();
1217
        // Reset the error handler
1218
        $this->privErrorReset();
1219
        // Look if the file exits
1220
        if (!is_file($this->zipname)) {
1221
            // Error log
1222
            $this->privErrorLog(self::ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
1223
            return false;
1224
        }
1225
        // Check that the file is readeable
1226
        if (!is_readable($this->zipname)) {
1227
            // Error log
1228
            $this->privErrorLog(self::ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
1229
            return false;
1230
        }
1231
        // Check the magic code
1232
        // TBC
1233
        // Check the central header
1234
        // TBC
1235
        // Check each file header
1236
        // TBC
1237
        // Return
1238
        return $v_result;
1239
    }
1240
  // --------------------------------------------------------------------------------
1241

    
1242
  // --------------------------------------------------------------------------------
1243
  // Function : privParseOptions()
1244
  // Description :
1245
  //   This internal methods reads the variable list of arguments ($p_options_list,
1246
  //   $p_size) and generate an array with the options and values ($v_result_list).
1247
  //   $v_requested_options contains the options that can be present and those that
1248
  //   must be present.
1249
  //   $v_requested_options is an array, with the option value as key, and 'optional',
1250
  //   or 'mandatory' as value.
1251
  // Parameters :
1252
  //   See above.
1253
  // Return Values :
1254
  //   1 on success.
1255
  //   0 on failure.
1256
  // --------------------------------------------------------------------------------
1257
    protected function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
1258
    {
1259
        $v_result=1;
1260
        // Read the options
1261
        $i=0;
1262
        while ($i<$p_size) {
1263
            // Check if the option is supported
1264
            if (!isset($v_requested_options[$p_options_list[$i]])) {
1265
                // Error log
1266
                $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
1267
                return PclZip::errorCode();
1268
            }
1269
            // Look for next option
1270
            switch ($p_options_list[$i]) {
1271
              // Look for options that request a path value
1272
                case self::OPT_PATH :
1273
                case self::OPT_REMOVE_PATH :
1274
                case self::OPT_ADD_PATH :
1275
                    // Check the number of parameters
1276
                    if (($i+1) >= $p_size) {
1277
                        // Error log
1278
                        $this->privErrorLog(
1279
                            self::ERR_MISSING_OPTION_VALUE,
1280
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1281
                        );
1282
                        return self::errorCode();
1283
                    }
1284
                    // Get the value
1285
                    $v_result_list[$p_options_list[$i]] = self::UtilTranslateWinPath($p_options_list[$i+1], false);
1286
                    $i++;
1287
                    break;
1288
               case self::OPT_TEMP_FILE_THRESHOLD :
1289
                    // Check the number of parameters
1290
                    if (($i+1) >= $p_size) {
1291
                        $this->privErrorLog(
1292
                            self::ERR_MISSING_OPTION_VALUE,
1293
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1294
                        );
1295
                        return self::errorCode();
1296
                    }
1297
                    // Check for incompatible options
1298
                    if (isset($v_result_list[self::OPT_TEMP_FILE_OFF])) {
1299
                        $this->privErrorLog(
1300
                            self::ERR_INVALID_PARAMETER,
1301
                            'Option \''.self::UtilOptionText($p_options_list[$i]).
1302
                            '\' can not be used with option \''.__CLASS__.'::OPT_TEMP_FILE_OFF\''
1303
                        );
1304
                        return self::errorCode();
1305
                    }
1306
                    // Check the value
1307
                    $v_value = $p_options_list[$i+1];
1308
                    if ((!is_integer($v_value)) || ($v_value<0)) {
1309
                        $this->privErrorLog(
1310
                            self::ERR_INVALID_OPTION_VALUE,
1311
                            'Integer expected for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1312
                        );
1313
                        return self::errorCode();
1314
                    }
1315
                    // Get the value (and convert it in bytes)
1316
                    $v_result_list[$p_options_list[$i]] = $v_value*1048576;
1317
                    $i++;
1318
                    break;
1319
                case self::OPT_TEMP_FILE_ON :
1320
                    // Check for incompatible options
1321
                    if (isset($v_result_list[self::OPT_TEMP_FILE_OFF])) {
1322
                        $this->privErrorLog(
1323
                            self::ERR_INVALID_PARAMETER,
1324
                            'Option \''.self::UtilOptionText($p_options_list[$i]).
1325
                            '\' can not be used with option \''.__CLASS__.'::OPT_TEMP_FILE_OFF\''
1326
                        );
1327
                        return self::errorCode();
1328
                    }
1329
                    $v_result_list[$p_options_list[$i]] = true;
1330
                    break;
1331
                case self::OPT_TEMP_FILE_OFF :
1332
                    // Check for incompatible options
1333
                    if (isset($v_result_list[self::OPT_TEMP_FILE_ON])) {
1334
                        $this->privErrorLog(
1335
                            self::ERR_INVALID_PARAMETER,
1336
                            'Option \''.self::UtilOptionText($p_options_list[$i]).
1337
                            '\' can not be used with option \''.__CLASS__.'::OPT_TEMP_FILE_ON\''
1338
                        );
1339
                        return self::errorCode();
1340
                    }
1341
                    // Check for incompatible options
1342
                    if (isset($v_result_list[self::OPT_TEMP_FILE_THRESHOLD])) {
1343
                        $this->privErrorLog(
1344
                            self::ERR_INVALID_PARAMETER,
1345
                            'Option \''.self::UtilOptionText($p_options_list[$i]).
1346
                            '\' can not be used with option \''.__CLASS__.'::OPT_TEMP_FILE_THRESHOLD\''
1347
                        );
1348
                        return self::errorCode();
1349
                    }
1350
                    $v_result_list[$p_options_list[$i]] = true;
1351
                    break;
1352
                case self::OPT_EXTRACT_DIR_RESTRICTION :
1353
                    // Check the number of parameters
1354
                    if (($i+1) >= $p_size) {
1355
                        // Error log
1356
                        $this->privErrorLog(
1357
                            self::ERR_MISSING_OPTION_VALUE,
1358
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1359
                        );
1360
                        return PclZip::errorCode();
1361
                    }
1362
                    // Get the value
1363
                    if (is_string($p_options_list[$i + 1]) && ($p_options_list[$i + 1] != '')) {
1364
                        $v_result_list[$p_options_list[$i]] = self::UtilTranslateWinPath($p_options_list[$i+1], false);
1365
                        $i++;
1366
                    } else { }
1367
                    break;
1368
                // Look for options that request an array of string for value
1369
                case self::OPT_BY_NAME :
1370
                    // Check the number of parameters
1371
                    if (($i + 1) >= $p_size) {
1372
                        // Error log
1373
                        $this->privErrorLog(
1374
                            self::ERR_MISSING_OPTION_VALUE,
1375
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1376
                        );
1377
                        return self::errorCode();
1378
                    }
1379
                    // Get the value
1380
                    if (is_string($p_options_list[$i + 1])) {
1381
                        $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i + 1];
1382
                    } else if (is_array($p_options_list[$i + 1])) {
1383
                        $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
1384
                    } else {
1385
                    // Error log
1386
                        $this->privErrorLog(
1387
                            self::ERR_INVALID_OPTION_VALUE,
1388
                            'Wrong parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1389
                        );
1390
                        return self::errorCode();
1391
                    }
1392
                    $i++;
1393
                    break;
1394
                // Look for options that request an EREG or PREG expression
1395
                case self::OPT_BY_EREG :
1396
                    // ereg() is deprecated starting with PHP 5.3. Move self::OPT_BY_EREG
1397
                    // to self::OPT_BY_PREG
1398
                    $p_options_list[$i] = self::OPT_BY_PREG;
1399
                case self::OPT_BY_PREG :
1400
                //case self::OPT_CRYPT :
1401
                    // Check the number of parameters
1402
                    if (($i + 1) >= $p_size) {
1403
                        // Error log
1404
                        $this->privErrorLog(
1405
                            self::ERR_MISSING_OPTION_VALUE,
1406
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1407
                        );
1408
                        return self::errorCode();
1409
                    }
1410
                    // Get the value
1411
                    if (is_string($p_options_list[$i + 1])) {
1412
                        $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
1413
                    } else {
1414
                        // Error log
1415
                        $this->privErrorLog(
1416
                            self::ERR_INVALID_OPTION_VALUE,
1417
                            'Wrong parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1418
                        );
1419
                        return self::errorCode();
1420
                    }
1421
                    $i++;
1422
                    break;
1423
                // Look for options that takes a string
1424
                case self::OPT_COMMENT :
1425
                case self::OPT_ADD_COMMENT :
1426
                case self::OPT_PREPEND_COMMENT :
1427
                    // Check the number of parameters
1428
                    if (($i + 1) >= $p_size) {
1429
                        // Error log
1430
                        $this->privErrorLog(
1431
                            self::ERR_MISSING_OPTION_VALUE,
1432
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1433
                        );
1434
                        return self::errorCode();
1435
                    }
1436
                    // Get the value
1437
                    if (is_string($p_options_list[$i + 1])) {
1438
                        $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
1439
                    } else {
1440
                        // Error log
1441
                        $this->privErrorLog(
1442
                            self::ERR_INVALID_OPTION_VALUE,
1443
                            'Wrong parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1444
                        );
1445
                        return self::errorCode();
1446
                    }
1447
                    $i++;
1448
                    break;
1449
                // Look for options that request an array of index
1450
                case self::OPT_BY_INDEX :
1451
                    // Check the number of parameters
1452
                    if (($i + 1) >= $p_size) {
1453
                        // Error log
1454
                        $this->privErrorLog(
1455
                            self::ERR_MISSING_OPTION_VALUE,
1456
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1457
                        );
1458
                        return self::errorCode();
1459
                    }
1460
                    // Get the value
1461
                    $v_work_list = array();
1462
                    if (is_string($p_options_list[$i + 1])) {
1463
                        // Remove spaces
1464
                        $p_options_list[$i + 1] = strtr($p_options_list[$i + 1], ' ', '');
1465
                        // Parse items
1466
                        $v_work_list = explode(',', $p_options_list[$i + 1]);
1467
                    } else if (is_integer($p_options_list[$i + 1])) {
1468
                        $v_work_list[0] = $p_options_list[$i + 1].'-'.$p_options_list[$i + 1];
1469
                    } else if (is_array($p_options_list[$i + 1])) {
1470
                        $v_work_list = $p_options_list[$i + 1];
1471
                    } else {
1472
                      // Error log
1473
                        $this->privErrorLog(
1474
                            self::ERR_INVALID_OPTION_VALUE,
1475
                            'Value must be integer, string or array for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1476
                        );
1477
                        return self::errorCode();
1478
                    }
1479
                    // Reduce the index list
1480
                    // each index item in the list must be a couple with a start and
1481
                    // an end value : [0,3], [5-5], [8-10], ...
1482
                    // Check the format of each item
1483
                    $v_sort_flag=false;
1484
                    $v_sort_value=0;
1485
                    for ($j = 0; $j < sizeof($v_work_list); $j++) {
1486
                        // Explode the item
1487
                        $v_item_list = explode('-', $v_work_list[$j]);
1488
                        $v_size_item_list = sizeof($v_item_list);
1489
                        // TBC : Here we might check that each item is a
1490
                        // real integer ...
1491
                        // Look for single value
1492
                        if ($v_size_item_list == 1) {
1493
                            // Set the option value
1494
                            $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
1495
                            $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
1496
                        } elseif ($v_size_item_list == 2) {
1497
                            // Set the option value
1498
                            $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
1499
                            $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
1500
                        } else {
1501
                            // Error log
1502
                            $this->privErrorLog(
1503
                                self::ERR_INVALID_OPTION_VALUE,
1504
                                'Too many values in index range for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1505
                            );
1506
                            return self::errorCode();
1507
                        }
1508
                        // Look for list sort
1509
                        if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
1510
                            $v_sort_flag=true;
1511
                            // TBC : An automatic sort should be writen ...
1512
                            // Error log
1513
                            $this->privErrorLog(
1514
                                self::_ERR_INVALID_OPTION_VALUE,
1515
                                'Invalid order of index range for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1516
                            );
1517
                            return self::errorCode();
1518
                        }
1519
                        $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
1520
                    }
1521
                    // Sort the items
1522
                    if ($v_sort_flag) { /* TBC : To Be Completed */ }
1523
                    // Next option
1524
                    $i++;
1525
                    break;
1526
                // Look for options that request no value
1527
                case self::OPT_REMOVE_ALL_PATH :
1528
                case self::OPT_EXTRACT_AS_STRING :
1529
                case self::OPT_NO_COMPRESSION :
1530
                case self::OPT_EXTRACT_IN_OUTPUT :
1531
                case self::OPT_REPLACE_NEWER :
1532
                case self::OPT_STOP_ON_ERROR :
1533
                    $v_result_list[$p_options_list[$i]] = true;
1534
                    break;
1535
                // Look for options that request an octal value
1536
                case self::OPT_SET_CHMOD :
1537
                    // Check the number of parameters
1538
                    if (($i + 1) >= $p_size) {
1539
                        // Error log
1540
                        $this->privErrorLog(
1541
                            self::ERR_MISSING_OPTION_VALUE,
1542
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1543
                        );
1544
                        return self::errorCode();
1545
                    }
1546
                    // Get the value
1547
                    $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1];
1548
                    $i++;
1549
                    break;
1550
                // Look for options that request a call-back
1551
                case self::CB_PRE_EXTRACT :
1552
                case self::CB_POST_EXTRACT :
1553
                case self::CB_PRE_ADD :
1554
                case self::CB_POST_ADD :
1555
                // for futur use
1556
//                case self::CB_PRE_DELETE :
1557
//                case self::CB_POST_DELETE :
1558
//                case self::CB_PRE_LIST :
1559
//                case self::CB_POST_LIST :
1560
                  // Check the number of parameters
1561
                    if (($i + 1) >= $p_size) {
1562
                        // Error log
1563
                        $this->privErrorLog(
1564
                            self::ERR_MISSING_OPTION_VALUE,
1565
                            'Missing parameter value for option \''.self::UtilOptionText($p_options_list[$i]).'\''
1566
                        );
1567
                        return self::errorCode();
1568
                    }
1569
                    // Get the value
1570
                    $v_function_name = $p_options_list[$i + 1];
1571
                    // Check that the value is a valid existing function
1572
                    if (!function_exists($v_function_name)) {
1573
                        // Error log
1574
                        $this->privErrorLog(
1575
                            self::ERR_INVALID_OPTION_VALUE,
1576
                            'Function \''.$v_function_name.'()\' is not an existing function for option \''.
1577
                            self::UtilOptionText($p_options_list[$i]).'\''
1578
                        );
1579
                        return self::errorCode();
1580
                    }
1581
                    // Set the attribute
1582
                    $v_result_list[$p_options_list[$i]] = $v_function_name;
1583
                    $i++;
1584
                    break;
1585
                default :
1586
                    // Error log
1587
                    $this->privErrorLog(
1588
                        self::ERR_INVALID_PARAMETER,
1589
                        'Unknown parameter \''.$p_options_list[$i].'\''
1590
                    );
1591
                    return self::errorCode();
1592
            } // end of switch
1593
            // Next options
1594
            $i++;
1595
        } // end of while
1596
        // Look for mandatory options
1597
        if ($v_requested_options !== false) {
1598
            for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) {
1599
                // Look for mandatory option
1600
                if ($v_requested_options[$key] == 'mandatory') {
1601
                    // Look if present
1602
                    if (!isset($v_result_list[$key])) {
1603
                        // Error log
1604
                        $this->privErrorLog(
1605
                            self::ERR_INVALID_PARAMETER,
1606
                            'Missing mandatory parameter \''.self::UtilOptionText($key).'('.$key.')'
1607
                        );
1608
                        return self::errorCode();
1609
                    }
1610
                }
1611
            }
1612
        }
1613
        // Look for default values
1614
        if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { }
1615
        return $v_result;
1616
    }
1617

    
1618
  // --------------------------------------------------------------------------------
1619
  // Function : privOptionDefaultThreshold()
1620
  // Description :
1621
  // Parameters :
1622
  // Return Values :
1623
  // --------------------------------------------------------------------------------
1624
    protected function privOptionDefaultThreshold(&$p_options)
1625
    {
1626
        $v_result=1;
1627
        if (isset($p_options[self::OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[self::OPT_TEMP_FILE_OFF])) {
1628
            return $v_result;
1629
        }
1630
        // Get 'memory_limit' configuration value
1631
//        $v_memory_limit = trim(ini_get('memory_limit'));
1632
//        $last = strtolower(substr($v_memory_limit, -1));
1633
        preg_match('/^([0-9]+)([a-z])$/', strtolower(trim(ini_get('memory_limit'))), $aMatch);
1634
        $v_memory_limit = (int)$aMatch[1];
1635
        switch ($aMatch[2]) {
1636
            case 'g':
1637
                $v_memory_limit *= 1024;
1638
            case 'm':
1639
                $v_memory_limit *= 1024;
1640
            case 'k':
1641
                $v_memory_limit *= 1024;
1642
                break;
1643
            default:
1644
                break;
1645
        }
1646
        $p_options[self::OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit * self::TEMPORARY_FILE_RATIO);
1647
        // Sanity check : No threshold if value lower than 1M
1648
        if ($p_options[self::OPT_TEMP_FILE_THRESHOLD] < 1048576) {
1649
          unset($p_options[self::OPT_TEMP_FILE_THRESHOLD]);
1650
        }
1651
        return $v_result;
1652
    }
1653
  // --------------------------------------------------------------------------------
1654
  // Function : privFileDescrParseAtt()
1655
  // Description :
1656
  // Parameters :
1657
  // Return Values :
1658
  //   1 on success.
1659
  //   0 on failure.
1660
  // --------------------------------------------------------------------------------
1661
    protected function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false)
1662
    {
1663
        $v_result = 1;
1664
        // For each file in the list check the attributes
1665
        foreach ($p_file_list as $v_key => $v_value) {
1666
            // Check if the option is supported
1667
            if (!isset($v_requested_options[$v_key])) {
1668
                // Error log
1669
                $this->privErrorLog(self::ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
1670
                // Return
1671
                return self::errorCode();
1672
            }
1673
            // Look for attribute
1674
            switch ($v_key) {
1675
                case self::ATT_FILE_NAME :
1676
                    if (!is_string($v_value)) {
1677
                        $this->privErrorLog(
1678
                            self::ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type '.gettype($v_value).
1679
                            '. String expected for attribute \''.self::UtilOptionText($v_key).'\''
1680
                        );
1681
                        return self::errorCode();
1682
                    }
1683
                    $p_filedescr['filename'] = self::UtilPathReduction($v_value);
1684
                    if ($p_filedescr['filename'] == '') {
1685
                        $this->privErrorLog(
1686
                            self::ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid empty filename for attribute \''.
1687
                            self::UtilOptionText($v_key).'\''
1688
                        );
1689
                        return self::errorCode();
1690
                    }
1691
                    break;
1692
                case self::ATT_FILE_NEW_SHORT_NAME :
1693
                    if (!is_string($v_value)) {
1694
                        $this->privErrorLog(
1695
                            self::ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type '.gettype($v_value).
1696
                            '. String expected for attribute \''.self::UtilOptionText($v_key).'\''
1697
                        );
1698
                        return self::errorCode();
1699
                    }
1700
                    $p_filedescr['new_short_name'] = self::UtilPathReduction($v_value);
1701
                    if ($p_filedescr['new_short_name'] == '') {
1702
                        $this->privErrorLog(
1703
                            self::ERR_INVALID_ATTRIBUTE_VALUE,
1704
                            'Invalid empty short filename for attribute \''.self::UtilOptionText($v_key).'\''
1705
                        );
1706
                        return self::errorCode();
1707
                    }
1708
                    break;
1709
                case self::ATT_FILE_NEW_FULL_NAME :
1710
                    if (!is_string($v_value)) {
1711
                        $this->privErrorLog(
1712
                            self::ERR_INVALID_ATTRIBUTE_VALUE, 'Invalid type '.gettype($v_value).
1713
                            '. String expected for attribute \''.self::UtilOptionText($v_key).'\''
1714
                        );
1715
                        return self::errorCode();
1716
                    }
1717
                    $p_filedescr['new_full_name'] = self::UtilPathReduction($v_value);
1718
                    if ($p_filedescr['new_full_name'] == '') {
1719
                        $this->privErrorLog(
1720
                            self::ERR_INVALID_ATTRIBUTE_VALUE,
1721
                            'Invalid empty full filename for attribute \''.self::UtilOptionText($v_key).'\''
1722
                        );
1723
                        return self::errorCode();
1724
                    }
1725
                    break;
1726
                // Look for options that takes a string
1727
                case self::ATT_FILE_COMMENT :
1728
                    if (!is_string($v_value)) {
1729
                        $this->privErrorLog(
1730
                            self::ERR_INVALID_ATTRIBUTE_VALUE,
1731
                            'Invalid type '.gettype($v_value).'. String expected for attribute \''.self::UtilOptionText($v_key).'\''
1732
                        );
1733
                        return self::errorCode();
1734
                    }
1735
                    $p_filedescr['comment'] = $v_value;
1736
                    break;
1737
                case self::ATT_FILE_MTIME :
1738
                    if (!is_integer($v_value)) {
1739
                        $this->privErrorLog(
1740
                            self::ERR_INVALID_ATTRIBUTE_VALUE,
1741
                            'Invalid type '.gettype($v_value).'. Integer expected for attribute \''.self::UtilOptionText($v_key).'\''
1742
                        );
1743
                        return self::errorCode();
1744
                    }
1745
                    $p_filedescr['mtime'] = $v_value;
1746
                    break;
1747
                case self::ATT_FILE_CONTENT :
1748
                    $p_filedescr['content'] = $v_value;
1749
                    break;
1750
                default :
1751
                    // Error log
1752
                    $this->privErrorLog(self::ERR_INVALID_PARAMETER, 'Unknown parameter \''.$v_key.'\'');
1753
                    return self::errorCode();
1754
            }
1755
            // Look for mandatory options
1756
            if ($v_requested_options !== false) {
1757
                for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) {
1758
                    // Look for mandatory option
1759
                    if ($v_requested_options[$key] == 'mandatory') {
1760
                        // Look if present
1761
                        if (!isset($p_file_list[$key])) {
1762
                            $this->privErrorLog(
1763
                                self::ERR_INVALID_PARAMETER,
1764
                                'Missing mandatory parameter '.self::UtilOptionText($key).'('.$key.')'
1765
                            );
1766
                            return self::errorCode();
1767
                        }
1768
                    }
1769
                }
1770
            }
1771
        } // end foreach
1772
        return $v_result;
1773
    }
1774
  // --------------------------------------------------------------------------------
1775

    
1776
  // --------------------------------------------------------------------------------
1777
  // Function : privFileDescrExpand()
1778
  // Description :
1779
  //   This method look for each item of the list to see if its a file, a folder
1780
  //   or a string to be added as file. For any other type of files (link, other)
1781
  //   just ignore the item.
1782
  //   Then prepare the information that will be stored for that file.
1783
  //   When its a folder, expand the folder with all the files that are in that
1784
  //   folder (recursively).
1785
  // Parameters :
1786
  // Return Values :
1787
  //   1 on success.
1788
  //   0 on failure.
1789
  // --------------------------------------------------------------------------------
1790
    protected function privFileDescrExpand(&$p_filedescr_list, &$p_options)
1791
    {
1792
        $v_result=1;
1793
        // Create a result list
1794
        $v_result_list = array();
1795
        // Look each entry
1796
        for ($i=0; $i<sizeof($p_filedescr_list); $i++) {
1797
            // Get filedescr
1798
            $v_descr = $p_filedescr_list[$i];
1799
            // Reduce the filename
1800
            $v_descr['filename'] = self::UtilTranslateWinPath($v_descr['filename'], false);
1801
            $v_descr['filename'] = self::UtilPathReduction($v_descr['filename']);
1802
            // Look for real file or folder
1803
            if (file_exists($v_descr['filename'])) {
1804
                if (@is_file($v_descr['filename'])) {
1805
                    $v_descr['type'] = 'file';
1806
                } else if (@is_dir($v_descr['filename'])) {
1807
                    $v_descr['type'] = 'folder';
1808
                } else if (@is_link($v_descr['filename'])) {
1809
                    // skip
1810
                    continue;
1811
                } else {
1812
                    // skip
1813
                    continue;
1814
                }
1815
            } else if (isset($v_descr['content'])) {
1816
                // Look for string added as file
1817
                $v_descr['type'] = 'virtual_file';
1818
            } else {
1819
                // Missing file / Error log
1820
                $sFilename = '/'.basename(dirname($v_descr['filename'])).'/'.basename($v_descr['filename']);
1821
                $this->privErrorLog(self::ERR_MISSING_FILE, ' File \''.$sFilename.'\' does not exist');
1822
                return PclZip::errorCode();
1823
            }
1824
            // Calculate the stored filename
1825
            $this->privCalculateStoredFilename($v_descr, $p_options);
1826
            // Add the descriptor in result list
1827
            $v_result_list[sizeof($v_result_list)] = $v_descr;
1828
            // Look for folder
1829
            if ($v_descr['type'] == 'folder') {
1830
                // List of items in folder
1831
                $v_dirlist_descr = array();
1832
                $v_dirlist_nb = 0;
1833
                if (($v_folder_handler = @opendir($v_descr['filename']))) {
1834
                    while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
1835
                        // Skip '.' and '..'
1836
                        if (($v_item_handler == '.') || ($v_item_handler == '..')) {
1837
                            continue;
1838
                        }
1839
                        // Compose the full filename
1840
                        $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
1841
                        // Look for different stored filename
1842
                        // Because the name of the folder was changed, the name of the
1843
                        // files/sub-folders also change
1844
                        if (($v_descr['stored_filename'] != $v_descr['filename']) && (!isset($p_options[self::OPT_REMOVE_ALL_PATH]))) {
1845
                            if ($v_descr['stored_filename'] != '') {
1846
                                $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
1847
                            } else {
1848
                                $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
1849
                            }
1850
                        }
1851
                        $v_dirlist_nb++;
1852
                    }
1853
                    @closedir($v_folder_handler);
1854
                } else { /* TBC : unable to open folder in read mode */ }
1855
                // Expand each element of the list
1856
                if ($v_dirlist_nb != 0) {
1857
                    // Expand
1858
                    if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
1859
                        return $v_result;
1860
                    }
1861
                    // Concat the resulting list
1862
                    $v_result_list = array_merge($v_result_list, $v_dirlist_descr);
1863
                } else { }
1864
                // Free local array
1865
                unset($v_dirlist_descr);
1866
            }
1867
        }
1868
        // Get the result list
1869
        $p_filedescr_list = $v_result_list;
1870
        return $v_result;
1871
    }
1872
  // --------------------------------------------------------------------------------
1873

    
1874
  // --------------------------------------------------------------------------------
1875
  // Function : privCreate()
1876
  // Description :
1877
  // Parameters :
1878
  // Return Values :
1879
  // --------------------------------------------------------------------------------
1880
    protected function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
1881
    {
1882
        $v_result=1;
1883
        $v_list_detail = array();
1884
        // Magic quotes trick
1885
        $this->privDisableMagicQuotes();
1886
        // Open the file in write mode
1887
        if (($v_result = $this->privOpenFd('wb')) != 1) {
1888
          return $v_result;
1889
        }
1890
        // Add the list of files
1891
        $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
1892
        // Close
1893
        $this->privCloseFd();
1894
        // Magic quotes trick
1895
        $this->privSwapBackMagicQuotes();
1896
        return $v_result;
1897
    }
1898
  // --------------------------------------------------------------------------------
1899

    
1900
  // --------------------------------------------------------------------------------
1901
  // Function : privAdd()
1902
  // Description :
1903
  // Parameters :
1904
  // Return Values :
1905
  // --------------------------------------------------------------------------------
1906
    protected function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
1907
    {
1908
        $v_result = 1;
1909
        $v_list_detail = array();
1910
        // Look if the archive exists or is empty
1911
        if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) {
1912
            // Do a create
1913
            $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
1914
            return $v_result;
1915
        }
1916
        // Magic quotes trick
1917
        $this->privDisableMagicQuotes();
1918
        // Open the zip file
1919
        if (($v_result=$this->privOpenFd('rb')) != 1) {
1920
            // Magic quotes trick
1921
            $this->privSwapBackMagicQuotes();
1922
            return $v_result;
1923
        }
1924
        // Read the central directory informations
1925
        $v_central_dir = array();
1926
        if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
1927
            $this->privCloseFd();
1928
            $this->privSwapBackMagicQuotes();
1929
            return $v_result;
1930
        }
1931
        // Go to beginning of File
1932
        @rewind($this->zip_fd);
1933
        // Creates a temporay file
1934
        $v_zip_temp_name = self::TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
1935
        // Open the temporary file in write mode
1936
        if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
1937
            $this->privCloseFd();
1938
            $this->privSwapBackMagicQuotes();
1939
            $this->privErrorLog(
1940
                self::ERR_READ_OPEN_FAIL,
1941
                'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'
1942
            );
1943
            return self::errorCode();
1944
        }
1945
        // Copy the files from the archive to the temporary file
1946
        // TBC : Here I should better append the file and go back to erase the central dir
1947
        $v_size = $v_central_dir['offset'];
1948
        while ($v_size != 0) {
1949
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
1950
            $v_buffer = fread($this->zip_fd, $v_read_size);
1951
            @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
1952
            $v_size -= $v_read_size;
1953
        }
1954
        // Swap the file descriptor
1955
        // Here is a trick : I swap the temporary fd with the zip fd, in order to use
1956
        // the following methods on the temporary fil and not the real archive
1957
        $v_swap = $this->zip_fd;
1958
        $this->zip_fd = $v_zip_temp_fd;
1959
        $v_zip_temp_fd = $v_swap;
1960
        // Add the files
1961
        $v_header_list = array();
1962
        if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
1963
            fclose($v_zip_temp_fd);
1964
            $this->privCloseFd();
1965
            @unlink($v_zip_temp_name);
1966
            $this->privSwapBackMagicQuotes();
1967
            return $v_result;
1968
        }
1969
        // Store the offset of the central dir
1970
        $v_offset = @ftell($this->zip_fd);
1971
        // Copy the block of file headers from the old archive
1972
        $v_size = $v_central_dir['size'];
1973
        while ($v_size != 0) {
1974
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
1975
            $v_buffer = @fread($v_zip_temp_fd, $v_read_size);
1976
            @fwrite($this->zip_fd, $v_buffer, $v_read_size);
1977
            $v_size -= $v_read_size;
1978
        }
1979
        // Create the Central Dir files header
1980
        for ($i = 0, $v_count = 0; $i < sizeof($v_header_list); $i++) {
1981
            // Create the file header
1982
            if ($v_header_list[$i]['status'] == 'ok') {
1983
                if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
1984
                    fclose($v_zip_temp_fd);
1985
                    $this->privCloseFd();
1986
                    @unlink($v_zip_temp_name);
1987
                    $this->privSwapBackMagicQuotes();
1988
                    return $v_result;
1989
                }
1990
                $v_count++;
1991
            }
1992
            // Transform the header to a 'usable' info
1993
            $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
1994
        }
1995
        // Zip file comment
1996
        $v_comment = $v_central_dir['comment'];
1997
        if (isset($p_options[self::OPT_COMMENT])) {
1998
            $v_comment = $p_options[self::OPT_COMMENT];
1999
        }
2000
        if (isset($p_options[self::OPT_ADD_COMMENT])) {
2001
            $v_comment = $v_comment.$p_options[self::OPT_ADD_COMMENT];
2002
        }
2003
        if (isset($p_options[self::OPT_PREPEND_COMMENT])) {
2004
            $v_comment = $p_options[self::OPT_PREPEND_COMMENT].$v_comment;
2005
        }
2006
        // Calculate the size of the central header
2007
        $v_size = @ftell($this->zip_fd)-$v_offset;
2008
        // Create the central dir footer
2009
        if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) {
2010
            // Reset the file list
2011
            unset($v_header_list);
2012
            $this->privSwapBackMagicQuotes();
2013
            return $v_result;
2014
        }
2015
        // Swap back the file descriptor
2016
        $v_swap = $this->zip_fd;
2017
        $this->zip_fd = $v_zip_temp_fd;
2018
        $v_zip_temp_fd = $v_swap;
2019
        // Close
2020
        $this->privCloseFd();
2021
        // Close the temporary file
2022
        @fclose($v_zip_temp_fd);
2023
        // Magic quotes trick
2024
        $this->privSwapBackMagicQuotes();
2025
        // Delete the zip file
2026
        // TBC : I should test the result ...
2027
        @unlink($this->zipname);
2028
        // Rename the temporary file
2029
        // TBC : I should test the result ...
2030
        // @rename($v_zip_temp_name, $this->zipname);
2031
        self::UtilRename($v_zip_temp_name, $this->zipname);
2032
        return $v_result;
2033
    }
2034
  // --------------------------------------------------------------------------------
2035

    
2036
  // --------------------------------------------------------------------------------
2037
  // Function : privOpenFd()
2038
  // Description :
2039
  // Parameters :
2040
  // --------------------------------------------------------------------------------
2041
    protected function privOpenFd($p_mode)
2042
    {
2043
        $v_result = 1;
2044
        // Look if already open
2045
        if ($this->zip_fd != 0) {
2046
          // Error log
2047
            $this->privErrorLog(self::ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
2048
            return self::errorCode();
2049
        }
2050
        // Open the zip file
2051
        if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) {
2052
            // Error log
2053
            $this->privErrorLog(self::ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
2054
            return self::errorCode();
2055
        }
2056
        return $v_result;
2057
    }
2058
  // --------------------------------------------------------------------------------
2059

    
2060
  // --------------------------------------------------------------------------------
2061
  // Function : privCloseFd()
2062
  // Description :
2063
  // Parameters :
2064
  // --------------------------------------------------------------------------------
2065
    protected function privCloseFd()
2066
    {
2067
        $v_result=1;
2068
        if ($this->zip_fd != 0) {
2069
            @fclose($this->zip_fd);
2070
        }
2071
        $this->zip_fd = 0;
2072
        return $v_result;
2073
    }
2074
  // --------------------------------------------------------------------------------
2075

    
2076
  // --------------------------------------------------------------------------------
2077
  // Function : privAddList()
2078
  // Description :
2079
  //   $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
2080
  //   different from the real path of the file. This is usefull if you want to have PclTar
2081
  //   running in any directory, and memorize relative path from an other directory.
2082
  // Parameters :
2083
  //   $p_list : An array containing the file or directory names to add in the tar
2084
  //   $p_result_list : list of added files with their properties (specially the status field)
2085
  //   $p_add_dir : Path to add in the filename path archived
2086
  //   $p_remove_dir : Path to remove in the filename path archived
2087
  // Return Values :
2088
  // --------------------------------------------------------------------------------
2089
//  public function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
2090
    protected function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
2091
    {
2092
        $v_result = 1;
2093
        // Add the files
2094
        $v_header_list = array();
2095
        if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
2096
            return $v_result;
2097
        }
2098
        // Store the offset of the central dir
2099
        $v_offset = @ftell($this->zip_fd);
2100
        // Create the Central Dir files header
2101
        for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++) {
2102
            // Create the file header
2103
            if ($v_header_list[$i]['status'] == 'ok') {
2104
                if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
2105
                    return $v_result;
2106
                }
2107
                $v_count++;
2108
            }
2109
            // Transform the header to a 'usable' info
2110
            $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
2111
        }
2112
        // Zip file comment
2113
        $v_comment = '';
2114
        if (isset($p_options[self::OPT_COMMENT])) {
2115
            $v_comment = $p_options[self::OPT_COMMENT];
2116
        }
2117
        // Calculate the size of the central header
2118
        $v_size = @ftell($this->zip_fd)-$v_offset;
2119
        // Create the central dir footer
2120
        if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) {
2121
            // Reset the file list
2122
            unset($v_header_list);
2123
            return $v_result;
2124
        }
2125
        return $v_result;
2126
    }
2127
  // --------------------------------------------------------------------------------
2128

    
2129
  // --------------------------------------------------------------------------------
2130
  // Function : privAddFileList()
2131
  // Description :
2132
  // Parameters :
2133
  //   $p_filedescr_list : An array containing the file description
2134
  //                      or directory names to add in the zip
2135
  //   $p_result_list : list of added files with their properties (specially the status field)
2136
  // Return Values :
2137
  // --------------------------------------------------------------------------------
2138
    protected function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
2139
    {
2140
        $v_result = 1;
2141
        $v_header = array();
2142
        // Recuperate the current number of elt in list
2143
        $v_nb = sizeof($p_result_list);
2144
        // Loop on the files
2145
        for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) {
2146
            // Format the filename
2147
            $p_filedescr_list[$j]['filename'] = self::UtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
2148
            // Skip empty file names
2149
            // TBC : Can this be possible ? not checked in DescrParseAtt ?
2150
            if ($p_filedescr_list[$j]['filename'] == "") {
2151
                continue;
2152
            }
2153
            // Check the filename
2154
            if (
2155
                ($p_filedescr_list[$j]['type'] != 'virtual_file') &&
2156
                (!file_exists($p_filedescr_list[$j]['filename'])))
2157
            {
2158
                $this->privErrorLog(self::ERR_MISSING_FILE, ' File \''.$p_filedescr_list[$j]['filename'].'\' does not exist');
2159
                return self::errorCode();
2160
            }
2161
            // Look if it is a file or a dir with no all path remove option
2162
            // or a dir with all its path removed
2163
            //      if (   (is_file($p_filedescr_list[$j]['filename']))
2164
            //          || (   is_dir($p_filedescr_list[$j]['filename'])
2165
            if (
2166
                ($p_filedescr_list[$j]['type'] == 'file') ||
2167
                ($p_filedescr_list[$j]['type'] == 'virtual_file') ||
2168
                (
2169
                    ($p_filedescr_list[$j]['type'] == 'folder') &&
2170
                    (!isset($p_options[self::OPT_REMOVE_ALL_PATH]) ||
2171
                    !$p_options[self::OPT_REMOVE_ALL_PATH])
2172
                )
2173
            ) {
2174
                // Add the file
2175
                $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options);
2176
                if ($v_result != 1) {
2177
                    return $v_result;
2178
                }
2179
                // Store the file infos
2180
                $p_result_list[$v_nb++] = $v_header;
2181
            }
2182
        }
2183
        return $v_result;
2184
    }
2185
  // --------------------------------------------------------------------------------
2186

    
2187
  // --------------------------------------------------------------------------------
2188
  // Function : privAddFile()
2189
  // Description :
2190
  // Parameters :
2191
  // Return Values :
2192
  // --------------------------------------------------------------------------------
2193
    protected function privAddFile($p_filedescr, &$p_header, &$p_options)
2194
    {
2195
        $v_result=1;
2196
        // Working variable
2197
        $p_filename = $p_filedescr['filename'];
2198
        // TBC : Already done in the fileAtt check ... ?
2199
        if ($p_filename == "") {
2200
            // Error log
2201
            $this->privErrorLog(self::ERR_INVALID_PARAMETER, 'Invalid file list parameter (invalid or empty list)');
2202
            return self::errorCode();
2203
        }
2204
        // Look for a stored different filename
2205
        /* TBC : Removed
2206
        if (isset($p_filedescr['stored_filename'])) {
2207
          $v_stored_filename = $p_filedescr['stored_filename'];
2208
        }
2209
        else {
2210
          $v_stored_filename = $p_filedescr['stored_filename'];
2211
        }
2212
        */
2213
        // Set the file properties
2214
        clearstatcache();
2215
        $p_header['version']           = 20;
2216
        $p_header['version_extracted'] = 10;
2217
        $p_header['flag']              = 0;
2218
        $p_header['compression']       = 0;
2219
        $p_header['crc']               = 0;
2220
        $p_header['compressed_size']   = 0;
2221
        $p_header['filename_len']      = strlen($p_filename);
2222
        $p_header['extra_len']         = 0;
2223
        $p_header['disk']              = 0;
2224
        $p_header['internal']          = 0;
2225
        $p_header['offset']            = 0;
2226
        $p_header['filename']          = $p_filename;
2227
        // TBC : Removed    $p_header['stored_filename'] = $v_stored_filename;
2228
        $p_header['stored_filename']   = $p_filedescr['stored_filename'];
2229
        $p_header['extra']             = '';
2230
        $p_header['status']            = 'ok';
2231
        $p_header['index']             = -1;
2232
        // Look for regular file
2233
        if ($p_filedescr['type']=='file') {
2234
            $p_header['external']  = 0x00000000;
2235
            $p_header['size']      = filesize($p_filename);
2236
        } else if ($p_filedescr['type']=='folder') {
2237
        // Look for regular folder
2238
            $p_header['external']  = 0x00000010;
2239
            $p_header['mtime']     = filemtime($p_filename);
2240
            $p_header['size']      = filesize($p_filename);
2241
        } else if ($p_filedescr['type'] == 'virtual_file') {
2242
        // Look for virtual file
2243
            $p_header['external']  = 0x00000000;
2244
            $p_header['size']      = strlen($p_filedescr['content']);
2245
        }
2246
        // Look for filetime
2247
        if (isset($p_filedescr['mtime'])) {
2248
            $p_header['mtime']     = $p_filedescr['mtime'];
2249
        } else if ($p_filedescr['type'] == 'virtual_file') {
2250
            $p_header['mtime']     = time();
2251
        } else {
2252
            $p_header['mtime']     = filemtime($p_filename);
2253
        }
2254
        // Look for file comment
2255
        if (isset($p_filedescr['comment'])) {
2256
            $p_header['comment_len'] = strlen($p_filedescr['comment']);
2257
            $p_header['comment']     = $p_filedescr['comment'];
2258
        } else {
2259
            $p_header['comment_len'] = 0;
2260
            $p_header['comment']     = '';
2261
        }
2262
        // Look for pre-add callback
2263
        if (isset($p_options[self::CB_PRE_ADD])) {
2264
            // Generate a local information
2265
            $v_local_header = array();
2266
            $this->privConvertHeader2FileInfo($p_header, $v_local_header);
2267
            // Call the callback
2268
            // Here I do not use call_user_func() because I need to send a reference to the
2269
            // header.
2270
//            eval('$v_result = '.$p_options[self::CB_PRE_ADD].'(self::CB_PRE_ADD, $v_local_header);');
2271
            $v_result = $p_options[self::CB_PRE_ADD](self::CB_PRE_ADD, $v_local_header);
2272
            if ($v_result == 0) {
2273
                // Change the file status
2274
                $p_header['status'] = "skipped";
2275
                $v_result = 1;
2276
            }
2277
            // Update the informations
2278
            // Only some fields can be modified
2279
            if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
2280
                $p_header['stored_filename'] = self::UtilPathReduction($v_local_header['stored_filename']);
2281
            }
2282
        }
2283
        // Look for empty stored filename
2284
        if ($p_header['stored_filename'] == "") {
2285
            $p_header['status'] = "filtered";
2286
        }
2287
        // Check the path length
2288
        if (strlen($p_header['stored_filename']) > 0xFF) {
2289
            $p_header['status'] = 'filename_too_long';
2290
        }
2291
        // Look if no error, or file not skipped
2292
        if ($p_header['status'] == 'ok') {
2293
            // Look for a file
2294
            if ($p_filedescr['type'] == 'file') {
2295
                // Look for using temporary file to zip
2296
                if (
2297
                    (!isset($p_options[self::OPT_TEMP_FILE_OFF])) &&
2298
                    (isset($p_options[self::OPT_TEMP_FILE_ON]) ||
2299
                        (isset($p_options[self::OPT_TEMP_FILE_THRESHOLD]) &&
2300
                            ($p_options[self::OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])
2301
                        )
2302
                    )
2303
                ) {
2304
                    $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
2305
                    if ($v_result < self::ERR_NO_ERROR) {
2306
                        return $v_result;
2307
                    }
2308
                } else {
2309
                    // Use "in memory" zip algo
2310
                    // Open the source file
2311
                    if (($v_file = @fopen($p_filename, "rb")) == 0) {
2312
                        $this->privErrorLog(
2313
                            self::ERR_READ_OPEN_FAIL,
2314
                            'Unable to open file \''.$p_filename.'\' in binary read mode'
2315
                        );
2316
                        return self::errorCode();
2317
                    }
2318
                    // Read the file content
2319
                    $v_content = @fread($v_file, $p_header['size']);
2320
                    // Close the file
2321
                    @fclose($v_file);
2322
                    // Calculate the CRC
2323
                    $p_header['crc'] = @crc32($v_content);
2324
                    // Look for no compression
2325
                    if ($p_options[self::OPT_NO_COMPRESSION]) {
2326
                        // Set header parameters
2327
                        $p_header['compressed_size'] = $p_header['size'];
2328
                        $p_header['compression'] = 0;
2329
                    } else {
2330
                        // Look for normal compression
2331
                        // Compress the content
2332
                        $v_content = @gzdeflate($v_content);
2333
                        // Set header parameters
2334
                        $p_header['compressed_size'] = strlen($v_content);
2335
                        $p_header['compression'] = 8;
2336
                    }
2337
                    // Call the header generation
2338
                    if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2339
                        @fclose($v_file);
2340
                        return $v_result;
2341
                    }
2342
                    // Write the compressed (or not) content
2343
                    @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
2344
                }
2345
            } else if ($p_filedescr['type'] == 'virtual_file') {
2346
                // Look for a virtual file (a file from string)
2347
                $v_content = $p_filedescr['content'];
2348
                // Calculate the CRC
2349
                $p_header['crc'] = @crc32($v_content);
2350
                // Look for no compression
2351
                if ($p_options[self::OPT_NO_COMPRESSION]) {
2352
                    // Set header parameters
2353
                    $p_header['compressed_size'] = $p_header['size'];
2354
                    $p_header['compression'] = 0;
2355
                } else {
2356
                    // Look for normal compression
2357
                    // Compress the content
2358
                    $v_content = @gzdeflate($v_content);
2359
                    // Set header parameters
2360
                    $p_header['compressed_size'] = strlen($v_content);
2361
                    $p_header['compression'] = 8;
2362
                }
2363
                // Call the header generation
2364
                if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2365
                    @fclose($v_file);
2366
                    return $v_result;
2367
                }
2368
                // Write the compressed (or not) content
2369
                @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
2370
            } else if ($p_filedescr['type'] == 'folder') {
2371
                // Look for a directory
2372
                // Look for directory last '/'
2373
                if (@substr($p_header['stored_filename'], -1) != '/') {
2374
                    $p_header['stored_filename'] .= '/';
2375
                }
2376
                // Set the file properties
2377
                $p_header['size'] = 0;
2378
//                $p_header['external'] = 0x41FF0010;   // Value for a folder : to be checked
2379
                $p_header['external'] = 0x00000010;   // Value for a folder : to be checked
2380
                // Call the header generation
2381
                if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2382
                    return $v_result;
2383
                }
2384
            }
2385
        }
2386
        // Look for post-add callback
2387
        if (isset($p_options[self::CB_POST_ADD])) {
2388
            // Generate a local information
2389
            $v_local_header = array();
2390
            $this->privConvertHeader2FileInfo($p_header, $v_local_header);
2391
            // Call the callback
2392
            // Here I do not use call_user_func() because I need to send a reference to the
2393
            // header.
2394
//            eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);');
2395
            $v_result = $p_options[self::CB_POST_ADD](self::CB_POST_ADD, $v_local_header);
2396
            if ($v_result == 0) {
2397
                // Ignored
2398
                $v_result = 1;
2399
            }
2400
            // Update the informations
2401
            // Nothing can be modified
2402
        }
2403
        return $v_result;
2404
    }
2405
  // --------------------------------------------------------------------------------
2406

    
2407
  // --------------------------------------------------------------------------------
2408
  // Function : privAddFileUsingTempFile()
2409
  // Description :
2410
  // Parameters :
2411
  // Return Values :
2412
  // --------------------------------------------------------------------------------
2413
    protected function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
2414
    {
2415
        $v_result = self::ERR_NO_ERROR;
2416
        // Working variable
2417
        $p_filename = $p_filedescr['filename'];
2418
        // Open the source file
2419
        if (($v_file = @fopen($p_filename, "rb")) == 0) {
2420
            $this->privErrorLog(
2421
                self::ERR_READ_OPEN_FAIL,
2422
                'Unable to open file \''.$p_filename.'\' in binary read mode'
2423
            );
2424
            return self::errorCode();
2425
        }
2426
        // Creates a compressed temporary file
2427
        $v_gzip_temp_name = self::TEMPORARY_DIR.uniqid('pclzip-').'.gz';
2428
        if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
2429
            fclose($v_file);
2430
            $this->privErrorLog(
2431
                self::ERR_WRITE_OPEN_FAIL,
2432
                'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'
2433
            );
2434
            return self::errorCode();
2435
        }
2436
        // Read the file by self::READ_BLOCK_SIZE octets blocks
2437
        $v_size = filesize($p_filename);
2438
        while ($v_size != 0) {
2439
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
2440
            $v_buffer = @fread($v_file, $v_read_size);
2441
//            $v_binary_data = pack('a'.$v_read_size, $v_buffer);
2442
            @gzputs($v_file_compressed, $v_buffer, $v_read_size);
2443
            $v_size -= $v_read_size;
2444
        }
2445
        // Close the file
2446
        @fclose($v_file);
2447
        @gzclose($v_file_compressed);
2448
        // Check the minimum file size
2449
        if (filesize($v_gzip_temp_name) < 18) {
2450
            $this->privErrorLog(
2451
                self::ERR_BAD_FORMAT,
2452
                'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'
2453
            );
2454
            return self::errorCode();
2455
        }
2456
        // Extract the compressed attributes
2457
        if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
2458
            $this->privErrorLog(
2459
                self::ERR_READ_OPEN_FAIL,
2460
                'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'
2461
            );
2462
            return self::errorCode();
2463
        }
2464
        // Read the gzip file header
2465
        $v_binary_data = @fread($v_file_compressed, 10);
2466
        $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
2467
        // Check some parameters
2468
        $v_data_header['os'] = bin2hex($v_data_header['os']);
2469
        // Read the gzip file footer
2470
        @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8);
2471
        $v_binary_data = @fread($v_file_compressed, 8);
2472
        $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
2473
        // Set the attributes
2474
        $p_header['compression'] = ord($v_data_header['cm']);
2475
        //$p_header['mtime'] = $v_data_header['mtime'];
2476
        $p_header['crc'] = $v_data_footer['crc'];
2477
        $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18;
2478
        // Close the file
2479
        @fclose($v_file_compressed);
2480
        // Call the header generation
2481
        if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
2482
            return $v_result;
2483
        }
2484
        // Add the compressed data
2485
        if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
2486
            $this->privErrorLog(
2487
                self::ERR_READ_OPEN_FAIL,
2488
                'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'
2489
            );
2490
            return self::errorCode();
2491
        }
2492
        // Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
2493
        fseek($v_file_compressed, 10);
2494
        $v_size = $p_header['compressed_size'];
2495
        while ($v_size != 0) {
2496
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
2497
            $v_buffer = @fread($v_file_compressed, $v_read_size);
2498
            //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
2499
            @fwrite($this->zip_fd, $v_buffer, $v_read_size);
2500
            $v_size -= $v_read_size;
2501
        }
2502
        // Close the file
2503
        @fclose($v_file_compressed);
2504
        // Unlink the temporary file
2505
        @unlink($v_gzip_temp_name);
2506
        return $v_result;
2507
    }
2508
  // --------------------------------------------------------------------------------
2509

    
2510
  // --------------------------------------------------------------------------------
2511
  // Function : privCalculateStoredFilename()
2512
  // Description :
2513
  //   Based on file descriptor properties and global options, this method
2514
  //   calculate the filename that will be stored in the archive.
2515
  // Parameters :
2516
  // Return Values :
2517
  // --------------------------------------------------------------------------------
2518
    protected function privCalculateStoredFilename(&$p_filedescr, &$p_options)
2519
    {
2520
        $v_result = 1;
2521
        // Working variables
2522
        $p_filename = $p_filedescr['filename'];
2523
        if (isset($p_options[self::OPT_ADD_PATH])) {
2524
            $p_add_dir = $p_options[self::OPT_ADD_PATH];
2525
        } else {
2526
          $p_add_dir = '';
2527
        }
2528
        if (isset($p_options[self::OPT_REMOVE_PATH])) {
2529
            $p_remove_dir = $p_options[self::OPT_REMOVE_PATH];
2530
        } else {
2531
            $p_remove_dir = '';
2532
        }
2533
        if (isset($p_options[self::OPT_REMOVE_ALL_PATH])) {
2534
            $p_remove_all_dir = $p_options[self::OPT_REMOVE_ALL_PATH];
2535
        } else {
2536
            $p_remove_all_dir = 0;
2537
        }
2538
        // Look for full name change
2539
        if (isset($p_filedescr['new_full_name'])) {
2540
            // Remove drive letter if any
2541
            $v_stored_filename = self::UtilTranslateWinPath($p_filedescr['new_full_name']);
2542
        } else {
2543
            // Look for path and/or short name change
2544
            // Its when we cahnge just the filename but not the path
2545
            if (isset($p_filedescr['new_short_name'])) {
2546
                $v_path_info = pathinfo($p_filename);
2547
                $v_dir = '';
2548
                if ($v_path_info['dirname'] != '') {
2549
                    $v_dir = $v_path_info['dirname'].'/';
2550
                }
2551
                $v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
2552
            } else {
2553
                // Calculate the stored filename
2554
                $v_stored_filename = $p_filename;
2555
            }
2556
            // Look for all path to remove
2557
            if ($p_remove_all_dir) {
2558
                $v_stored_filename = basename($p_filename);
2559
            } else if ($p_remove_dir != "") {
2560
            // Look for partial path remove
2561
                if (substr($p_remove_dir, -1) != '/') {
2562
                    $p_remove_dir .= "/";
2563
                }
2564
                if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) {
2565
                    if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) {
2566
                        $p_remove_dir = "./".$p_remove_dir;
2567
                    }
2568
                    if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) {
2569
                        $p_remove_dir = substr($p_remove_dir, 2);
2570
                    }
2571
                }
2572
                $v_compare = self::UtilPathInclusion($p_remove_dir, $v_stored_filename);
2573
                if ($v_compare > 0) {
2574
                    if ($v_compare == 2) {
2575
                      $v_stored_filename = "";
2576
                    } else {
2577
                        $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir));
2578
                    }
2579
                }
2580
            }
2581
            // Remove drive letter if any
2582
            $v_stored_filename = self::UtilTranslateWinPath($v_stored_filename);
2583
            // Look for path to add
2584
            if ($p_add_dir != "") {
2585
                if (substr($p_add_dir, -1) == "/") {
2586
                  $v_stored_filename = $p_add_dir.$v_stored_filename;
2587
                } else {
2588
                  $v_stored_filename = $p_add_dir."/".$v_stored_filename;
2589
                }
2590
            }
2591
        }
2592
        // Filename (reduce the path of stored name)
2593
        $v_stored_filename = self::UtilPathReduction($v_stored_filename);
2594
        $p_filedescr['stored_filename'] = $v_stored_filename;
2595
        return $v_result;
2596
    }
2597
  // --------------------------------------------------------------------------------
2598

    
2599
  // --------------------------------------------------------------------------------
2600
  // Function : privWriteFileHeader()
2601
  // Description :
2602
  // Parameters :
2603
  // Return Values :
2604
  // --------------------------------------------------------------------------------
2605
    protected function privWriteFileHeader(&$p_header)
2606
    {
2607
        $v_result = 1;
2608
        // Store the offset position of the file
2609
        $p_header['offset'] = ftell($this->zip_fd);
2610
        // Transform UNIX mtime to DOS format mdate/mtime
2611
        $v_date = getdate($p_header['mtime']);
2612
        $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
2613
        $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
2614
        // Packed data
2615
        $v_binary_data = pack(
2616
            'VvvvvvVVVvv',
2617
            0x04034b50,
2618
            $p_header['version_extracted'],
2619
            $p_header['flag'],
2620
            $p_header['compression'],
2621
            $v_mtime,
2622
            $v_mdate,
2623
            $p_header['crc'],
2624
            $p_header['compressed_size'],
2625
            $p_header['size'],
2626
            strlen($p_header['stored_filename']),
2627
            $p_header['extra_len']
2628
        );
2629
        // Write the first 148 bytes of the header in the archive
2630
        fputs($this->zip_fd, $v_binary_data, 30);
2631
        // Write the variable fields
2632
        if (strlen($p_header['stored_filename']) != 0) {
2633
            fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
2634
        }
2635
        if ($p_header['extra_len'] != 0) {
2636
            fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
2637
        }
2638
        return $v_result;
2639
    }
2640
  // --------------------------------------------------------------------------------
2641

    
2642
  // --------------------------------------------------------------------------------
2643
  // Function : privWriteCentralFileHeader()
2644
  // Description :
2645
  // Parameters :
2646
  // Return Values :
2647
  // --------------------------------------------------------------------------------
2648
    protected function privWriteCentralFileHeader(&$p_header)
2649
    {
2650
        $v_result = 1;
2651
        // TBC
2652
        //for(reset($p_header); $key = key($p_header); next($p_header)) { }
2653
        // Transform UNIX mtime to DOS format mdate/mtime
2654
        $v_date = getdate($p_header['mtime']);
2655
        $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
2656
        $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
2657
        // Packed data
2658
        $v_binary_data = pack(
2659
            'VvvvvvvVVVvvvvvVV',
2660
            0x02014b50,
2661
            $p_header['version'],
2662
            $p_header['version_extracted'],
2663
            $p_header['flag'],
2664
            $p_header['compression'],
2665
            $v_mtime,
2666
            $v_mdate,
2667
            $p_header['crc'],
2668
            $p_header['compressed_size'],
2669
            $p_header['size'],
2670
            strlen($p_header['stored_filename']),
2671
            $p_header['extra_len'],
2672
            $p_header['comment_len'],
2673
            $p_header['disk'],
2674
            $p_header['internal'],
2675
            $p_header['external'],
2676
            $p_header['offset']
2677
        );
2678
        // Write the 42 bytes of the header in the zip file
2679
        fputs($this->zip_fd, $v_binary_data, 46);
2680
        // Write the variable fields
2681
        if (strlen($p_header['stored_filename']) != 0) {
2682
            fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
2683
        }
2684
        if ($p_header['extra_len'] != 0) {
2685
            fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
2686
        }
2687
        if ($p_header['comment_len'] != 0) {
2688
            fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
2689
        }
2690
        return $v_result;
2691
    }
2692
  // --------------------------------------------------------------------------------
2693

    
2694
  // --------------------------------------------------------------------------------
2695
  // Function : privWriteCentralHeader()
2696
  // Description :
2697
  // Parameters :
2698
  // Return Values :
2699
  // --------------------------------------------------------------------------------
2700
    protected function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
2701
    {
2702
        $v_result=1;
2703
        // Packed data
2704
        $v_binary_data = pack(
2705
            'VvvvvVVv',
2706
            0x06054b50,
2707
            0,
2708
            0,
2709
            $p_nb_entries,
2710
            $p_nb_entries,
2711
            $p_size,
2712
            $p_offset,
2713
            strlen($p_comment)
2714
        );
2715
        // Write the 22 bytes of the header in the zip file
2716
        fputs($this->zip_fd, $v_binary_data, 22);
2717
        // Write the variable fields
2718
        if (strlen($p_comment) != 0) {
2719
            fputs($this->zip_fd, $p_comment, strlen($p_comment));
2720
        }
2721
        return $v_result;
2722
    }
2723
  // --------------------------------------------------------------------------------
2724

    
2725
  // --------------------------------------------------------------------------------
2726
  // Function : privList()
2727
  // Description :
2728
  // Parameters :
2729
  // Return Values :
2730
  // --------------------------------------------------------------------------------
2731
    protected function privList(&$p_list)
2732
    {
2733
        $v_result = 1;
2734
        // Magic quotes trick
2735
        $this->privDisableMagicQuotes();
2736
        // Open the zip file
2737
        if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) {
2738
            // Magic quotes trick
2739
            $this->privSwapBackMagicQuotes();
2740
            // Error log
2741
            $this->privErrorLog(
2742
                self::ERR_READ_OPEN_FAIL,
2743
                'Unable to open archive \''.$this->zipname.'\' in binary read mode'
2744
            );
2745
            // Return
2746
            return self::errorCode();
2747
        }
2748
        // Read the central directory informations
2749
        $v_central_dir = array();
2750
        if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
2751
            $this->privSwapBackMagicQuotes();
2752
            return $v_result;
2753
        }
2754
        // Go to beginning of Central Dir
2755
        @rewind($this->zip_fd);
2756
        if (@fseek($this->zip_fd, $v_central_dir['offset'])) {
2757
            $this->privSwapBackMagicQuotes();
2758
            // Error log
2759
            $this->privErrorLog(
2760
                self::ERR_INVALID_ARCHIVE_ZIP,
2761
                'Invalid archive size'
2762
            );
2763
            return self::errorCode();
2764
        }
2765
        // Read each entry
2766
        for ($i=0; $i<$v_central_dir['entries']; $i++) {
2767
            // Read the file header
2768
            if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) {
2769
                $this->privSwapBackMagicQuotes();
2770
                return $v_result;
2771
            }
2772
            $v_header['index'] = $i;
2773
            // Get the only interesting attributes
2774
            $this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
2775
            unset($v_header);
2776
        }
2777
        // Close the zip file
2778
        $this->privCloseFd();
2779
        // Magic quotes trick
2780
        $this->privSwapBackMagicQuotes();
2781
        return $v_result;
2782
    }
2783
  // --------------------------------------------------------------------------------
2784

    
2785
  // --------------------------------------------------------------------------------
2786
  // Function : privConvertHeader2FileInfo()
2787
  // Description :
2788
  //   This function takes the file informations from the central directory
2789
  //   entries and extract the interesting parameters that will be given back.
2790
  //   The resulting file infos are set in the array $p_info
2791
  //     $p_info['filename'] : Filename with full path. Given by user (add),
2792
  //                           extracted in the filesystem (extract).
2793
  //     $p_info['stored_filename'] : Stored filename in the archive.
2794
  //     $p_info['size'] = Size of the file.
2795
  //     $p_info['compressed_size'] = Compressed size of the file.
2796
  //     $p_info['mtime'] = Last modification date of the file.
2797
  //     $p_info['comment'] = Comment associated with the file.
2798
  //     $p_info['folder'] = true/false : indicates if the entry is a folder or not.
2799
  //     $p_info['status'] = status of the action on the file.
2800
  //     $p_info['crc'] = CRC of the file content.
2801
  // Parameters :
2802
  // Return Values :
2803
  // --------------------------------------------------------------------------------
2804
    protected function privConvertHeader2FileInfo($p_header, &$p_info)
2805
    {
2806
        $v_result = 1;
2807
        // Get the interesting attributes
2808
        $v_temp_path               = self::UtilPathReduction($p_header['filename']);
2809
        $p_info['filename']        = $v_temp_path;
2810
        $v_temp_path               = self::UtilPathReduction($p_header['stored_filename']);
2811
        $p_info['stored_filename'] = $v_temp_path;
2812
        $p_info['size']            = $p_header['size'];
2813
        $p_info['compressed_size'] = $p_header['compressed_size'];
2814
        $p_info['mtime']           = $p_header['mtime'];
2815
        $p_info['comment']         = $p_header['comment'];
2816
        $p_info['folder']          = (($p_header['external']&0x00000010)==0x00000010);
2817
        $p_info['index']           = $p_header['index'];
2818
        $p_info['status']          = $p_header['status'];
2819
        $p_info['crc']             = $p_header['crc'];
2820
        // Return
2821
        return $v_result;
2822
    }
2823
  // --------------------------------------------------------------------------------
2824

    
2825
  // --------------------------------------------------------------------------------
2826
  // Function : privExtractByRule()
2827
  // Description :
2828
  //   Extract a file or directory depending of rules (by index, by name, ...)
2829
  // Parameters :
2830
  //   $p_file_list : An array where will be placed the properties of each
2831
  //                  extracted file
2832
  //   $p_path : Path to add while writing the extracted files
2833
  //   $p_remove_path : Path to remove (from the file memorized path) while writing the
2834
  //                    extracted files. If the path does not match the file path,
2835
  //                    the file is extracted with its memorized path.
2836
  //                    $p_remove_path does not apply to 'list' mode.
2837
  //                    $p_path and $p_remove_path are commulative.
2838
  // Return Values :
2839
  //   1 on success,0 or less on error (see error code list)
2840
  // --------------------------------------------------------------------------------
2841
    protected function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
2842
    {
2843
        $v_result = 1;
2844
        // Magic quotes trick
2845
        $this->privDisableMagicQuotes();
2846
        // Check the path
2847
        if (
2848
            ($p_path == "") ||
2849
            (
2850
                (substr($p_path, 0, 1) != "/") &&
2851
                (substr($p_path, 0, 3) != "../") &&
2852
                (substr($p_path,1,2)!=":/")
2853
            )
2854
        ) {
2855
            $p_path = "./".$p_path;
2856
        }
2857
        // Reduce the path last (and duplicated) '/'
2858
        if (($p_path != "./") && ($p_path != "/")) {
2859
            // Look for the path end '/'
2860
            while (substr($p_path, -1) == "/") {
2861
                $p_path = substr($p_path, 0, strlen($p_path)-1);
2862
            }
2863
        }
2864
        // Look for path to remove format (should end by /)
2865
        if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) {
2866
            $p_remove_path .= '/';
2867
        }
2868
        $p_remove_path_size = strlen($p_remove_path);
2869
        // Open the zip file
2870
        if (($v_result = $this->privOpenFd('rb')) != 1) {
2871
            $this->privSwapBackMagicQuotes();
2872
            return $v_result;
2873
        }
2874
        // Read the central directory informations
2875
        $v_central_dir = array();
2876
        if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
2877
            // Close the zip file
2878
            $this->privCloseFd();
2879
            $this->privSwapBackMagicQuotes();
2880
            return $v_result;
2881
        }
2882
        // Start at beginning of Central Dir
2883
        $v_pos_entry = $v_central_dir['offset'];
2884
        // Read each entry
2885
        $j_start = 0;
2886
        for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; $i++) {
2887
            // Read next Central dir entry
2888
            @rewind($this->zip_fd);
2889
            if (@fseek($this->zip_fd, $v_pos_entry)) {
2890
                // Close the zip file
2891
                $this->privCloseFd();
2892
                $this->privSwapBackMagicQuotes();
2893
                // Error log
2894
                $this->privErrorLog(
2895
                    self::ERR_INVALID_ARCHIVE_ZIP,
2896
                    'Invalid archive size'
2897
                );
2898
                return self::errorCode();
2899
            }
2900
            // Read the file header
2901
            $v_header = array();
2902
            if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) {
2903
                // Close the zip file
2904
                $this->privCloseFd();
2905
                $this->privSwapBackMagicQuotes();
2906
                return $v_result;
2907
            }
2908
            // Store the index
2909
            $v_header['index'] = $i;
2910
            // Store the file position
2911
            $v_pos_entry = ftell($this->zip_fd);
2912
            // Look for the specific extract rules
2913
            $v_extract = false;
2914
            // Look for extract by name rule
2915
            if (   (isset($p_options[self::OPT_BY_NAME])) && ($p_options[self::OPT_BY_NAME] != 0)) {
2916
                // Look if the filename is in the list
2917
                for ($j = 0; ($j < sizeof($p_options[self::OPT_BY_NAME])) && (!$v_extract); $j++) {
2918
                    // Look for a directory
2919
                    if (substr($p_options[self::OPT_BY_NAME][$j], -1) == '/') {
2920
                        // Look if the directory is in the filename path
2921
                        if (
2922
                            (strlen($v_header['stored_filename']) > strlen($p_options[self::OPT_BY_NAME][$j])) &&
2923
                            (substr(
2924
                                $v_header['stored_filename'],
2925
                                0,
2926
                                strlen($p_options[self::OPT_BY_NAME][$j])) == $p_options[self::OPT_BY_NAME][$j]
2927
                            )
2928
                        ) {
2929
                            $v_extract = true;
2930
                        }
2931
                    } elseif ($v_header['stored_filename'] == $p_options[self::OPT_BY_NAME][$j]) {
2932
                    // Look for a filename
2933
                        $v_extract = true;
2934
                    }
2935
                }
2936
            } else if ((isset($p_options[self::OPT_BY_PREG])) && ($p_options[self::OPT_BY_PREG] != "")) {
2937
                // Look for extract by preg rule
2938
                if (preg_match($p_options[self::OPT_BY_PREG], $v_header['stored_filename'])) {
2939
                    $v_extract = true;
2940
                }
2941
            } else if ((isset($p_options[self::OPT_BY_INDEX])) && ($p_options[self::OPT_BY_INDEX] != 0)) {
2942
                // Look for extract by index rule
2943
                // Look if the index is in the list
2944
                for ($j=$j_start; ($j<sizeof($p_options[self::OPT_BY_INDEX])) && (!$v_extract); $j++) {
2945
                    if (($i>=$p_options[self::OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[self::OPT_BY_INDEX][$j]['end'])) {
2946
                        $v_extract = true;
2947
                    }
2948
                    if ($i>=$p_options[self::OPT_BY_INDEX][$j]['end']) {
2949
                        $j_start = $j+1;
2950
                    }
2951
                    if ($p_options[self::OPT_BY_INDEX][$j]['start']>$i) {
2952
                        break;
2953
                    }
2954
                }
2955
            } else {
2956
                // Look for no rule, which means extract all the archive
2957
                $v_extract = true;
2958
            }
2959
            // Check compression method
2960
            if (
2961
                ($v_extract) && (
2962
                    ($v_header['compression'] != 8) && ($v_header['compression'] != 0))
2963
            ) {
2964
                $v_header['status'] = 'unsupported_compression';
2965
                // Look for self::OPT_STOP_ON_ERROR
2966
                if (
2967
                    (isset($p_options[self::OPT_STOP_ON_ERROR])) && ($p_options[self::OPT_STOP_ON_ERROR]===true)
2968
                ) {
2969
                    $this->privSwapBackMagicQuotes();
2970
                    $this->privErrorLog(
2971
                        self::ERR_UNSUPPORTED_COMPRESSION,
2972
                        'Filename \''.$v_header['stored_filename'].'\' is '.
2973
                        'compressed by an unsupported compression method ('.$v_header['compression'].') '
2974
                    );
2975
                    return self::errorCode();
2976
                }
2977
            }
2978
            // Check encrypted files
2979
            if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
2980
                $v_header['status'] = 'unsupported_encryption';
2981
                // Look for self::OPT_STOP_ON_ERROR
2982
                if ((isset($p_options[self::OPT_STOP_ON_ERROR])) && ($p_options[self::OPT_STOP_ON_ERROR]===true)) {
2983
                    $this->privSwapBackMagicQuotes();
2984
                    $this->privErrorLog(
2985
                        self::ERR_UNSUPPORTED_ENCRYPTION,
2986
                        'Unsupported encryption for filename \''.$v_header['stored_filename'].'\''
2987
                    );
2988
                    return self::errorCode();
2989
                }
2990
            }
2991
            // Look for real extraction
2992
            if (($v_extract) && ($v_header['status'] != 'ok')) {
2993
                $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]);
2994
                if ($v_result != 1) {
2995
                    $this->privCloseFd();
2996
                    $this->privSwapBackMagicQuotes();
2997
                    return $v_result;
2998
                }
2999
                $v_extract = false;
3000
            }
3001
            // Look for real extraction
3002
            if ($v_extract) {
3003
                // Go to the file position
3004
                @rewind($this->zip_fd);
3005
                if (@fseek($this->zip_fd, $v_header['offset'])) {
3006
                    // Close the zip file
3007
                    $this->privCloseFd();
3008
                    $this->privSwapBackMagicQuotes();
3009
                    // Error log
3010
                    $this->privErrorLog(self::ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
3011
                    return self::errorCode();
3012
                }
3013
                // Look for extraction as string
3014
                if ($p_options[self::OPT_EXTRACT_AS_STRING]) {
3015
                    $v_string = '';
3016
                    // Extracting the file
3017
                    $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
3018
                    if ($v_result1 < 1) {
3019
                        $this->privCloseFd();
3020
                        $this->privSwapBackMagicQuotes();
3021
                        return $v_result1;
3022
                    }
3023
                    // Get the only interesting attributes
3024
                    if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) {
3025
                        // Close the zip file
3026
                        $this->privCloseFd();
3027
                        $this->privSwapBackMagicQuotes();
3028
                        return $v_result;
3029
                    }
3030
                    // Set the file content
3031
                    $p_file_list[$v_nb_extracted]['content'] = $v_string;
3032
                    // Next extracted file
3033
                    $v_nb_extracted++;
3034
                    // Look for user callback abort
3035
                    if ($v_result1 == 2) {
3036
                        break;
3037
                    }
3038
                } elseif ((isset($p_options[self::OPT_EXTRACT_IN_OUTPUT])) && ($p_options[self::OPT_EXTRACT_IN_OUTPUT])) {
3039
                    // Look for extraction in standard output
3040
                    // Extracting the file in standard output
3041
                    $v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
3042
                    if ($v_result1 < 1) {
3043
                        $this->privCloseFd();
3044
                        $this->privSwapBackMagicQuotes();
3045
                        return $v_result1;
3046
                    }
3047
                    // Get the only interesting attributes
3048
                    if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
3049
                        $this->privCloseFd();
3050
                        $this->privSwapBackMagicQuotes();
3051
                        return $v_result;
3052
                    }
3053
                    // Look for user callback abort
3054
                    if ($v_result1 == 2) {
3055
                        break;
3056
                    }
3057
                } else {
3058
                    // Look for normal extraction
3059
                    // Extracting the file
3060
                    $v_result1 = $this->privExtractFile(
3061
                        $v_header,
3062
                        $p_path,
3063
                        $p_remove_path,
3064
                        $p_remove_all_path,
3065
                        $p_options
3066
                    );
3067
                    if ($v_result1 < 1) {
3068
                        $this->privCloseFd();
3069
                        $this->privSwapBackMagicQuotes();
3070
                        return $v_result1;
3071
                    }
3072
                    // Get the only interesting attributes
3073
                    if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
3074
                        // Close the zip file
3075
                        $this->privCloseFd();
3076
                        $this->privSwapBackMagicQuotes();
3077
                        return $v_result;
3078
                    }
3079
                    // Look for user callback abort
3080
                    if ($v_result1 == 2) {
3081
                        break;
3082
                    }
3083
                }
3084
            }
3085
        }
3086
        // Close the zip file
3087
        $this->privCloseFd();
3088
        $this->privSwapBackMagicQuotes();
3089
        return $v_result;
3090
    }
3091
  // --------------------------------------------------------------------------------
3092

    
3093
  // --------------------------------------------------------------------------------
3094
  // Function : privExtractFile()
3095
  // Description :
3096
  // Parameters :
3097
  // Return Values :
3098
  //
3099
  // 1 : ... ?
3100
  // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
3101
  // --------------------------------------------------------------------------------
3102
    protected function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
3103
    {
3104
        $v_result = 1;
3105
        // Read the file header
3106
        if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
3107
            return $v_result;
3108
        }
3109
        // Check that the file header is coherent with $p_entry info
3110
        if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
3111
            // TBC
3112
        }
3113
        // Look for all path to remove
3114
        if ($p_remove_all_path == true) {
3115
            // Look for folder entry that not need to be extracted
3116
            if (($p_entry['external']&0x00000010)==0x00000010) {
3117
                $p_entry['status'] = "filtered";
3118
                return $v_result;
3119
            }
3120
            // Get the basename of the path
3121
            $p_entry['filename'] = basename($p_entry['filename']);
3122
        } else if ($p_remove_path != '') {
3123
        // Look for path to remove
3124
            if (self::UtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) {
3125
                // Change the file status
3126
                $p_entry['status'] = 'filtered';
3127
                // Return
3128
                return $v_result;
3129
            }
3130
            $p_remove_path_size = strlen($p_remove_path);
3131
            if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) {
3132
                // Remove the path
3133
                $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
3134
            }
3135
        }
3136
        // Add the path
3137
        if ($p_path != '') {
3138
            $p_entry['filename'] = $p_path."/".$p_entry['filename'];
3139
        }
3140
        // Check a base_dir_restriction
3141
        if (isset($p_options[self::OPT_EXTRACT_DIR_RESTRICTION])) {
3142
            $v_inclusion = self::UtilPathInclusion(
3143
                $p_options[self::OPT_EXTRACT_DIR_RESTRICTION] , $p_entry['filename']
3144
            );
3145
            if ($v_inclusion == 0) {
3146
                $this->privErrorLog(
3147
                    self::ERR_DIRECTORY_RESTRICTION,
3148
                    'Filename \''.$p_entry['filename'].'\' is outside '.self::OPT_EXTRACT_DIR_RESTRICTION
3149
                );
3150
                return self::errorCode();
3151
            }
3152
        }
3153
        // Look for pre-extract callback
3154
        if (isset($p_options[self::CB_PRE_EXTRACT])) {
3155
            // Generate a local information
3156
            $v_local_header = array();
3157
            $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3158
            // Call the callback
3159
            // Here I do not use call_user_func() because I need to send a reference to the header.
3160
//            eval('$v_result = '.$p_options[self::CB_PRE_EXTRACT].'(self::CB_PRE_EXTRACT, $v_local_header);');
3161
            $v_result = $p_options[self::CB_PRE_EXTRACT](self::CB_PRE_EXTRACT, $v_local_header);
3162
            if ($v_result == 0) {
3163
                // Change the file status
3164
                $p_entry['status'] = 'skipped';
3165
                $v_result = 1;
3166
            }
3167
            // Look for abort result
3168
            if ($v_result == 2) {
3169
                // This status is internal and will be changed in 'skipped'
3170
                $p_entry['status'] = 'aborted';
3171
                $v_result = self::ERR_USER_ABORTED;
3172
            }
3173
            // Update the informations
3174
            // Only some fields can be modified
3175
            $p_entry['filename'] = $v_local_header['filename'];
3176
        }
3177
        // Look if extraction should be done
3178
        if ($p_entry['status'] == 'ok') {
3179
            // Look for specific actions while the file exist
3180
            if (file_exists($p_entry['filename'])) {
3181
                // Look if file is a directory
3182
                if (is_dir($p_entry['filename'])) {
3183
                    // Change the file status
3184
                    $p_entry['status'] = 'already_a_directory';
3185
                    // Look for self::OPT_STOP_ON_ERROR
3186
                    // For historical reason first PclZip implementation does not stop
3187
                    // when this kind of error occurs.
3188
                    if ((isset($p_options[self::OPT_STOP_ON_ERROR])) && ($p_options[self::OPT_STOP_ON_ERROR]===true)) {
3189
                        $this->privErrorLog(
3190
                            self::ERR_ALREADY_A_DIRECTORY,
3191
                            'Filename \''.$p_entry['filename'].'\' is already used by an existing directory'
3192
                        );
3193
                        return PclZip::errorCode();
3194
                    }
3195
                } else if (!is_writeable($p_entry['filename'])) {
3196
                    // Look if file is write protected
3197
                    // Change the file status
3198
                    $p_entry['status'] = "write_protected";
3199
                    // Look for self::OPT_STOP_ON_ERROR
3200
                    // For historical reason first PclZip implementation does not stop
3201
                    // when this kind of error occurs.
3202
                    if ((isset($p_options[self::OPT_STOP_ON_ERROR])) && ($p_options[self::OPT_STOP_ON_ERROR]===true)) {
3203
                        $this->privErrorLog(
3204
                            self::ERR_WRITE_OPEN_FAIL,
3205
                            'Filename \''.$p_entry['filename'].'\' exists and is write protected'
3206
                        );
3207
                        return PclZip::errorCode();
3208
                    }
3209
                } else if (filemtime($p_entry['filename']) > $p_entry['mtime']) {
3210
                    // Look if the extracted file is older
3211
                    // Change the file status
3212
                    if ((isset($p_options[self::OPT_REPLACE_NEWER])) && ($p_options[self::OPT_REPLACE_NEWER]===true)) {
3213
                        // do nothing
3214
                    } else {
3215
                        $p_entry['status'] = 'newer_exist';
3216
                        // Look for self::OPT_STOP_ON_ERROR
3217
                        // For historical reason first PclZip implementation does not stop
3218
                        // when this kind of error occurs.
3219
                        if ((isset($p_options[self::OPT_STOP_ON_ERROR])) && ($p_options[self::OPT_STOP_ON_ERROR]===true)) {
3220
                            $this->privErrorLog(
3221
                                self::ERR_WRITE_OPEN_FAIL,
3222
                                'Newer version of \''.$p_entry['filename'].'\' exists and option PCLZIP_OPT_REPLACE_NEWER is not selected'
3223
                            );
3224
                            return self::errorCode();
3225
                        }
3226
                    }
3227
                } else { }
3228
            } else {
3229
                // Check the directory availability and create it if necessary
3230
                if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) {
3231
                    $v_dir_to_check = $p_entry['filename'];
3232
                } else if (!strstr($p_entry['filename'], "/")) {
3233
                    $v_dir_to_check = "";
3234
                } else {
3235
                    $v_dir_to_check = dirname($p_entry['filename']);
3236
                }
3237
                if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
3238
                    // Change the file status
3239
                    $p_entry['status'] = 'path_creation_fail';
3240
                    //return $v_result;
3241
                    $v_result = 1;
3242
                }
3243
            }
3244
        }
3245
        // Look if extraction should be done
3246
        if ($p_entry['status'] == 'ok') {
3247
            // Do the extraction (if not a folder)
3248
            if (!(($p_entry['external']&0x00000010)==0x00000010)) {
3249
                // Look for not compressed file
3250
                if ($p_entry['compression'] == 0) {
3251
                    // Opening destination file
3252
                    if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
3253
                        // Change the file status
3254
                        $p_entry['status'] = 'write_error';
3255
                        return $v_result;
3256
                    }
3257
                    // Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
3258
                    $v_size = $p_entry['compressed_size'];
3259
                    while ($v_size != 0) {
3260
                        $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
3261
                        $v_buffer = @fread($this->zip_fd, $v_read_size);
3262
//                        $v_binary_data = pack('a'.$v_read_size, $v_buffer);
3263
//                        @fwrite($v_dest_file, $v_binary_data, $v_read_size);
3264
                        @fwrite($v_dest_file, $v_buffer, $v_read_size);
3265
                        $v_size -= $v_read_size;
3266
                    }
3267
                    // Closing the destination file
3268
                    fclose($v_dest_file);
3269
                    // Change the file mtime
3270
                    touch($p_entry['filename'], $p_entry['mtime']);
3271
                } else {
3272
                    // TBC
3273
                    // Need to be finished
3274
                    if (($p_entry['flag'] & 1) == 1) {
3275
                        $this->privErrorLog(
3276
                            self::ERR_UNSUPPORTED_ENCRYPTION,
3277
                            'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'
3278
                        );
3279
                        return self::errorCode();
3280
                    }
3281
                    // Look for using temporary file to unzip
3282
                    if (
3283
                        (!isset($p_options[self::OPT_TEMP_FILE_OFF])) &&
3284
                        (isset($p_options[self::OPT_TEMP_FILE_ON]) ||
3285
                            (isset($p_options[self::OPT_TEMP_FILE_THRESHOLD]) &&
3286
                                ($p_options[self::OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])
3287
                            )
3288
                        )
3289
                    ) {
3290
                        $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
3291
                        if ($v_result < self::ERR_NO_ERROR) {
3292
                            return $v_result;
3293
                        }
3294
                    } else {
3295
                        // Look for extract in memory
3296
                        // Read the compressed file in a buffer (one shot)
3297
                        $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
3298
                        // Decompress the file
3299
                        $v_file_content = @gzinflate($v_buffer);
3300
                        unset($v_buffer);
3301
                        if ($v_file_content === false) {
3302
                            // Change the file status
3303
                            // TBC
3304
                            $p_entry['status'] = "error";
3305
                            return $v_result;
3306
                        }
3307
                        // Opening destination file
3308
                        if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
3309
                            // Change the file status
3310
                            $p_entry['status'] = "write_error";
3311
                            return $v_result;
3312
                        }
3313
                        // Write the uncompressed data
3314
                        @fwrite($v_dest_file, $v_file_content, $p_entry['size']);
3315
                        unset($v_file_content);
3316
                        // Closing the destination file
3317
                        @fclose($v_dest_file);
3318
                    }
3319
                    // Change the file mtime
3320
                    @touch($p_entry['filename'], $p_entry['mtime']);
3321
                }
3322
                // Look for chmod option
3323
                if (isset($p_options[self::OPT_SET_CHMOD])) {
3324
                    // Change the mode of the file
3325
                    @chmod($p_entry['filename'], $p_options[self::OPT_SET_CHMOD]);
3326
                }
3327
            }
3328
        }
3329
        // Change abort status
3330
        if ($p_entry['status'] == "aborted") {
3331
            $p_entry['status'] = "skipped";
3332
        } elseif (isset($p_options[self::CB_POST_EXTRACT])) {
3333
            // Look for post-extract callback
3334
            // Generate a local information
3335
            $v_local_header = array();
3336
            $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3337
            // Call the callback
3338
            // Here I do not use call_user_func() because I need to send a reference to the header.
3339
//            eval('$v_result = '.$p_options[self::CB_POST_EXTRACT].'(self::CB_POST_EXTRACT, $v_local_header);');
3340
            $v_result = $p_options[self::CB_POST_EXTRACT](self::CB_POST_EXTRACT, $v_local_header);
3341
            // Look for abort result
3342
            if ($v_result == 2) {
3343
                $v_result = self::ERR_USER_ABORTED;
3344
            }
3345
        }
3346
        return $v_result;
3347
    }
3348
  // --------------------------------------------------------------------------------
3349

    
3350
  // --------------------------------------------------------------------------------
3351
  // Function : privExtractFileUsingTempFile()
3352
  // Description :
3353
  // Parameters :
3354
  // Return Values :
3355
  // --------------------------------------------------------------------------------
3356
    protected function privExtractFileUsingTempFile(&$p_entry, &$p_options)
3357
    {
3358
        $v_result = 1;
3359
        // Creates a temporary file
3360
        $v_gzip_temp_name = self::TEMPORARY_DIR.uniqid('pclzip-').'.gz';
3361
        if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
3362
            fclose($v_file);
3363
            $this->privErrorLog(
3364
                self::ERR_WRITE_OPEN_FAIL,
3365
                'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'
3366
            );
3367
            return self::errorCode();
3368
        }
3369
        // Write gz file format header
3370
        $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
3371
        @fwrite($v_dest_file, $v_binary_data, 10);
3372
        // Read the file by self::READ_BLOCK_SIZE octets blocks
3373
        $v_size = $p_entry['compressed_size'];
3374
        while ($v_size != 0) {
3375
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
3376
            $v_buffer = @fread($this->zip_fd, $v_read_size);
3377
            //$v_binary_data = pack('a'.$v_read_size, $v_buffer);
3378
            @fwrite($v_dest_file, $v_buffer, $v_read_size);
3379
            $v_size -= $v_read_size;
3380
        }
3381
        // Write gz file format footer
3382
        $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
3383
        @fwrite($v_dest_file, $v_binary_data, 8);
3384
        // Close the temporary file
3385
        @fclose($v_dest_file);
3386
        // Opening destination file
3387
        if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
3388
            $p_entry['status'] = "write_error";
3389
            return $v_result;
3390
        }
3391
        // Open the temporary gz file
3392
        if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
3393
            @fclose($v_dest_file);
3394
            $p_entry['status'] = "read_error";
3395
            $this->privErrorLog(
3396
                self::ERR_READ_OPEN_FAIL,
3397
                'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'
3398
            );
3399
            return self::errorCode();
3400
        }
3401
        // Read the file by self::READ_BLOCK_SIZE octets blocks
3402
        $v_size = $p_entry['size'];
3403
        while ($v_size != 0) {
3404
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
3405
            $v_buffer = @gzread($v_src_file, $v_read_size);
3406
//            $v_binary_data = pack('a'.$v_read_size, $v_buffer);
3407
            @fwrite($v_dest_file, $v_buffer, $v_read_size);
3408
            $v_size -= $v_read_size;
3409
        }
3410
        @fclose($v_dest_file);
3411
        @gzclose($v_src_file);
3412
        // Delete the temporary file
3413
        @unlink($v_gzip_temp_name);
3414
        return $v_result;
3415
    }
3416
  // --------------------------------------------------------------------------------
3417

    
3418
  // --------------------------------------------------------------------------------
3419
  // Function : privExtractFileInOutput()
3420
  // Description :
3421
  // Parameters :
3422
  // Return Values :
3423
  // --------------------------------------------------------------------------------
3424
    protected function privExtractFileInOutput(&$p_entry, &$p_options)
3425
    {
3426
        $v_result=1;
3427
        // Read the file header
3428
        if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
3429
            return $v_result;
3430
        }
3431
        // Check that the file header is coherent with $p_entry info
3432
        if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
3433
            // TBC
3434
        }
3435
        // Look for pre-extract callback
3436
        if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) {
3437
            // Generate a local information
3438
            $v_local_header = array();
3439
            $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3440
            // Call the callback
3441
            // Here I do not use call_user_func() because I need to send a reference to the
3442
            // header.
3443
//            eval('$v_result = '.$p_options[self::CB_PRE_EXTRACT].'(self::CB_PRE_EXTRACT, $v_local_header);');
3444
            $v_result = $p_options[self::CB_PRE_EXTRACT](self::CB_PRE_EXTRACT, $v_local_header);
3445
            if ($v_result == 0) {
3446
                // Change the file status
3447
                $p_entry['status'] = "skipped";
3448
                $v_result = 1;
3449
            }
3450
            // Look for abort result
3451
            if ($v_result == 2) {
3452
                // This status is internal and will be changed in 'skipped'
3453
                $p_entry['status'] = "aborted";
3454
                $v_result = self::ERR_USER_ABORTED;
3455
            }
3456
            // Update the informations
3457
            // Only some fields can be modified
3458
            $p_entry['filename'] = $v_local_header['filename'];
3459
        }
3460
        // Trace
3461
        // Look if extraction should be done
3462
        if ($p_entry['status'] == 'ok') {
3463
            // Do the extraction (if not a folder)
3464
            if (!(($p_entry['external']&0x00000010)==0x00000010)) {
3465
                // Look for not compressed file
3466
                if ($p_entry['compressed_size'] == $p_entry['size']) {
3467
                    // Read the file in a buffer (one shot)
3468
                    $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
3469
                    // Send the file to the output
3470
                    echo $v_buffer;
3471
                    unset($v_buffer);
3472
                } else {
3473
                    // Read the compressed file in a buffer (one shot)
3474
                    $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
3475
                    // Decompress the file
3476
                    $v_file_content = gzinflate($v_buffer);
3477
                    unset($v_buffer);
3478
                    // Send the file to the output
3479
                    echo $v_file_content;
3480
                    unset($v_file_content);
3481
                }
3482
            }
3483
        }
3484
        // Change abort status
3485
        if ($p_entry['status'] == "aborted") {
3486
            $p_entry['status'] = "skipped";
3487
        } elseif (isset($p_options[self::CB_POST_EXTRACT])) {
3488
            // Look for post-extract callback
3489
            // Generate a local information
3490
            $v_local_header = array();
3491
            $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3492
            // Call the callback
3493
            // Here I do not use call_user_func() because I need to send a reference to the
3494
            // header.
3495
//            eval('$v_result = '.$p_options[self::CB_POST_EXTRACT].'(self::CB_POST_EXTRACT, $v_local_header);');
3496
            $v_result = $p_options[self::CB_POST_EXTRACT](self::CB_POST_EXTRACT, $v_local_header);
3497
            // Look for abort result
3498
            if ($v_result == 2) {
3499
                $v_result = self::ERR_USER_ABORTED;
3500
            }
3501
        }
3502
        return $v_result;
3503
    }
3504
  // --------------------------------------------------------------------------------
3505

    
3506
  // --------------------------------------------------------------------------------
3507
  // Function : privExtractFileAsString()
3508
  // Description :
3509
  // Parameters :
3510
  // Return Values :
3511
  // --------------------------------------------------------------------------------
3512
    protected function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
3513
    {
3514
        $v_result = 1;
3515
        // Read the file header
3516
        $v_header = array();
3517
        if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
3518
            return $v_result;
3519
        }
3520
        // Check that the file header is coherent with $p_entry info
3521
        if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
3522
            // TBC
3523
        }
3524
        // Look for pre-extract callback
3525
        if (isset($p_options[self::CB_PRE_EXTRACT])) {
3526
            // Generate a local information
3527
            $v_local_header = array();
3528
            $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3529
            // Call the callback
3530
            // Here I do not use call_user_func() because I need to send a reference to the header.
3531
//            eval('$v_result = '.$p_options[self::CB_PRE_EXTRACT].'(self::CB_PRE_EXTRACT, $v_local_header);');
3532
            $v_result = $p_options[self::CB_PRE_EXTRACT](self::CB_PRE_EXTRACT, $v_local_header);
3533
            if ($v_result == 0) {
3534
                // Change the file status
3535
                $p_entry['status'] = 'skipped';
3536
                $v_result = 1;
3537
            }
3538
            // Look for abort result
3539
            if ($v_result == 2) {
3540
                // This status is internal and will be changed in 'skipped'
3541
                $p_entry['status'] = "aborted";
3542
                $v_result = self::ERR_USER_ABORTED;
3543
            }
3544
            // Update the informations
3545
            // Only some fields can be modified
3546
            $p_entry['filename'] = $v_local_header['filename'];
3547
        }
3548
        // Look if extraction should be done
3549
        if ($p_entry['status'] == 'ok') {
3550
            // Do the extraction (if not a folder)
3551
            if (!(($p_entry['external']&0x00000010)==0x00000010)) {
3552
                // Look for not compressed file
3553
//                if ($p_entry['compressed_size'] == $p_entry['size'])
3554
                if ($p_entry['compression'] == 0) {
3555
                    // Reading the file
3556
                    $p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
3557
                } else {
3558
                    // Reading the file
3559
                    $v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
3560
                    // Decompress the file
3561
                    if (($p_string = @gzinflate($v_data)) === false) {
3562
                        // TBC
3563
                    }
3564
                }
3565
                // Trace
3566
            }  else {
3567
                // TBC : error : can not extract a folder in a string
3568
            }
3569
        }
3570
        // Change abort status
3571
        if ($p_entry['status'] == 'aborted') {
3572
            $p_entry['status'] = 'skipped';
3573
        } elseif (isset($p_options[self::CB_POST_EXTRACT])) {
3574
            // Look for post-extract callback
3575
            // Generate a local information
3576
            $v_local_header = array();
3577
            $this->privConvertHeader2FileInfo($p_entry, $v_local_header);
3578
            // Swap the content to header
3579
            $v_local_header['content'] = $p_string;
3580
            $p_string = '';
3581
            // Call the callback
3582
            // Here I do not use call_user_func() because I need to send a reference to the
3583
            // header.
3584
//            eval('$v_result = '.$p_options[self::CB_POST_EXTRACT].'(self::CB_POST_EXTRACT, $v_local_header);');
3585
            $v_result = $p_options[self::CB_POST_EXTRACT](self::CB_POST_EXTRACT, $v_local_header);
3586
            // Swap back the content to header
3587
            $p_string = $v_local_header['content'];
3588
            unset($v_local_header['content']);
3589
            // Look for abort result
3590
            if ($v_result == 2) {
3591
                $v_result = self::ERR_USER_ABORTED;
3592
            }
3593
        }
3594
        return $v_result;
3595
    }
3596
  // --------------------------------------------------------------------------------
3597

    
3598
  // --------------------------------------------------------------------------------
3599
  // Function : privReadFileHeader()
3600
  // Description :
3601
  // Parameters :
3602
  // Return Values :
3603
  // --------------------------------------------------------------------------------
3604
    protected function privReadFileHeader(&$p_header)
3605
    {
3606
        $v_result = 1;
3607
        // Read the 4 bytes signature
3608
        $v_binary_data = @fread($this->zip_fd, 4);
3609
        $v_data = unpack('Vid', $v_binary_data);
3610
        // Check signature
3611
        if ($v_data['id'] != 0x04034b50) {
3612
            // Error log
3613
            $this->privErrorLog(self::ERR_BAD_FORMAT, 'Invalid archive structure');
3614
            return self::errorCode();
3615
        }
3616
        // Read the first 42 bytes of the header
3617
        $v_binary_data = fread($this->zip_fd, 26);
3618
        // Look for invalid block size
3619
        if (strlen($v_binary_data) != 26) {
3620
            $p_header['filename'] = "";
3621
            $p_header['status'] = "invalid_header";
3622
            // Error log
3623
            $this->privErrorLog(self::ERR_BAD_FORMAT, 'Invalid block size : '.strlen($v_binary_data));
3624
            return self::errorCode();
3625
        }
3626
        // Extract the values
3627
        $v_data = unpack(
3628
            'vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len',
3629
            $v_binary_data
3630
        );
3631
        // Get filename
3632
        $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
3633
        // Get extra_fields
3634
        if ($v_data['extra_len'] != 0) {
3635
            $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
3636
        } else {
3637
            $p_header['extra'] = '';
3638
        }
3639
        // Extract properties
3640
        $p_header['version_extracted'] = $v_data['version'];
3641
        $p_header['compression']       = $v_data['compression'];
3642
        $p_header['size']              = $v_data['size'];
3643
        $p_header['compressed_size']   = $v_data['compressed_size'];
3644
        $p_header['crc']               = $v_data['crc'];
3645
        $p_header['flag']              = $v_data['flag'];
3646
        $p_header['filename_len']      = $v_data['filename_len'];
3647
        // Recuperate date in UNIX format
3648
        $p_header['mdate']             = $v_data['mdate'];
3649
        $p_header['mtime']             = $v_data['mtime'];
3650
        if ($p_header['mdate'] && $p_header['mtime']) {
3651
            // Extract time
3652
            $v_hour    = ($p_header['mtime'] & 0xF800) >> 11;
3653
            $v_minute  = ($p_header['mtime'] & 0x07E0) >> 5;
3654
            $v_seconde = ($p_header['mtime'] & 0x001F)*2;
3655
            // Extract date
3656
            $v_year    = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
3657
            $v_month   =  ($p_header['mdate'] & 0x01E0) >> 5;
3658
            $v_day     =   $p_header['mdate'] & 0x001F;
3659
            // Get UNIX date format
3660
            $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
3661
        } else {
3662
            $p_header['mtime'] = time();
3663
        }
3664
        // TBC
3665
        //for(reset($v_data); $key = key($v_data); next($v_data)) {
3666
        //}
3667
        // Set the stored filename
3668
        $p_header['stored_filename'] = $p_header['filename'];
3669
        // Set the status field
3670
        $p_header['status'] = "ok";
3671
        // Return
3672
        return $v_result;
3673
    }
3674
  // --------------------------------------------------------------------------------
3675

    
3676
  // --------------------------------------------------------------------------------
3677
  // Function : privReadCentralFileHeader()
3678
  // Description :
3679
  // Parameters :
3680
  // Return Values :
3681
  // --------------------------------------------------------------------------------
3682
    protected function privReadCentralFileHeader(&$p_header)
3683
    {
3684
        $v_result = 1;
3685
        // Read the 4 bytes signature
3686
        $v_binary_data = @fread($this->zip_fd, 4);
3687
        $v_data = unpack('Vid', $v_binary_data);
3688
        // Check signature
3689
        if ($v_data['id'] != 0x02014b50) {
3690
            // Error log
3691
            $this->privErrorLog(self::ERR_BAD_FORMAT, 'Invalid archive structure');
3692
            // Return
3693
            return self::errorCode();
3694
        }
3695
        // Read the first 42 bytes of the header
3696
        $v_binary_data = fread($this->zip_fd, 42);
3697
        // Look for invalid block size
3698
        if (strlen($v_binary_data) != 42) {
3699
            $p_header['filename'] = "";
3700
            $p_header['status'] = "invalid_header";
3701
            // Error log
3702
            $this->privErrorLog(self::ERR_BAD_FORMAT, 'Invalid block size : '.strlen($v_binary_data));
3703
            return self::errorCode();
3704
        }
3705
        // Extract the values
3706
        $p_header = unpack(
3707
            'vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/'.
3708
            'vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset',
3709
            $v_binary_data
3710
        );
3711
        // Get filename
3712
        if ($p_header['filename_len'] != 0) {
3713
            $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
3714
        } else {
3715
            $p_header['filename'] = '';
3716
        }
3717
        // Get extra
3718
        if ($p_header['extra_len'] != 0) {
3719
            $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
3720
        } else {
3721
            $p_header['extra'] = '';
3722
        }
3723
        // Get comment
3724
        if ($p_header['comment_len'] != 0) {
3725
            $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
3726
        } else {
3727
            $p_header['comment'] = '';
3728
        }
3729
        // Extract properties
3730
        // Recuperate date in UNIX format
3731
        //if ($p_header['mdate'] && $p_header['mtime'])
3732
        // TBC : bug : this was ignoring time with 0/0/0
3733
        if (1) {
3734
            // Extract time
3735
            $v_hour    = ($p_header['mtime'] & 0xF800) >> 11;
3736
            $v_minute  = ($p_header['mtime'] & 0x07E0) >> 5;
3737
            $v_seconde = ($p_header['mtime'] & 0x001F)*2;
3738
            // Extract date
3739
            $v_year  = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
3740
            $v_month =  ($p_header['mdate'] & 0x01E0) >> 5;
3741
            $v_day   =   $p_header['mdate'] & 0x001F;
3742
            // Get UNIX date format
3743
            $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
3744
        } else {
3745
            $p_header['mtime'] = time();
3746
        }
3747
        // Set the stored filename
3748
        $p_header['stored_filename'] = $p_header['filename'];
3749
        // Set default status to ok
3750
        $p_header['status'] = 'ok';
3751
        // Look if it is a directory
3752
        if (substr($p_header['filename'], -1) == '/') {
3753
            //$p_header['external'] = 0x41FF0010;
3754
            $p_header['external'] = 0x00000010;
3755
        }
3756
        return $v_result;
3757
    }
3758
  // --------------------------------------------------------------------------------
3759

    
3760
  // --------------------------------------------------------------------------------
3761
  // Function : privCheckFileHeaders()
3762
  // Description :
3763
  // Parameters :
3764
  // Return Values :
3765
  //   1 on success,
3766
  //   0 on error;
3767
  // --------------------------------------------------------------------------------
3768
    protected function privCheckFileHeaders(&$p_local_header, &$p_central_header)
3769
    {
3770
        $v_result = 1;
3771
        // Check the static values
3772
        // TBC
3773
        if ($p_local_header['filename'] != $p_central_header['filename']) {
3774
        }
3775
        if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
3776
        }
3777
        if ($p_local_header['flag'] != $p_central_header['flag']) {
3778
        }
3779
        if ($p_local_header['compression'] != $p_central_header['compression']) {
3780
        }
3781
        if ($p_local_header['mtime'] != $p_central_header['mtime']) {
3782
        }
3783
        if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
3784
        }
3785
        // Look for flag bit 3
3786
        if (($p_local_header['flag'] & 8) == 8) {
3787
            $p_local_header['size'] = $p_central_header['size'];
3788
            $p_local_header['compressed_size'] = $p_central_header['compressed_size'];
3789
            $p_local_header['crc'] = $p_central_header['crc'];
3790
        }
3791
        return $v_result;
3792
    }
3793
  // --------------------------------------------------------------------------------
3794

    
3795
  // --------------------------------------------------------------------------------
3796
  // Function : privReadEndCentralDir()
3797
  // Description :
3798
  // Parameters :
3799
  // Return Values :
3800
  // --------------------------------------------------------------------------------
3801
    public function privReadEndCentralDir(&$p_central_dir)
3802
    {
3803
        $v_result = 1;
3804
        // Go to the end of the zip file
3805
        $v_size = filesize($this->zipname);
3806
        @fseek($this->zip_fd, $v_size);
3807
        if (@ftell($this->zip_fd) != $v_size) {
3808
            // Error log
3809
            $this->privErrorLog(self::ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
3810
            return self::errorCode();
3811
        }
3812
        // First try : look if this is an archive with no commentaries (most of the time)
3813
        // in this case the end of central dir is at 22 bytes of the file end
3814
        $v_found = 0;
3815
        if ($v_size > 26) {
3816
            @fseek($this->zip_fd, $v_size-22);
3817
            if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) {
3818
              // Error log
3819
              $this->privErrorLog(self::ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
3820
              return self::errorCode();
3821
            }
3822
            // Read for bytes
3823
            $v_binary_data = @fread($this->zip_fd, 4);
3824
            $v_data = @unpack('Vid', $v_binary_data);
3825
            // Check signature
3826
            if ($v_data['id'] == 0x06054b50) {
3827
                $v_found = 1;
3828
            }
3829
            $v_pos = ftell($this->zip_fd);
3830
        }
3831
        // Go back to the maximum possible size of the Central Dir End Record
3832
        if (!$v_found) {
3833
            $v_maximum_size = 65557; // 0xFFFF + 22;
3834
            if ($v_maximum_size > $v_size) {
3835
                $v_maximum_size = $v_size;
3836
            }
3837
            @fseek($this->zip_fd, $v_size-$v_maximum_size);
3838
            if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) {
3839
                // Error log
3840
                $this->privErrorLog(self::ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
3841
                return self::errorCode();
3842
            }
3843
            // Read byte per byte in order to find the signature
3844
            $v_pos = ftell($this->zip_fd);
3845
            $v_bytes = 0x00000000;
3846
            while ($v_pos < $v_size) {
3847
                // Read a byte
3848
                $v_byte = @fread($this->zip_fd, 1);
3849
                //  Add the byte
3850
                //$v_bytes = ($v_bytes << 8) | Ord($v_byte);
3851
                // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
3852
                // Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
3853
                $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
3854
                // Compare the bytes
3855
                if ($v_bytes == 0x504b0506) {
3856
                    $v_pos++;
3857
                    break;
3858
                }
3859
                $v_pos++;
3860
            }
3861
            // Look if not found end of central dir
3862
            if ($v_pos == $v_size) {
3863
                // Error log
3864
                $this->privErrorLog(self::ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
3865
                return self::errorCode();
3866
            }
3867
        }
3868
        // Read the first 18 bytes of the header
3869
        $v_binary_data = fread($this->zip_fd, 18);
3870
        // Look for invalid block size
3871
        if (strlen($v_binary_data) != 18) {
3872
          // Error log
3873
            $this->privErrorLog(self::ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
3874
            return self::errorCode();
3875
        }
3876
        // Extract the values
3877
        $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
3878
        // Check the global size
3879
        if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
3880
            // Removed in release 2.2 see readme file
3881
            // The check of the file size is a little too strict.
3882
            // Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
3883
            // While decrypted, zip has training 0 bytes
3884
            if (0) {
3885
                // Error log
3886
                $this->privErrorLog(
3887
                    self::ERR_BAD_FORMAT,
3888
                    'The central dir is not at the end of the archive. Some trailing bytes exists after the archive.'
3889
                );
3890
                return self::errorCode();
3891
            }
3892
        }
3893
        // Get comment
3894
        if ($v_data['comment_size'] != 0) {
3895
            $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
3896
        } else {
3897
            $p_central_dir['comment'] = '';
3898
        }
3899
        $p_central_dir['entries']      = $v_data['entries'];
3900
        $p_central_dir['disk_entries'] = $v_data['disk_entries'];
3901
        $p_central_dir['offset']       = $v_data['offset'];
3902
        $p_central_dir['size']         = $v_data['size'];
3903
        $p_central_dir['disk']         = $v_data['disk'];
3904
        $p_central_dir['disk_start']   = $v_data['disk_start'];
3905
        // TBC
3906
        //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
3907
        //}
3908
        return $v_result;
3909
    }
3910
  // --------------------------------------------------------------------------------
3911

    
3912
  // --------------------------------------------------------------------------------
3913
  // Function : privDeleteByRule()
3914
  // Description :
3915
  // Parameters :
3916
  // Return Values :
3917
  // --------------------------------------------------------------------------------
3918
    protected function privDeleteByRule(&$p_result_list, &$p_options)
3919
    {
3920
        $v_result = 1;
3921
        $v_list_detail = array();
3922
        // Open the zip file
3923
        if (($v_result=$this->privOpenFd('rb')) != 1) {
3924
            return $v_result;
3925
        }
3926
        // Read the central directory informations
3927
        $v_central_dir = array();
3928
        if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
3929
            $this->privCloseFd();
3930
            return $v_result;
3931
        }
3932
        // Go to beginning of File
3933
        @rewind($this->zip_fd);
3934
        // Scan all the files
3935
        // Start at beginning of Central Dir
3936
        $v_pos_entry = $v_central_dir['offset'];
3937
        @rewind($this->zip_fd);
3938
        if (@fseek($this->zip_fd, $v_pos_entry)) {
3939
            // Close the zip file
3940
            $this->privCloseFd();
3941
            // Error log
3942
            $this->privErrorLog(self::ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
3943
            return self::errorCode();
3944
        }
3945
        // Read each entry
3946
        $v_header_list = array();
3947
        $j_start = 0;
3948
        for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) {
3949
            // Read the file header
3950
            $v_header_list[$v_nb_extracted] = array();
3951
            if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) {
3952
                // Close the zip file
3953
                $this->privCloseFd();
3954
                return $v_result;
3955
            }
3956
            // Store the index
3957
            $v_header_list[$v_nb_extracted]['index'] = $i;
3958
            // Look for the specific extract rules
3959
            $v_found = false;
3960
            // Look for extract by name rule
3961
            if ((isset($p_options[self::OPT_BY_NAME])) && ($p_options[self::OPT_BY_NAME] != 0)) {
3962
                // Look if the filename is in the list
3963
                for ($j=0; ($j<sizeof($p_options[self::OPT_BY_NAME])) && (!$v_found); $j++) {
3964
                    // Look for a directory
3965
                    if (substr($p_options[self::OPT_BY_NAME][$j], -1) == "/") {
3966
                        // Look if the directory is in the filename path
3967
                        if (
3968
                            (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[self::OPT_BY_NAME][$j])) &&
3969
                            (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[self::OPT_BY_NAME][$j]))
3970
                                == $p_options[self::OPT_BY_NAME][$j])
3971
                        ) {
3972
                            $v_found = true;
3973
                        } elseif (
3974
                            (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) && /* Indicates a folder */
3975
                            ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[self::OPT_BY_NAME][$j])
3976
                        ) {
3977
                            $v_found = true;
3978
                        }
3979
                    } elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[self::OPT_BY_NAME][$j]) {
3980
                        // Look for a filename
3981
                        $v_found = true;
3982
                    }
3983
                }
3984
            } else if (   (isset($p_options[self::OPT_BY_PREG]))
3985
                     && ($p_options[self::OPT_BY_PREG] != "")) {
3986
            // Look for extract by ereg rule
3987
            // ereg() is deprecated with PHP 5.3
3988
            /*
3989
            else if (   (isset($p_options[PCLZIP_OPT_BY_EREG]))
3990
                     && ($p_options[PCLZIP_OPT_BY_EREG] != "")) {
3991
                if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
3992
                    $v_found = true;
3993
                }
3994
            }
3995
            */
3996
                // Look for extract by preg rule
3997
                if (preg_match($p_options[self::OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
3998
                    $v_found = true;
3999
                }
4000
            } else if ((isset($p_options[self::OPT_BY_INDEX])) && ($p_options[self::OPT_BY_INDEX] != 0)) {
4001
                // Look for extract by index rule
4002
                // Look if the index is in the list
4003
                for ($j=$j_start; ($j<sizeof($p_options[self::OPT_BY_INDEX])) && (!$v_found); $j++) {
4004
                    if (($i>=$p_options[self::OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[self::OPT_BY_INDEX][$j]['end'])) {
4005
                        $v_found = true;
4006
                    }
4007
                    if ($i>=$p_options[self::OPT_BY_INDEX][$j]['end']) {
4008
                        $j_start = $j+1;
4009
                    }
4010
                    if ($p_options[self::OPT_BY_INDEX][$j]['start']>$i) {
4011
                        break;
4012
                    }
4013
                }
4014
            } else {
4015
                $v_found = true;
4016
            }
4017
            // Look for deletion
4018
            if ($v_found) {
4019
                unset($v_header_list[$v_nb_extracted]);
4020
            } else {
4021
                $v_nb_extracted++;
4022
            }
4023
        }
4024
        // Look if something need to be deleted
4025
        if ($v_nb_extracted > 0) {
4026
            // Creates a temporay file
4027
            $v_zip_temp_name = self::TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
4028
            // Creates a temporary zip archive
4029
            $sClass = __CLASS__;
4030
            $v_temp_zip = new $sClass($v_zip_temp_name);
4031
            // Open the temporary zip file in write mode
4032
            if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
4033
                $this->privCloseFd();
4034
                return $v_result;
4035
            }
4036
            // Look which file need to be kept
4037
            for ($i=0; $i<sizeof($v_header_list); $i++) {
4038
                // Calculate the position of the header
4039
                @rewind($this->zip_fd);
4040
                if (@fseek($this->zip_fd,  $v_header_list[$i]['offset'])) {
4041
                    // Close the zip file
4042
                    $this->privCloseFd();
4043
                    $v_temp_zip->privCloseFd();
4044
                    @unlink($v_zip_temp_name);
4045
                    // Error log
4046
                    $this->privErrorLog(self::ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
4047
                    return self::errorCode();
4048
                }
4049
                // Read the file header
4050
                $v_local_header = array();
4051
                if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
4052
                    // Close the zip file
4053
                    $this->privCloseFd();
4054
                    $v_temp_zip->privCloseFd();
4055
                    @unlink($v_zip_temp_name);
4056
                    return $v_result;
4057
                }
4058
                // Check that local file header is same as central file header
4059
                if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) {
4060
                    // TBC
4061
                }
4062
                unset($v_local_header);
4063
                // Write the file header
4064
                if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
4065
                    // Close the zip file
4066
                    $this->privCloseFd();
4067
                    $v_temp_zip->privCloseFd();
4068
                    @unlink($v_zip_temp_name);
4069
                    return $v_result;
4070
                }
4071
                // Read/write the data block
4072
                if (($v_result = self::UtilCopyBlock(
4073
                    $this->zip_fd,
4074
                    $v_temp_zip->zip_fd,
4075
                    $v_header_list[$i]['compressed_size'])) != 1
4076
                ) {
4077
                    // Close the zip file
4078
                    $this->privCloseFd();
4079
                    $v_temp_zip->privCloseFd();
4080
                    @unlink($v_zip_temp_name);
4081
                    return $v_result;
4082
                }
4083
            }
4084
            // Store the offset of the central dir
4085
            $v_offset = @ftell($v_temp_zip->zip_fd);
4086
            // Re-Create the Central Dir files header
4087
            for ($i=0; $i<sizeof($v_header_list); $i++) {
4088
                // Create the file header
4089
                if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
4090
                    $v_temp_zip->privCloseFd();
4091
                    $this->privCloseFd();
4092
                    @unlink($v_zip_temp_name);
4093
                    return $v_result;
4094
                }
4095
                // Transform the header to a 'usable' info
4096
                $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
4097
            }
4098
            // Zip file comment
4099
            $v_comment = '';
4100
            if (isset($p_options[self::OPT_COMMENT])) {
4101
                $v_comment = $p_options[self::OPT_COMMENT];
4102
            }
4103
            // Calculate the size of the central header
4104
            $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
4105
            // Create the central dir footer
4106
            if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
4107
                // Reset the file list
4108
                unset($v_header_list);
4109
                $v_temp_zip->privCloseFd();
4110
                $this->privCloseFd();
4111
                @unlink($v_zip_temp_name);
4112
                return $v_result;
4113
            }
4114
            // Close
4115
            $v_temp_zip->privCloseFd();
4116
            $this->privCloseFd();
4117
            // Delete the zip file
4118
            // TBC : I should test the result ...
4119
            @unlink($this->zipname);
4120
            // Rename the temporary file
4121
            // TBC : I should test the result ...
4122
            //@rename($v_zip_temp_name, $this->zipname);
4123
            self::UtilRename($v_zip_temp_name, $this->zipname);
4124
            // Destroy the temporary archive
4125
            unset($v_temp_zip);
4126
        } else if ($v_central_dir['entries'] != 0) {
4127
            // Remove every files : reset the file
4128
            $this->privCloseFd();
4129
            if (($v_result = $this->privOpenFd('wb')) != 1) {
4130
                return $v_result;
4131
            }
4132
            if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
4133
                return $v_result;
4134
            }
4135
            $this->privCloseFd();
4136
        }
4137
        return $v_result;
4138
    }
4139
  // --------------------------------------------------------------------------------
4140

    
4141
  // --------------------------------------------------------------------------------
4142
  // Function : privDirCheck()
4143
  // Description :
4144
  //   Check if a directory exists, if not it creates it and all the parents directory
4145
  //   which may be useful.
4146
  // Parameters :
4147
  //   $p_dir : Directory path to check.
4148
  // Return Values :
4149
  //    1 : OK
4150
  //   -1 : Unable to create directory
4151
  // --------------------------------------------------------------------------------
4152
    protected function privDirCheck($p_dir, $p_is_dir=false)
4153
    {
4154
        $v_result = 1;
4155
        // Remove the final '/'
4156
        if (($p_is_dir) && (substr($p_dir, -1)=='/')) {
4157
            $p_dir = substr($p_dir, 0, strlen($p_dir)-1);
4158
        }
4159
        // Check the directory availability
4160
        if ((is_dir($p_dir)) || ($p_dir == '')) {
4161
            return 1;
4162
        }
4163
        // Extract parent directory
4164
        $p_parent_dir = dirname($p_dir);
4165
        // Just a check
4166
        if ($p_parent_dir != $p_dir) {
4167
            // Look for parent directory
4168
            if ($p_parent_dir != '') {
4169
                if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) {
4170
                    return $v_result;
4171
                }
4172
            }
4173
        }
4174
        // Create the directory
4175
        if (!@mkdir($p_dir, 0777)) {
4176
            // Error log
4177
            $this->privErrorLog(self::ERR_DIR_CREATE_FAIL, 'Unable to create directory \''.$p_dir.'\'');
4178
            return self::errorCode();
4179
        }
4180
        return $v_result;
4181
    }
4182
  // --------------------------------------------------------------------------------
4183

    
4184
  // --------------------------------------------------------------------------------
4185
  // Function : privMerge()
4186
  // Description :
4187
  //   If $p_archive_to_add does not exist, the function exit with a success result.
4188
  // Parameters :
4189
  // Return Values :
4190
  // --------------------------------------------------------------------------------
4191
    protected function privMerge(&$p_archive_to_add)
4192
    {
4193
        $v_result = 1;
4194
        // Look if the archive_to_add exists
4195
        if (!is_file($p_archive_to_add->zipname)) {
4196
            // Nothing to merge, so merge is a success
4197
            $v_result = 1;
4198
            return $v_result;
4199
        }
4200
        // Look if the archive exists
4201
        if (!is_file($this->zipname)) {
4202
            // Do a duplicate
4203
            $v_result = $this->privDuplicate($p_archive_to_add->zipname);
4204
            return $v_result;
4205
        }
4206
        // Open the zip file
4207
        if (($v_result=$this->privOpenFd('rb')) != 1) {
4208
            return $v_result;
4209
        }
4210
        // Read the central directory informations
4211
        $v_central_dir = array();
4212
        if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
4213
            $this->privCloseFd();
4214
            return $v_result;
4215
        }
4216
        // Go to beginning of File
4217
        @rewind($this->zip_fd);
4218
        // Open the archive_to_add file
4219
        if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) {
4220
            $this->privCloseFd();
4221
            return $v_result;
4222
        }
4223
        // Read the central directory informations
4224
        $v_central_dir_to_add = array();
4225
        if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) {
4226
            $this->privCloseFd();
4227
            $p_archive_to_add->privCloseFd();
4228
            return $v_result;
4229
        }
4230
        // Go to beginning of File
4231
        @rewind($p_archive_to_add->zip_fd);
4232
        // Creates a temporay file
4233
        $v_zip_temp_name = self::TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
4234
        // Open the temporary file in write mode
4235
        if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
4236
            $this->privCloseFd();
4237
            $p_archive_to_add->privCloseFd();
4238
            $this->privErrorLog(
4239
                self::ERR_READ_OPEN_FAIL,
4240
                'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'
4241
            );
4242
            return self::errorCode();
4243
        }
4244
        // Copy the files from the archive to the temporary file
4245
        // TBC : Here I should better append the file and go back to erase the central dir
4246
        $v_size = $v_central_dir['offset'];
4247
        while ($v_size != 0) {
4248
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
4249
            $v_buffer = fread($this->zip_fd, $v_read_size);
4250
            @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4251
            $v_size -= $v_read_size;
4252
        }
4253
        // Copy the files from the archive_to_add into the temporary file
4254
        $v_size = $v_central_dir_to_add['offset'];
4255
        while ($v_size != 0) {
4256
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
4257
            $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
4258
            @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4259
            $v_size -= $v_read_size;
4260
        }
4261
        // Store the offset of the central dir
4262
        $v_offset = @ftell($v_zip_temp_fd);
4263
        // Copy the block of file headers from the old archive
4264
        $v_size = $v_central_dir['size'];
4265
        while ($v_size != 0) {
4266
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
4267
            $v_buffer = @fread($this->zip_fd, $v_read_size);
4268
            @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4269
            $v_size -= $v_read_size;
4270
        }
4271
        // Copy the block of file headers from the archive_to_add
4272
        $v_size = $v_central_dir_to_add['size'];
4273
        while ($v_size != 0) {
4274
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
4275
            $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
4276
            @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
4277
            $v_size -= $v_read_size;
4278
        }
4279
        // Merge the file comments
4280
        $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
4281
        // Calculate the size of the (new) central header
4282
        $v_size = @ftell($v_zip_temp_fd)-$v_offset;
4283
        // Swap the file descriptor
4284
        // Here is a trick : I swap the temporary fd with the zip fd, in order to use
4285
        // the following methods on the temporary fil and not the real archive fd
4286
        $v_swap = $this->zip_fd;
4287
        $this->zip_fd = $v_zip_temp_fd;
4288
        $v_zip_temp_fd = $v_swap;
4289
        // Create the central dir footer
4290
        if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) {
4291
            $this->privCloseFd();
4292
            $p_archive_to_add->privCloseFd();
4293
            @fclose($v_zip_temp_fd);
4294
            $this->zip_fd = null;
4295
            // Reset the file list
4296
            unset($v_header_list);
4297
            return $v_result;
4298
        }
4299
        // Swap back the file descriptor
4300
        $v_swap = $this->zip_fd;
4301
        $this->zip_fd = $v_zip_temp_fd;
4302
        $v_zip_temp_fd = $v_swap;
4303
        // Close
4304
        $this->privCloseFd();
4305
        $p_archive_to_add->privCloseFd();
4306
        // Close the temporary file
4307
        @fclose($v_zip_temp_fd);
4308
        // Delete the zip file
4309
        // TBC : I should test the result ...
4310
        @unlink($this->zipname);
4311
        // Rename the temporary file
4312
        // TBC : I should test the result ...
4313
        //@rename($v_zip_temp_name, $this->zipname);
4314
        self::UtilRename($v_zip_temp_name, $this->zipname);
4315
        return $v_result;
4316
    }
4317
  // --------------------------------------------------------------------------------
4318

    
4319
  // --------------------------------------------------------------------------------
4320
  // Function : privDuplicate()
4321
  // Description :
4322
  // Parameters :
4323
  // Return Values :
4324
  // --------------------------------------------------------------------------------
4325
    protected function privDuplicate($p_archive_filename)
4326
    {
4327
        $v_result = 1;
4328
        // Look if the $p_archive_filename exists
4329
        if (!is_file($p_archive_filename)) {
4330
            // Nothing to duplicate, so duplicate is a success.
4331
            $v_result = 1;
4332
            return $v_result;
4333
        }
4334
        // Open the zip file
4335
        if (($v_result=$this->privOpenFd('wb')) != 1) {
4336
            return $v_result;
4337
        }
4338
        // Open the temporary file in write mode
4339
        if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) {
4340
            $this->privCloseFd();
4341
            $this->privErrorLog(self::ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
4342
            return self::errorCode();
4343
        }
4344
        // Copy the files from the archive to the temporary file
4345
        // TBC : Here I should better append the file and go back to erase the central dir
4346
        $v_size = filesize($p_archive_filename);
4347
        while ($v_size != 0) {
4348
            $v_read_size = ($v_size < self::READ_BLOCK_SIZE ? $v_size : self::READ_BLOCK_SIZE);
4349
            $v_buffer = fread($v_zip_temp_fd, $v_read_size);
4350
            @fwrite($this->zip_fd, $v_buffer, $v_read_size);
4351
            $v_size -= $v_read_size;
4352
        }
4353
        // Close
4354
        $this->privCloseFd();
4355
        // Close the temporary file
4356
        @fclose($v_zip_temp_fd);
4357
        return $v_result;
4358
    }
4359
  // --------------------------------------------------------------------------------
4360

    
4361
  // --------------------------------------------------------------------------------
4362
  // Function : privErrorLog()
4363
  // Description :
4364
  // Parameters :
4365
  // --------------------------------------------------------------------------------
4366
    protected function privErrorLog($p_error_code=0, $p_error_string='')
4367
    {
4368
        if (self::ERROR_EXTERNAL == 1) {
4369
            PclError($p_error_code, $p_error_string);
4370
        } else {
4371
            $this->error_code = $p_error_code;
4372
            $this->error_string = $p_error_string;
4373
        }
4374
    }
4375
  // --------------------------------------------------------------------------------
4376

    
4377
  // --------------------------------------------------------------------------------
4378
  // Function : privErrorReset()
4379
  // Description :
4380
  // Parameters :
4381
  // --------------------------------------------------------------------------------
4382
    protected function privErrorReset()
4383
    {
4384
        if (self::ERROR_EXTERNAL == 1) {
4385
            PclErrorReset();
4386
        } else {
4387
            $this->error_code = 0;
4388
            $this->error_string = '';
4389
        }
4390
    }
4391
  // --------------------------------------------------------------------------------
4392

    
4393
  // --------------------------------------------------------------------------------
4394
  // Function : privDisableMagicQuotes()
4395
  // Description :
4396
  // Parameters :
4397
  // Return Values :
4398
  // --------------------------------------------------------------------------------
4399
    protected function privDisableMagicQuotes()
4400
    {
4401
        $v_result = 1;
4402
        // Look if function exists
4403
        if ((!function_exists('get_magic_quotes_runtime')) || (!function_exists('set_magic_quotes_runtime'))) {
4404
            return $v_result;
4405
        }
4406
        // Look if already done
4407
        if ($this->magic_quotes_status != -1) {
4408
            return $v_result;
4409
        }
4410
        // Get and memorize the magic_quote value
4411
        $this->magic_quotes_status = @get_magic_quotes_runtime();
4412
        // Disable magic_quotes
4413
        if ($this->magic_quotes_status == 1) {
4414
            @set_magic_quotes_runtime(0);
4415
        }
4416
        return $v_result;
4417
    }
4418
  // --------------------------------------------------------------------------------
4419

    
4420
  // --------------------------------------------------------------------------------
4421
  // Function : privSwapBackMagicQuotes()
4422
  // Description :
4423
  // Parameters :
4424
  // Return Values :
4425
  // --------------------------------------------------------------------------------
4426
    protected function privSwapBackMagicQuotes()
4427
    {
4428
        $v_result = 1;
4429
        // Look if function exists
4430
        if ((!function_exists('get_magic_quotes_runtime')) || (!function_exists('set_magic_quotes_runtime'))) {
4431
            return $v_result;
4432
        }
4433
        // Look if something to do
4434
        if ($this->magic_quotes_status != -1) {
4435
            return $v_result;
4436
        }
4437
        // Swap back magic_quotes
4438
        if ($this->magic_quotes_status == 1) {
4439
            @set_magic_quotes_runtime($this->magic_quotes_status);
4440
        }
4441
        return $v_result;
4442
    }
4443
  // --------------------------------------------------------------------------------
4444

    
4445
/**
4446
 * get all
4447
 * @staticvar null $aFullList
4448
 * @return array
4449
 */
4450
    protected static function getClassConstants()
4451
    {
4452
        static $aFullList = null; // list caching
4453
        if ($aFullList === null) {
4454
            // load cache
4455
            $reflect = new ReflectionClass(__CLASS__);
4456
            // read list of constants and remove unneeded from list
4457
            $aFullList = array_diff_key(
4458
                $reflect->getConstants(),
4459
                array_flip(
4460
                    array(
4461
                        'READ_BLOCK_SIZE','SEPARATOR','ERROR_EXTERNAL',
4462
                        'TEMPORARY_DIR', 'TEMPORARY_FILE_RATIO'
4463
                    )
4464
                )
4465
            );
4466
        }
4467
        return $aFullList;
4468
    }
4469

    
4470
  // --------------------------------------------------------------------------------
4471
  // Function : UtilPathReduction()
4472
  // Description :
4473
  // Parameters :
4474
  // Return Values :
4475
  // --------------------------------------------------------------------------------
4476
    public static function UtilPathReduction($p_dir)
4477
    {
4478
        $v_result = '';
4479
        // Look for not empty path
4480
        if ($p_dir != "") {
4481
            // Explode path by directory names
4482
            $v_list = explode("/", $p_dir);
4483
            // Study directories from last to first
4484
            $v_skip = 0;
4485
            for ($i=sizeof($v_list)-1; $i>=0; $i--) {
4486
                // Look for current path
4487
                if ($v_list[$i] == ".") {
4488
                  // Ignore this directory
4489
                  // Should be the first $i=0, but no check is done
4490
                } else if ($v_list[$i] == "..") {
4491
                    $v_skip++;
4492
                } else if ($v_list[$i] == "") {
4493
                // First '/' i.e. root slash
4494
                    if ($i == 0) {
4495
                        $v_result = "/".$v_result;
4496
                        if ($v_skip > 0) {
4497
                            // It is an invalid path, so the path is not modified
4498
                            // TBC
4499
                            $v_result = $p_dir;
4500
                            $v_skip = 0;
4501
                        }
4502
                    } else if ($i == (sizeof($v_list)-1)) {
4503
                        // Last '/' i.e. indicates a directory
4504
                        $v_result = $v_list[$i];
4505
                    } else {
4506
                        // Double '/' inside the path
4507
                        // Ignore only the double '//' in path,
4508
                        // but not the first and last '/'
4509
                    }
4510
                } else {
4511
                    // Look for item to skip
4512
                    if ($v_skip > 0) {
4513
                        $v_skip--;
4514
                    } else {
4515
                        $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
4516
                    }
4517
                }
4518
            }
4519
            // Look for skip
4520
            if ($v_skip > 0) {
4521
                while ($v_skip > 0) {
4522
                    $v_result = '../'.$v_result;
4523
                    $v_skip--;
4524
                }
4525
            }
4526
        }
4527
        // Return
4528
        return $v_result;
4529
    }
4530
  // --------------------------------------------------------------------------------
4531

    
4532
  // --------------------------------------------------------------------------------
4533
  // Function : self::UtilPathInclusion()
4534
  // Description :
4535
  //   This function indicates if the path $p_path is under the $p_dir tree. Or,
4536
  //   said in an other way, if the file or sub-dir $p_path is inside the dir
4537
  //   $p_dir.
4538
  //   The function indicates also if the path is exactly the same as the dir.
4539
  //   This function supports path with duplicated '/' like '//', but does not
4540
  //   support '.' or '..' statements.
4541
  // Parameters :
4542
  // Return Values :
4543
  //   0 if $p_path is not inside directory $p_dir
4544
  //   1 if $p_path is inside directory $p_dir
4545
  //   2 if $p_path is exactly the same as $p_dir
4546
  // --------------------------------------------------------------------------------
4547
    public static function UtilPathInclusion($p_dir, $p_path)
4548
    {
4549
        $v_result = 1;
4550
        // Look for path beginning by ./
4551
        if (($p_dir == '.') || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
4552
            $p_dir = self::UtilTranslateWinPath(getcwd(), false).'/'.substr($p_dir, 1);
4553
        }
4554
        if (($p_path == '.') || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
4555
            $p_path = self::UtilTranslateWinPath(getcwd(), false).'/'.substr($p_path, 1);
4556
        }
4557
        // Explode dir and path by directory separator
4558
        $v_list_dir       = explode("/", $p_dir);
4559
        $v_list_dir_size  = sizeof($v_list_dir);
4560
        $v_list_path      = explode("/", $p_path);
4561
        $v_list_path_size = sizeof($v_list_path);
4562
        // Study directories paths
4563
        $i = 0;
4564
        $j = 0;
4565
        while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
4566
            // Look for empty dir (path reduction)
4567
            if ($v_list_dir[$i] == '') {
4568
                $i++;
4569
                continue;
4570
            }
4571
            if ($v_list_path[$j] == '') {
4572
                $j++;
4573
                continue;
4574
            }
4575
            // Compare the items
4576
            if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
4577
                $v_result = 0;
4578
            }
4579
            // Next items
4580
            $i++;
4581
            $j++;
4582
        }
4583
        // Look if everything seems to be the same
4584
        if ($v_result) {
4585
            // Skip all the empty items
4586
            while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) { $j++; }
4587
            while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) { $i++; }
4588
            if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
4589
                // There are exactly the same
4590
                $v_result = 2;
4591
            } else if ($i < $v_list_dir_size) {
4592
                // The path is shorter than the dir
4593
                $v_result = 0;
4594
            }
4595
        }
4596
        return $v_result;
4597
    }
4598
  // --------------------------------------------------------------------------------
4599

    
4600
  // --------------------------------------------------------------------------------
4601
  // Function : self::UtilCopyBlock()
4602
  // Description :
4603
  // Parameters :
4604
  //   $p_mode : read/write compression mode
4605
  //             0 : src & dest normal
4606
  //             1 : src gzip, dest normal
4607
  //             2 : src normal, dest gzip
4608
  //             3 : src & dest gzip
4609
  // Return Values :
4610
  // --------------------------------------------------------------------------------
4611
    public static function UtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0)
4612
    {
4613
        $v_result = 1;
4614
        if ($p_mode==0) {
4615
            while ($p_size != 0) {
4616
                $v_read_size = ($p_size < self::READ_BLOCK_SIZE ? $p_size : self::READ_BLOCK_SIZE);
4617
                $v_buffer = @fread($p_src, $v_read_size);
4618
                @fwrite($p_dest, $v_buffer, $v_read_size);
4619
                $p_size -= $v_read_size;
4620
            }
4621
        } else if ($p_mode==1) {
4622
            while ($p_size != 0) {
4623
                $v_read_size = ($p_size < self::READ_BLOCK_SIZE ? $p_size : self::READ_BLOCK_SIZE);
4624
                $v_buffer = @gzread($p_src, $v_read_size);
4625
                @fwrite($p_dest, $v_buffer, $v_read_size);
4626
                $p_size -= $v_read_size;
4627
            }
4628
        } else if ($p_mode==2) {
4629
            while ($p_size != 0) {
4630
                $v_read_size = ($p_size < self::READ_BLOCK_SIZE ? $p_size : self::READ_BLOCK_SIZE);
4631
                $v_buffer = @fread($p_src, $v_read_size);
4632
                @gzwrite($p_dest, $v_buffer, $v_read_size);
4633
                $p_size -= $v_read_size;
4634
            }
4635
        } else if ($p_mode==3) {
4636
            while ($p_size != 0) {
4637
                $v_read_size = ($p_size < self::READ_BLOCK_SIZE ? $p_size : self::READ_BLOCK_SIZE);
4638
                $v_buffer = @gzread($p_src, $v_read_size);
4639
                @gzwrite($p_dest, $v_buffer, $v_read_size);
4640
                $p_size -= $v_read_size;
4641
            }
4642
        }
4643
        return $v_result;
4644
    }
4645
  // --------------------------------------------------------------------------------
4646

    
4647
  // --------------------------------------------------------------------------------
4648
  // Function : self::UtilRename()
4649
  // Description :
4650
  //   This function tries to do a simple rename() function. If it fails, it
4651
  //   tries to copy the $p_src file in a new $p_dest file and then unlink the
4652
  //   first one.
4653
  // Parameters :
4654
  //   $p_src : Old filename
4655
  //   $p_dest : New filename
4656
  // Return Values :
4657
  //   1 on success, 0 on failure.
4658
  // --------------------------------------------------------------------------------
4659
    public static function UtilRename($p_src, $p_dest)
4660
    {
4661
        $v_result = 1;
4662
        // Try to rename the files
4663
        if (!@rename($p_src, $p_dest)) {
4664
            // Try to copy & unlink the src
4665
            if (!@copy($p_src, $p_dest)) {
4666
                $v_result = 0;
4667
            } else if (!@unlink($p_src)) {
4668
                $v_result = 0;
4669
            }
4670
        }
4671
        return $v_result;
4672
    }
4673
  // --------------------------------------------------------------------------------
4674

    
4675
  // --------------------------------------------------------------------------------
4676
  // Function : self::UtilOptionText()
4677
  // Description :
4678
  //   Translate option value in text. Mainly for debug purpose.
4679
  // Parameters :
4680
  //   $p_option : the option value.
4681
  // Return Values :
4682
  //   The option text value.
4683
  // --------------------------------------------------------------------------------
4684
    public static function UtilOptionText($p_option)
4685
    {
4686
        // search the const whitch is defined to $p_option
4687
        $aResult = array_filter(
4688
            self::getClassConstants(),
4689
            function ($val) use ($p_option) { return ($p_option == $val); }
4690
        );
4691
        return ($aResult ? key($aResult) : 'Unknown');
4692
    }
4693
  // --------------------------------------------------------------------------------
4694

    
4695
  // --------------------------------------------------------------------------------
4696
  // Function : self::UtilTranslateWinPath()
4697
  // Description :
4698
  //   Translate windows path by replacing '\' by '/' and optionally removing
4699
  //   drive letter.
4700
  // Parameters :
4701
  //   $p_path : path to translate.
4702
  //   $p_remove_disk_letter : true | false
4703
  // Return Values :
4704
  //   The path translated.
4705
  // --------------------------------------------------------------------------------
4706
    public static function UtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
4707
    {
4708
        if (stristr(php_uname(), 'windows')) {
4709
            // Look for potential disk letter
4710
            if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
4711
                $p_path = substr($p_path, $v_position+1);
4712
            }
4713
            // Change potential windows directory separator
4714
            $p_path = str_replace('\\', '/', $p_path);
4715
//            if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
4716
//                $p_path = strtr($p_path, '\\', '/');
4717
//            }
4718
        }
4719
        return $p_path;
4720
    }
4721
  // --------------------------------------------------------------------------------
4722
} // End of class
4723
  // --------------------------------------------------------------------------------
4724
// end of file
(3-3/4)