PageRenderTime 32ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/administrator/components/com_zoo/framework/helpers/archive.php

https://bitbucket.org/organicdevelopment/joomla-2.5
PHP | 2219 lines | 1524 code | 216 blank | 479 comment | 362 complexity | 9744b13119f7b551d7f7069046e5c0e0 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, MIT, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * @package com_zoo
  4. * @author YOOtheme http://www.yootheme.com
  5. * @copyright Copyright (C) YOOtheme GmbH
  6. * @license http://www.gnu.org/licenses/gpl.html GNU/GPL
  7. */
  8. /**
  9. * Archive Helper class
  10. *
  11. * This class deals with the opening for archive files in tar and zip formats
  12. *
  13. * @package Framework.Helpers
  14. */
  15. class ArchiveHelper extends AppHelper {
  16. /**
  17. * Class Constructor
  18. *
  19. * @param App $app A reference to the global App object
  20. */
  21. public function __construct($app) {
  22. parent::__construct($app);
  23. // increase memory limit
  24. @ini_set('memory_limit', '256M');
  25. }
  26. /**
  27. * Open an archive file
  28. *
  29. * @param string $file The full file path to open
  30. * @param string $format The file format. If not specified, will be guessed by the file extension
  31. *
  32. * @return AppZipArchive|AppTarArchive The archive object (zip or tar)
  33. *
  34. * @since 1.0.0
  35. */
  36. public function open($file, $format = null) {
  37. // auto-detect format
  38. if (!$format) {
  39. $format = $this->format($file);
  40. }
  41. // create archive object
  42. if ($format == 'zip') {
  43. return new AppZipArchive($file);
  44. } elseif ($format == 'tar') {
  45. return new AppTarArchive($file);
  46. }
  47. return null;
  48. }
  49. /**
  50. * Get an archive format based on the file extension
  51. *
  52. * Any tar-related format (tgz, gz, etc) will be returned as tar
  53. *
  54. * @param string $file The filename or the full file path
  55. *
  56. * @return string The file format (zip or tar)
  57. *
  58. * @since 1.0.0
  59. */
  60. public function format($file) {
  61. // detect .zip format
  62. if (preg_match('/\.zip$/i', $file)) {
  63. return 'zip';
  64. }
  65. // detect .tar format
  66. if (preg_match('/\.tar$|\.tar\.gz$|\.tgz$|\.tar\.bz2$|\.tbz2$/i', $file)) {
  67. return 'tar';
  68. }
  69. return null;
  70. }
  71. }
  72. /**
  73. * Class to manage zip archives
  74. *
  75. * @package Framework.Classes
  76. */
  77. class AppZipArchive {
  78. /**
  79. * The ZipArchive class that deals with the zip file
  80. *
  81. * @var ZipArchive
  82. * @since 1.0.0
  83. */
  84. public $zip;
  85. /**
  86. * Class Constructor
  87. *
  88. * @param string $file The file to open
  89. *
  90. * @since 1.0.0
  91. */
  92. public function __construct($file) {
  93. $this->zip = new ZipArchive();
  94. $this->zip->open($file);
  95. }
  96. /**
  97. * Add a file to the archive
  98. *
  99. * @param string $file The file to add
  100. *
  101. * @since 1.0.0
  102. */
  103. public function add($file) {
  104. $this->zip->addFile($file);
  105. }
  106. /**
  107. * Extract the archive into a specific directory
  108. *
  109. * @param string $path The directory in which to extract the file
  110. * @param string|array $files The file(s) to extract from the archive. If empty, it will extract the entire archive content
  111. *
  112. * @return boolean If the operation was successful
  113. */
  114. public function extract($path, $files = array()) {
  115. return empty($files) ? $this->zip->extractTo($path) : $this->zip->extractTo($path, $files);
  116. }
  117. }
  118. /**
  119. * Class to manage Tar-based archives
  120. *
  121. * @package Framework.Classes
  122. */
  123. class AppTarArchive {
  124. /**
  125. * The Archive_Tar object that will manage the archive
  126. *
  127. * @var Archive_Tar
  128. * @since 1.0.0
  129. */
  130. public $tar;
  131. /**
  132. * Class Constructor
  133. *
  134. * @param string $file The full file path of the archive
  135. *
  136. * @since 1.0.0
  137. */
  138. public function __construct($file) {
  139. $this->tar = new Archive_Tar($file);
  140. }
  141. /**
  142. * Add a file to the archive
  143. *
  144. * @param string $file The file to add
  145. *
  146. * @since 1.0.0
  147. */
  148. public function add($file) {
  149. $this->tar->add($file);
  150. }
  151. /**
  152. * Extract the archive into a specific directory
  153. *
  154. * @param string $path The directory in which to extract the file
  155. * @param string|array $files The file(s) to extract from the archive. If empty, it will extract the entire archive content
  156. *
  157. * @return boolean If the operation was successful
  158. */
  159. public function extract($path, $files = array()) {
  160. return empty($files) ? $this->tar->extract($path) : $this->tar->extractList($files, $path);
  161. }
  162. }
  163. /**
  164. * File::CSV
  165. *
  166. * PHP versions 4 and 5
  167. *
  168. * Copyright (c) 1997-2008,
  169. * Vincent Blavet <vincent@phpconcept.net>
  170. * All rights reserved.
  171. *
  172. * Redistribution and use in source and binary forms, with or without
  173. * modification, are permitted provided that the following conditions are met:
  174. *
  175. * * Redistributions of source code must retain the above copyright notice,
  176. * this list of conditions and the following disclaimer.
  177. * * Redistributions in binary form must reproduce the above copyright
  178. * notice, this list of conditions and the following disclaimer in the
  179. * documentation and/or other materials provided with the distribution.
  180. *
  181. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  182. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  183. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  184. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  185. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  186. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  187. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  188. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  189. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  190. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  191. *
  192. *
  193. * @package Framework.Classes
  194. * @author Vincent Blavet <vincent@phpconcept.net>
  195. * @copyright 1997-2008 The Authors
  196. * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
  197. * @version CVS: $Id: system.tar.inc,v 1.5 2010/02/09 12:29:39 dries Exp $
  198. * @link http://pear.php.net/package/Archive_Tar
  199. */
  200. define('ARCHIVE_TAR_ATT_SEPARATOR', 90001);
  201. define('ARCHIVE_TAR_END_BLOCK', pack("a512", ''));
  202. /**
  203. * Creates a (compressed) Tar archive
  204. *
  205. * @author Vincent Blavet <vincent@phpconcept.net>
  206. * @version $Revision: 1.5 $
  207. * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
  208. * @package Framework.Classes
  209. */
  210. class Archive_Tar
  211. {
  212. /**
  213. * Name of the Tar
  214. *
  215. * @var string
  216. */
  217. var $_tarname='';
  218. /**
  219. * if true, the Tar file will be gzipped
  220. *
  221. * @var boolean
  222. */
  223. var $_compress=false;
  224. /**
  225. * Type of compression : 'none', 'gz' or 'bz2'
  226. *
  227. * @var string
  228. */
  229. var $_compress_type='none';
  230. /**
  231. * Explode separator
  232. *
  233. * @var string
  234. */
  235. var $_separator=' ';
  236. /**
  237. * Descriptor
  238. *
  239. * @var file
  240. */
  241. var $_file=0;
  242. /**
  243. * Local Tar name of a remote Tar (http:// or ftp://)
  244. * @var string
  245. */
  246. var $_temp_tarname='';
  247. /**
  248. * Archive_Tar Class constructor. This flavour of the constructor only
  249. * declare a new Archive_Tar object, identifying it by the name of the
  250. * tar file.
  251. * If the compress argument is set the tar will be read or created as a
  252. * gzip or bz2 compressed TAR file.
  253. *
  254. * @param string $p_tarname The name of the tar archive to create
  255. * @param string $p_compress can be null, 'gz' or 'bz2'. This
  256. * parameter indicates if gzip or bz2 compression
  257. * is required. For compatibility reason the
  258. * boolean value 'true' means 'gz'.
  259. * @access public
  260. */
  261. function __construct($p_tarname, $p_compress = null)
  262. {
  263. $this->_compress = false;
  264. $this->_compress_type = 'none';
  265. if (($p_compress === null) || ($p_compress == '')) {
  266. if (@file_exists($p_tarname)) {
  267. if ($fp = @fopen($p_tarname, "rb")) {
  268. // look for gzip magic cookie
  269. $data = fread($fp, 2);
  270. fclose($fp);
  271. if ($data == "\37\213") {
  272. $this->_compress = true;
  273. $this->_compress_type = 'gz';
  274. // No sure it's enought for a magic code ....
  275. } elseif ($data == "BZ") {
  276. $this->_compress = true;
  277. $this->_compress_type = 'bz2';
  278. }
  279. }
  280. } else {
  281. // probably a remote file or some file accessible
  282. // through a stream interface
  283. if (substr($p_tarname, -2) == 'gz') {
  284. $this->_compress = true;
  285. $this->_compress_type = 'gz';
  286. } elseif ((substr($p_tarname, -3) == 'bz2') ||
  287. (substr($p_tarname, -2) == 'bz')) {
  288. $this->_compress = true;
  289. $this->_compress_type = 'bz2';
  290. }
  291. }
  292. } else {
  293. if (($p_compress === true) || ($p_compress == 'gz')) {
  294. $this->_compress = true;
  295. $this->_compress_type = 'gz';
  296. } else if ($p_compress == 'bz2') {
  297. $this->_compress = true;
  298. $this->_compress_type = 'bz2';
  299. } else {
  300. die("Unsupported compression type '$p_compress'\n".
  301. "Supported types are 'gz' and 'bz2'.\n");
  302. return false;
  303. }
  304. }
  305. $this->_tarname = $p_tarname;
  306. if ($this->_compress) { // assert zlib or bz2 extension support
  307. if ($this->_compress_type == 'gz')
  308. $extname = 'zlib';
  309. else if ($this->_compress_type == 'bz2')
  310. $extname = 'bz2';
  311. if (!extension_loaded($extname)) {
  312. $this->loadExtension($extname);
  313. }
  314. if (!extension_loaded($extname)) {
  315. die("The extension '$extname' couldn't be found.\n".
  316. "Make sure your version of PHP was built ".
  317. "with '$extname' support.\n");
  318. return false;
  319. }
  320. }
  321. }
  322. // }}}
  323. /**
  324. * OS independant PHP extension load. Remember to take care
  325. * on the correct extension name for case sensitive OSes.
  326. *
  327. * @param string $ext The extension name
  328. * @return bool Success or not on the dl() call
  329. */
  330. function loadExtension($ext)
  331. {
  332. if (!extension_loaded($ext)) {
  333. // if either returns true dl() will produce a FATAL error, stop that
  334. if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
  335. return false;
  336. }
  337. if (OS_WINDOWS) {
  338. $suffix = '.dll';
  339. } elseif (PHP_OS == 'HP-UX') {
  340. $suffix = '.sl';
  341. } elseif (PHP_OS == 'AIX') {
  342. $suffix = '.a';
  343. } elseif (PHP_OS == 'OSX') {
  344. $suffix = '.bundle';
  345. } else {
  346. $suffix = '.so';
  347. }
  348. return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
  349. }
  350. return true;
  351. }
  352. /**
  353. * Destructor
  354. */
  355. function __destruct()
  356. {
  357. $this->_close();
  358. // ----- Look for a local copy to delete
  359. if ($this->_temp_tarname != '')
  360. @unlink($this->_temp_tarname);
  361. }
  362. /**
  363. * This method creates the archive file and add the files / directories
  364. * that are listed in $p_filelist.
  365. * If a file with the same name exist and is writable, it is replaced
  366. * by the new tar.
  367. * The method return false and a PEAR error text.
  368. * The $p_filelist parameter can be an array of string, each string
  369. * representing a filename or a directory name with their path if
  370. * needed. It can also be a single string with names separated by a
  371. * single blank.
  372. * For each directory added in the archive, the files and
  373. * sub-directories are also added.
  374. * See also createModify() method for more details.
  375. *
  376. * @param array $p_filelist An array of filenames and directory names, or a
  377. * single string with names separated by a single
  378. * blank space.
  379. * @return true on success, false on error.
  380. * @see createModify()
  381. * @access public
  382. */
  383. function create($p_filelist)
  384. {
  385. return $this->createModify($p_filelist, '', '');
  386. }
  387. // }}}
  388. // {{{ add()
  389. /**
  390. * This method add the files / directories that are listed in $p_filelist in
  391. * the archive. If the archive does not exist it is created.
  392. * The method return false and a PEAR error text.
  393. * The files and directories listed are only added at the end of the archive,
  394. * even if a file with the same name is already archived.
  395. * See also createModify() method for more details.
  396. *
  397. * @param array $p_filelist An array of filenames and directory names, or a
  398. * single string with names separated by a single
  399. * blank space.
  400. * @return true on success, false on error.
  401. * @see createModify()
  402. * @access public
  403. */
  404. function add($p_filelist)
  405. {
  406. return $this->addModify($p_filelist, '', '');
  407. }
  408. // }}}
  409. /**
  410. * This method extract all the content of the archive in the directory
  411. *
  412. * @param string $p_path The path in which to extract the files
  413. *
  414. * @return boolean If the operation was successfull
  415. *
  416. * @see Archive_Tar::extractModify()
  417. */
  418. function extract($p_path='')
  419. {
  420. return $this->extractModify($p_path, '');
  421. }
  422. // }}}
  423. /**
  424. * Return the content of the archive
  425. *
  426. * @return array The content of the archive
  427. */
  428. function listContent()
  429. {
  430. $v_list_detail = array();
  431. if ($this->_openRead()) {
  432. if (!$this->_extractList('', $v_list_detail, "list", '', '')) {
  433. unset($v_list_detail);
  434. $v_list_detail = 0;
  435. }
  436. $this->_close();
  437. }
  438. return $v_list_detail;
  439. }
  440. // }}}
  441. // {{{ createModify()
  442. /**
  443. * This method creates the archive file and add the files / directories
  444. * that are listed in $p_filelist.
  445. * If the file already exists and is writable, it is replaced by the
  446. * new tar. It is a create and not an add. If the file exists and is
  447. * read-only or is a directory it is not replaced. The method return
  448. * false and a PEAR error text.
  449. * The $p_filelist parameter can be an array of string, each string
  450. * representing a filename or a directory name with their path if
  451. * needed. It can also be a single string with names separated by a
  452. * single blank.
  453. * The path indicated in $p_remove_dir will be removed from the
  454. * memorized path of each file / directory listed when this path
  455. * exists. By default nothing is removed (empty path '')
  456. * The path indicated in $p_add_dir will be added at the beginning of
  457. * the memorized path of each file / directory listed. However it can
  458. * be set to empty ''. The adding of a path is done after the removing
  459. * of path.
  460. * The path add/remove ability enables the user to prepare an archive
  461. * for extraction in a different path than the origin files are.
  462. * See also addModify() method for file adding properties.
  463. *
  464. * @param array $p_filelist An array of filenames and directory names,
  465. * or a single string with names separated by
  466. * a single blank space.
  467. * @param string $p_add_dir A string which contains a path to be added
  468. * to the memorized path of each element in
  469. * the list.
  470. * @param string $p_remove_dir A string which contains a path to be
  471. * removed from the memorized path of each
  472. * element in the list, when relevant.
  473. * @return boolean true on success, false on error.
  474. * @access public
  475. * @see addModify()
  476. */
  477. function createModify($p_filelist, $p_add_dir, $p_remove_dir='')
  478. {
  479. $v_result = true;
  480. if (!$this->_openWrite())
  481. return false;
  482. if ($p_filelist != '') {
  483. if (is_array($p_filelist))
  484. $v_list = $p_filelist;
  485. elseif (is_string($p_filelist))
  486. $v_list = explode($this->_separator, $p_filelist);
  487. else {
  488. $this->_cleanFile();
  489. $this->_error('Invalid file list');
  490. return false;
  491. }
  492. $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir);
  493. }
  494. if ($v_result) {
  495. $this->_writeFooter();
  496. $this->_close();
  497. } else
  498. $this->_cleanFile();
  499. return $v_result;
  500. }
  501. // }}}
  502. // {{{ addModify()
  503. /**
  504. * This method add the files / directories listed in $p_filelist at the
  505. * end of the existing archive. If the archive does not yet exists it
  506. * is created.
  507. * The $p_filelist parameter can be an array of string, each string
  508. * representing a filename or a directory name with their path if
  509. * needed. It can also be a single string with names separated by a
  510. * single blank.
  511. * The path indicated in $p_remove_dir will be removed from the
  512. * memorized path of each file / directory listed when this path
  513. * exists. By default nothing is removed (empty path '')
  514. * The path indicated in $p_add_dir will be added at the beginning of
  515. * the memorized path of each file / directory listed. However it can
  516. * be set to empty ''. The adding of a path is done after the removing
  517. * of path.
  518. * The path add/remove ability enables the user to prepare an archive
  519. * for extraction in a different path than the origin files are.
  520. * If a file/dir is already in the archive it will only be added at the
  521. * end of the archive. There is no update of the existing archived
  522. * file/dir. However while extracting the archive, the last file will
  523. * replace the first one. This results in a none optimization of the
  524. * archive size.
  525. * If a file/dir does not exist the file/dir is ignored. However an
  526. * error text is send to PEAR error.
  527. * If a file/dir is not readable the file/dir is ignored. However an
  528. * error text is send to PEAR error.
  529. *
  530. * @param array $p_filelist An array of filenames and directory
  531. * names, or a single string with names
  532. * separated by a single blank space.
  533. * @param string $p_add_dir A string which contains a path to be
  534. * added to the memorized path of each
  535. * element in the list.
  536. * @param string $p_remove_dir A string which contains a path to be
  537. * removed from the memorized path of
  538. * each element in the list, when
  539. * relevant.
  540. * @return true on success, false on error.
  541. * @access public
  542. */
  543. function addModify($p_filelist, $p_add_dir, $p_remove_dir='')
  544. {
  545. $v_result = true;
  546. if (!$this->_isArchive())
  547. $v_result = $this->createModify($p_filelist, $p_add_dir,
  548. $p_remove_dir);
  549. else {
  550. if (is_array($p_filelist))
  551. $v_list = $p_filelist;
  552. elseif (is_string($p_filelist))
  553. $v_list = explode($this->_separator, $p_filelist);
  554. else {
  555. $this->_error('Invalid file list');
  556. return false;
  557. }
  558. $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir);
  559. }
  560. return $v_result;
  561. }
  562. // }}}
  563. // {{{ addString()
  564. /**
  565. * This method add a single string as a file at the
  566. * end of the existing archive. If the archive does not yet exists it
  567. * is created.
  568. *
  569. * @param string $p_filename A string which contains the full
  570. * filename path that will be associated
  571. * with the string.
  572. * @param string $p_string The content of the file added in
  573. * the archive.
  574. * @return true on success, false on error.
  575. * @access public
  576. */
  577. function addString($p_filename, $p_string)
  578. {
  579. $v_result = true;
  580. if (!$this->_isArchive()) {
  581. if (!$this->_openWrite()) {
  582. return false;
  583. }
  584. $this->_close();
  585. }
  586. if (!$this->_openAppend())
  587. return false;
  588. // Need to check the get back to the temporary file ? ....
  589. $v_result = $this->_addString($p_filename, $p_string);
  590. $this->_writeFooter();
  591. $this->_close();
  592. return $v_result;
  593. }
  594. // }}}
  595. // {{{ extractModify()
  596. /**
  597. * This method extract all the content of the archive in the directory
  598. * indicated by $p_path. When relevant the memorized path of the
  599. * files/dir can be modified by removing the $p_remove_path path at the
  600. * beginning of the file/dir path.
  601. * While extracting a file, if the directory path does not exists it is
  602. * created.
  603. * While extracting a file, if the file already exists it is replaced
  604. * without looking for last modification date.
  605. * While extracting a file, if the file already exists and is write
  606. * protected, the extraction is aborted.
  607. * While extracting a file, if a directory with the same name already
  608. * exists, the extraction is aborted.
  609. * While extracting a directory, if a file with the same name already
  610. * exists, the extraction is aborted.
  611. * While extracting a file/directory if the destination directory exist
  612. * and is write protected, or does not exist but can not be created,
  613. * the extraction is aborted.
  614. * If after extraction an extracted file does not show the correct
  615. * stored file size, the extraction is aborted.
  616. * When the extraction is aborted, a PEAR error text is set and false
  617. * is returned. However the result can be a partial extraction that may
  618. * need to be manually cleaned.
  619. *
  620. * @param string $p_path The path of the directory where the
  621. * files/dir need to by extracted.
  622. * @param string $p_remove_path Part of the memorized path that can be
  623. * removed if present at the beginning of
  624. * the file/dir path.
  625. * @return boolean true on success, false on error.
  626. * @access public
  627. * @see extractList()
  628. */
  629. function extractModify($p_path, $p_remove_path)
  630. {
  631. $v_result = true;
  632. $v_list_detail = array();
  633. if ($v_result = $this->_openRead()) {
  634. $v_result = $this->_extractList($p_path, $v_list_detail,
  635. "complete", 0, $p_remove_path);
  636. $this->_close();
  637. }
  638. return $v_result;
  639. }
  640. // }}}
  641. // {{{ extractInString()
  642. /**
  643. * This method extract from the archive one file identified by $p_filename.
  644. * The return value is a string with the file content, or NULL on error.
  645. * @param string $p_filename The path of the file to extract in a string.
  646. * @return a string with the file content or NULL.
  647. * @access public
  648. */
  649. function extractInString($p_filename)
  650. {
  651. if ($this->_openRead()) {
  652. $v_result = $this->_extractInString($p_filename);
  653. $this->_close();
  654. } else {
  655. $v_result = NULL;
  656. }
  657. return $v_result;
  658. }
  659. // }}}
  660. // {{{ extractList()
  661. /**
  662. * This method extract from the archive only the files indicated in the
  663. * $p_filelist. These files are extracted in the current directory or
  664. * in the directory indicated by the optional $p_path parameter.
  665. * If indicated the $p_remove_path can be used in the same way as it is
  666. * used in extractModify() method.
  667. * @param array $p_filelist An array of filenames and directory names,
  668. * or a single string with names separated
  669. * by a single blank space.
  670. * @param string $p_path The path of the directory where the
  671. * files/dir need to by extracted.
  672. * @param string $p_remove_path Part of the memorized path that can be
  673. * removed if present at the beginning of
  674. * the file/dir path.
  675. * @return true on success, false on error.
  676. * @access public
  677. * @see extractModify()
  678. */
  679. function extractList($p_filelist, $p_path='', $p_remove_path='')
  680. {
  681. $v_result = true;
  682. $v_list_detail = array();
  683. if (is_array($p_filelist))
  684. $v_list = $p_filelist;
  685. elseif (is_string($p_filelist))
  686. $v_list = explode($this->_separator, $p_filelist);
  687. else {
  688. $this->_error('Invalid string list');
  689. return false;
  690. }
  691. if ($v_result = $this->_openRead()) {
  692. $v_result = $this->_extractList($p_path, $v_list_detail, "partial",
  693. $v_list, $p_remove_path);
  694. $this->_close();
  695. }
  696. return $v_result;
  697. }
  698. // }}}
  699. // {{{ setAttribute()
  700. /**
  701. * This method set specific attributes of the archive. It uses a variable
  702. * list of parameters, in the format attribute code + attribute values :
  703. * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ',');
  704. *
  705. * @return true on success, false on error.
  706. * @access public
  707. */
  708. function setAttribute()
  709. {
  710. $v_result = true;
  711. // ----- Get the number of variable list of arguments
  712. if (($v_size = func_num_args()) == 0) {
  713. return true;
  714. }
  715. // ----- Get the arguments
  716. $v_att_list = &func_get_args();
  717. // ----- Read the attributes
  718. $i=0;
  719. while ($i<$v_size) {
  720. // ----- Look for next option
  721. switch ($v_att_list[$i]) {
  722. // ----- Look for options that request a string value
  723. case ARCHIVE_TAR_ATT_SEPARATOR :
  724. // ----- Check the number of parameters
  725. if (($i+1) >= $v_size) {
  726. $this->_error('Invalid number of parameters for '
  727. .'attribute ARCHIVE_TAR_ATT_SEPARATOR');
  728. return false;
  729. }
  730. // ----- Get the value
  731. $this->_separator = $v_att_list[$i+1];
  732. $i++;
  733. break;
  734. default :
  735. $this->_error('Unknow attribute code '.$v_att_list[$i].'');
  736. return false;
  737. }
  738. // ----- Next attribute
  739. $i++;
  740. }
  741. return $v_result;
  742. }
  743. // }}}
  744. /**
  745. * Throw an exception
  746. *
  747. * @param string $p_message The error string
  748. *
  749. * @throws Exception
  750. */
  751. function _error($p_message)
  752. {
  753. // ----- To be completed
  754. throw new Exception($p_message);
  755. }
  756. // }}}
  757. /**
  758. * Throw an exception
  759. *
  760. * @param string $p_message The error string
  761. *
  762. * @throws Exception
  763. */
  764. function _warning($p_message)
  765. {
  766. // ----- To be completed
  767. throw new Exception($p_message);
  768. }
  769. // }}}
  770. /**
  771. * Check if the file is an archive
  772. *
  773. * @param string $p_filename The file to check
  774. *
  775. * @return boolean If the file is an archive
  776. */
  777. function _isArchive($p_filename=NULL)
  778. {
  779. if ($p_filename == NULL) {
  780. $p_filename = $this->_tarname;
  781. }
  782. clearstatcache();
  783. return @is_file($p_filename) && !@is_link($p_filename);
  784. }
  785. // }}}
  786. /**
  787. * Opens a file for writing
  788. *
  789. * @return boolean True on success
  790. */
  791. function _openWrite()
  792. {
  793. if ($this->_compress_type == 'gz')
  794. $this->_file = @gzopen($this->_tarname, "wb9");
  795. else if ($this->_compress_type == 'bz2')
  796. $this->_file = @bzopen($this->_tarname, "w");
  797. else if ($this->_compress_type == 'none')
  798. $this->_file = @fopen($this->_tarname, "wb");
  799. else
  800. $this->_error('Unknown or missing compression type ('
  801. .$this->_compress_type.')');
  802. if ($this->_file == 0) {
  803. $this->_error('Unable to open in write mode \''
  804. .$this->_tarname.'\'');
  805. return false;
  806. }
  807. return true;
  808. }
  809. // }}}
  810. /**
  811. * Open a file for reading
  812. *
  813. * @return boolean True on success
  814. */
  815. function _openRead()
  816. {
  817. if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') {
  818. // ----- Look if a local copy need to be done
  819. if ($this->_temp_tarname == '') {
  820. $this->_temp_tarname = uniqid('tar').'.tmp';
  821. if (!$v_file_from = @fopen($this->_tarname, 'rb')) {
  822. $this->_error('Unable to open in read mode \''
  823. .$this->_tarname.'\'');
  824. $this->_temp_tarname = '';
  825. return false;
  826. }
  827. if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) {
  828. $this->_error('Unable to open in write mode \''
  829. .$this->_temp_tarname.'\'');
  830. $this->_temp_tarname = '';
  831. return false;
  832. }
  833. while ($v_data = @fread($v_file_from, 1024))
  834. @fwrite($v_file_to, $v_data);
  835. @fclose($v_file_from);
  836. @fclose($v_file_to);
  837. }
  838. // ----- File to open if the local copy
  839. $v_filename = $this->_temp_tarname;
  840. } else
  841. // ----- File to open if the normal Tar file
  842. $v_filename = $this->_tarname;
  843. if ($this->_compress_type == 'gz')
  844. $this->_file = @gzopen($v_filename, "rb");
  845. else if ($this->_compress_type == 'bz2')
  846. $this->_file = @bzopen($v_filename, "r");
  847. else if ($this->_compress_type == 'none')
  848. $this->_file = @fopen($v_filename, "rb");
  849. else
  850. $this->_error('Unknown or missing compression type ('
  851. .$this->_compress_type.')');
  852. if ($this->_file == 0) {
  853. $this->_error('Unable to open in read mode \''.$v_filename.'\'');
  854. return false;
  855. }
  856. return true;
  857. }
  858. // }}}
  859. /**
  860. * Open a file for reading and writing
  861. *
  862. * @return boolean true on success
  863. */
  864. function _openReadWrite()
  865. {
  866. if ($this->_compress_type == 'gz')
  867. $this->_file = @gzopen($this->_tarname, "r+b");
  868. else if ($this->_compress_type == 'bz2') {
  869. $this->_error('Unable to open bz2 in read/write mode \''
  870. .$this->_tarname.'\' (limitation of bz2 extension)');
  871. return false;
  872. } else if ($this->_compress_type == 'none')
  873. $this->_file = @fopen($this->_tarname, "r+b");
  874. else
  875. $this->_error('Unknown or missing compression type ('
  876. .$this->_compress_type.')');
  877. if ($this->_file == 0) {
  878. $this->_error('Unable to open in read/write mode \''
  879. .$this->_tarname.'\'');
  880. return false;
  881. }
  882. return true;
  883. }
  884. // }}}
  885. /**
  886. * Close a file handler
  887. */
  888. function _close()
  889. {
  890. //if (isset($this->_file)) {
  891. if (is_resource($this->_file)) {
  892. if ($this->_compress_type == 'gz')
  893. @gzclose($this->_file);
  894. else if ($this->_compress_type == 'bz2')
  895. @bzclose($this->_file);
  896. else if ($this->_compress_type == 'none')
  897. @fclose($this->_file);
  898. else
  899. $this->_error('Unknown or missing compression type ('
  900. .$this->_compress_type.')');
  901. $this->_file = 0;
  902. }
  903. // ----- Look if a local copy need to be erase
  904. // Note that it might be interesting to keep the url for a time : ToDo
  905. if ($this->_temp_tarname != '') {
  906. @unlink($this->_temp_tarname);
  907. $this->_temp_tarname = '';
  908. }
  909. return true;
  910. }
  911. // }}}
  912. /**
  913. * Close the file handler and cleans the local vars
  914. *
  915. * @return boolean true on success
  916. */
  917. function _cleanFile()
  918. {
  919. $this->_close();
  920. // ----- Look for a local copy
  921. if ($this->_temp_tarname != '') {
  922. // ----- Remove the local copy but not the remote tarname
  923. @unlink($this->_temp_tarname);
  924. $this->_temp_tarname = '';
  925. } else {
  926. // ----- Remove the local tarname file
  927. @unlink($this->_tarname);
  928. }
  929. $this->_tarname = '';
  930. return true;
  931. }
  932. // }}}
  933. /**
  934. * Write a block of data
  935. *
  936. * @param mixed $p_binary_data The data to write
  937. * @param int $p_len The length of the data to write
  938. *
  939. * @return boolean true on success
  940. */
  941. function _writeBlock($p_binary_data, $p_len=null)
  942. {
  943. if (is_resource($this->_file)) {
  944. if ($p_len === null) {
  945. if ($this->_compress_type == 'gz')
  946. @gzputs($this->_file, $p_binary_data);
  947. else if ($this->_compress_type == 'bz2')
  948. @bzwrite($this->_file, $p_binary_data);
  949. else if ($this->_compress_type == 'none')
  950. @fputs($this->_file, $p_binary_data);
  951. else
  952. $this->_error('Unknown or missing compression type ('
  953. .$this->_compress_type.')');
  954. } else {
  955. if ($this->_compress_type == 'gz')
  956. @gzputs($this->_file, $p_binary_data, $p_len);
  957. else if ($this->_compress_type == 'bz2')
  958. @bzwrite($this->_file, $p_binary_data, $p_len);
  959. else if ($this->_compress_type == 'none')
  960. @fputs($this->_file, $p_binary_data, $p_len);
  961. else
  962. $this->_error('Unknown or missing compression type ('
  963. .$this->_compress_type.')');
  964. }
  965. }
  966. return true;
  967. }
  968. // }}}
  969. /**
  970. * Read a block of data
  971. *
  972. * @return mixed The data read
  973. */
  974. function _readBlock()
  975. {
  976. $v_block = null;
  977. if (is_resource($this->_file)) {
  978. if ($this->_compress_type == 'gz')
  979. $v_block = @gzread($this->_file, 512);
  980. else if ($this->_compress_type == 'bz2')
  981. $v_block = @bzread($this->_file, 512);
  982. else if ($this->_compress_type == 'none')
  983. $v_block = @fread($this->_file, 512);
  984. else
  985. $this->_error('Unknown or missing compression type ('
  986. .$this->_compress_type.')');
  987. }
  988. return $v_block;
  989. }
  990. // }}}
  991. /**
  992. * Jump to a block of data
  993. *
  994. * @param int $p_len The position to jump to
  995. *
  996. * @return boolean True on success
  997. */
  998. function _jumpBlock($p_len=null)
  999. {
  1000. if (is_resource($this->_file)) {
  1001. if ($p_len === null)
  1002. $p_len = 1;
  1003. if ($this->_compress_type == 'gz') {
  1004. @gzseek($this->_file, gztell($this->_file)+($p_len*512));
  1005. }
  1006. else if ($this->_compress_type == 'bz2') {
  1007. // ----- Replace missing bztell() and bzseek()
  1008. for ($i=0; $i<$p_len; $i++)
  1009. $this->_readBlock();
  1010. } else if ($this->_compress_type == 'none')
  1011. @fseek($this->_file, ftell($this->_file)+($p_len*512));
  1012. else
  1013. $this->_error('Unknown or missing compression type ('
  1014. .$this->_compress_type.')');
  1015. }
  1016. return true;
  1017. }
  1018. // }}}
  1019. /**
  1020. * Write the end of the file
  1021. *
  1022. * @return boolean true on success
  1023. */
  1024. function _writeFooter()
  1025. {
  1026. if (is_resource($this->_file)) {
  1027. // ----- Write the last 0 filled block for end of archive
  1028. $v_binary_data = pack('a1024', '');
  1029. $this->_writeBlock($v_binary_data);
  1030. }
  1031. return true;
  1032. }
  1033. // }}}
  1034. /**
  1035. * Add a list of resources
  1036. *
  1037. * @param array $p_list The list of files to add
  1038. * @param string $p_add_dir The directory to add the files to
  1039. * @param string $p_remove_dir A directory to remove from the file path
  1040. *
  1041. * @return boolean True on success
  1042. */
  1043. function _addList($p_list, $p_add_dir, $p_remove_dir)
  1044. {
  1045. $v_result=true;
  1046. $v_header = array();
  1047. // ----- Remove potential windows directory separator
  1048. $p_add_dir = $this->_translateWinPath($p_add_dir);
  1049. $p_remove_dir = $this->_translateWinPath($p_remove_dir, false);
  1050. if (!$this->_file) {
  1051. $this->_error('Invalid file descriptor');
  1052. return false;
  1053. }
  1054. if (sizeof($p_list) == 0)
  1055. return true;
  1056. foreach ($p_list as $v_filename) {
  1057. if (!$v_result) {
  1058. break;
  1059. }
  1060. // ----- Skip the current tar name
  1061. if ($v_filename == $this->_tarname)
  1062. continue;
  1063. if ($v_filename == '')
  1064. continue;
  1065. if (!file_exists($v_filename)) {
  1066. $this->_warning("File '$v_filename' does not exist");
  1067. continue;
  1068. }
  1069. // ----- Add the file or directory header
  1070. if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir))
  1071. return false;
  1072. if (@is_dir($v_filename) && !@is_link($v_filename)) {
  1073. if (!($p_hdir = opendir($v_filename))) {
  1074. $this->_warning("Directory '$v_filename' can not be read");
  1075. continue;
  1076. }
  1077. while (false !== ($p_hitem = readdir($p_hdir))) {
  1078. if (($p_hitem != '.') && ($p_hitem != '..')) {
  1079. if ($v_filename != ".")
  1080. $p_temp_list[0] = $v_filename.'/'.$p_hitem;
  1081. else
  1082. $p_temp_list[0] = $p_hitem;
  1083. $v_result = $this->_addList($p_temp_list,
  1084. $p_add_dir,
  1085. $p_remove_dir);
  1086. }
  1087. }
  1088. unset($p_temp_list);
  1089. unset($p_hdir);
  1090. unset($p_hitem);
  1091. }
  1092. }
  1093. return $v_result;
  1094. }
  1095. // }}}
  1096. /**
  1097. * Add a file
  1098. *
  1099. * @param string $p_filename The file to add
  1100. * @param string $p_header Header
  1101. * @param string $p_add_dir The directory to add the files to
  1102. * @param string $p_remove_dir A directory to remove from the file path
  1103. *
  1104. * @return boolean True on success
  1105. */
  1106. function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir)
  1107. {
  1108. if (!$this->_file) {
  1109. $this->_error('Invalid file descriptor');
  1110. return false;
  1111. }
  1112. if ($p_filename == '') {
  1113. $this->_error('Invalid file name');
  1114. return false;
  1115. }
  1116. // ----- Calculate the stored filename
  1117. $p_filename = $this->_translateWinPath($p_filename, false);
  1118. $v_stored_filename = $p_filename;
  1119. if (strcmp($p_filename, $p_remove_dir) == 0) {
  1120. return true;
  1121. }
  1122. if ($p_remove_dir != '') {
  1123. if (substr($p_remove_dir, -1) != '/')
  1124. $p_remove_dir .= '/';
  1125. if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir)
  1126. $v_stored_filename = substr($p_filename, strlen($p_remove_dir));
  1127. }
  1128. $v_stored_filename = $this->_translateWinPath($v_stored_filename);
  1129. if ($p_add_dir != '') {
  1130. if (substr($p_add_dir, -1) == '/')
  1131. $v_stored_filename = $p_add_dir.$v_stored_filename;
  1132. else
  1133. $v_stored_filename = $p_add_dir.'/'.$v_stored_filename;
  1134. }
  1135. $v_stored_filename = $this->_pathReduction($v_stored_filename);
  1136. if ($this->_isArchive($p_filename)) {
  1137. if (($v_file = @fopen($p_filename, "rb")) == 0) {
  1138. $this->_warning("Unable to open file '".$p_filename
  1139. ."' in binary read mode");
  1140. return true;
  1141. }
  1142. if (!$this->_writeHeader($p_filename, $v_stored_filename))
  1143. return false;
  1144. while (($v_buffer = fread($v_file, 512)) != '') {
  1145. $v_binary_data = pack("a512", "$v_buffer");
  1146. $this->_writeBlock($v_binary_data);
  1147. }
  1148. fclose($v_file);
  1149. } else {
  1150. // ----- Only header for dir
  1151. if (!$this->_writeHeader($p_filename, $v_stored_filename))
  1152. return false;
  1153. }
  1154. return true;
  1155. }
  1156. // }}}
  1157. /**
  1158. * Add a string to a file
  1159. *
  1160. * @param string $p_filename The file
  1161. * @param string $p_string The string
  1162. *
  1163. * @return boolean true on success
  1164. */
  1165. function _addString($p_filename, $p_string)
  1166. {
  1167. if (!$this->_file) {
  1168. $this->_error('Invalid file descriptor');
  1169. return false;
  1170. }
  1171. if ($p_filename == '') {
  1172. $this->_error('Invalid file name');
  1173. return false;
  1174. }
  1175. // ----- Calculate the stored filename
  1176. $p_filename = $this->_translateWinPath($p_filename, false);
  1177. if (!$this->_writeHeaderBlock($p_filename, strlen($p_string),
  1178. time(), 384, "", 0, 0))
  1179. return false;
  1180. $i=0;
  1181. while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') {
  1182. $v_binary_data = pack("a512", $v_buffer);
  1183. $this->_writeBlock($v_binary_data);
  1184. }
  1185. return true;
  1186. }
  1187. // }}}
  1188. /**
  1189. * Write an header to a file
  1190. *
  1191. * @param string $p_filename The file
  1192. * @param string $p_stored_filename The stored file
  1193. */
  1194. function _writeHeader($p_filename, $p_stored_filename)
  1195. {
  1196. if ($p_stored_filename == '')
  1197. $p_stored_filename = $p_filename;
  1198. $v_reduce_filename = $this->_pathReduction($p_stored_filename);
  1199. if (strlen($v_reduce_filename) > 99) {
  1200. if (!$this->_writeLongHeader($v_reduce_filename))
  1201. return false;
  1202. }
  1203. $v_info = lstat($p_filename);
  1204. $v_uid = sprintf("%6s ", DecOct($v_info[4]));
  1205. $v_gid = sprintf("%6s ", DecOct($v_info[5]));
  1206. $v_perms = sprintf("%6s ", DecOct($v_info['mode']));
  1207. $v_mtime = sprintf("%11s", DecOct($v_info['mode']));
  1208. $v_linkname = '';
  1209. if (@is_link($p_filename)) {
  1210. $v_typeflag = '2';
  1211. $v_linkname = readlink($p_filename);
  1212. $v_size = sprintf("%11s ", DecOct(0));
  1213. } elseif (@is_dir($p_filename)) {
  1214. $v_typeflag = "5";
  1215. $v_size = sprintf("%11s ", DecOct(0));
  1216. } else {
  1217. $v_typeflag = '';
  1218. clearstatcache();
  1219. $v_size = sprintf("%11s ", DecOct($v_info['size']));
  1220. }
  1221. $v_magic = '';
  1222. $v_version = '';
  1223. $v_uname = '';
  1224. $v_gname = '';
  1225. $v_devmajor = '';
  1226. $v_devminor = '';
  1227. $v_prefix = '';
  1228. $v_binary_data_first = pack("a100a8a8a8a12A12",
  1229. $v_reduce_filename, $v_perms, $v_uid,
  1230. $v_gid, $v_size, $v_mtime);
  1231. $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
  1232. $v_typeflag, $v_linkname, $v_magic,
  1233. $v_version, $v_uname, $v_gname,
  1234. $v_devmajor, $v_devminor, $v_prefix, '');
  1235. // ----- Calculate the checksum
  1236. $v_checksum = 0;
  1237. // ..... First part of the header
  1238. for ($i=0; $i<148; $i++)
  1239. $v_checksum += ord(substr($v_binary_data_first,$i,1));
  1240. // ..... Ignore the checksum value and replace it by ' ' (space)
  1241. for ($i=148; $i<156; $i++)
  1242. $v_checksum += ord(' ');
  1243. // ..... Last part of the header
  1244. for ($i=156, $j=0; $i<512; $i++, $j++)
  1245. $v_checksum += ord(substr($v_binary_data_last,$j,1));
  1246. // ----- Write the first 148 bytes of the header in the archive
  1247. $this->_writeBlock($v_binary_data_first, 148);
  1248. // ----- Write the calculated checksum
  1249. $v_checksum = sprintf("%6s ", DecOct($v_checksum));
  1250. $v_binary_data = pack("a8", $v_checksum);
  1251. $this->_writeBlock($v_binary_data, 8);
  1252. // ----- Write the last 356 bytes of the header in the archive
  1253. $this->_writeBlock($v_binary_data_last, 356);
  1254. return true;
  1255. }
  1256. // }}}
  1257. /**
  1258. * Write an header block
  1259. *
  1260. * @param string $p_filename The file
  1261. * @param int $p_size The size
  1262. * @param int $p_mtime The mtime
  1263. * @param string $p_perms The permissions
  1264. * @param string $p_type The type of the file
  1265. * @param int $p_uid The uid
  1266. * @param int $p_gid the gid
  1267. *
  1268. * @return boolean Ture on succcess
  1269. */
  1270. function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0,
  1271. $p_type='', $p_uid=0, $p_gid=0)
  1272. {
  1273. $p_filename = $this->_pathReduction($p_filename);
  1274. if (strlen($p_filename) > 99) {
  1275. if (!$this->_writeLongHeader($p_filename))
  1276. return false;
  1277. }
  1278. if ($p_type == "5") {
  1279. $v_size = sprintf("%11s ", DecOct(0));
  1280. } else {
  1281. $v_size = sprintf("%11s ", DecOct($p_size));
  1282. }
  1283. $v_uid = sprintf("%6s ", DecOct($p_uid));
  1284. $v_gid = sprintf("%6s ", DecOct($p_gid));
  1285. $v_perms = sprintf("%6s ", DecOct($p_perms));
  1286. $v_mtime = sprintf("%11s", DecOct($p_mtime));
  1287. $v_linkname = '';
  1288. $v_magic = '';
  1289. $v_version = '';
  1290. $v_uname = '';
  1291. $v_gname = '';
  1292. $v_devmajor = '';
  1293. $v_devminor = '';
  1294. $v_prefix = '';
  1295. $v_binary_data_first = pack("a100a8a8a8a12A12",
  1296. $p_filename, $v_perms, $v_uid, $v_gid,
  1297. $v_size, $v_mtime);
  1298. $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
  1299. $p_type, $v_linkname, $v_magic,
  1300. $v_version, $v_uname, $v_gname,
  1301. $v_devmajor, $v_devminor, $v_prefix, '');
  1302. // ----- Calculate the checksum
  1303. $v_checksum = 0;
  1304. // ..... First part of the header
  1305. for ($i=0; $i<148; $i++)
  1306. $v_checksum += ord(substr($v_binary_data_first,$i,1));
  1307. // ..... Ignore the checksum value and replace it by ' ' (space)
  1308. for ($i=148; $i<156; $i++)
  1309. $v_checksum += ord(' ');
  1310. // ..... Last part of the header
  1311. for ($i=156, $j=0; $i<512; $i++, $j++)
  1312. $v_checksum += ord(substr($v_binary_data_last,$j,1));
  1313. // ----- Write the first 148 bytes of the header in the archive
  1314. $this->_writeBlock($v_binary_data_first, 148);
  1315. // ----- Write the calculated checksum
  1316. $v_checksum = sprintf("%6s ", DecOct($v_checksum));
  1317. $v_binary_data = pack("a8", $v_checksum);
  1318. $this->_writeBlock($v_binary_data, 8);
  1319. // ----- Write the last 356 bytes of the header in the archive
  1320. $this->_writeBlock($v_binary_data_last, 356);
  1321. return true;
  1322. }
  1323. // }}}
  1324. /**
  1325. * Write a long header
  1326. *
  1327. * @param string $p_filename The file
  1328. */
  1329. function _writeLongHeader($p_filename)
  1330. {
  1331. $v_size = sprintf("%11s ", DecOct(strlen($p_filename)));
  1332. $v_typeflag = 'L';
  1333. $v_linkname = '';
  1334. $v_magic = '';
  1335. $v_version = '';
  1336. $v_uname = '';
  1337. $v_gname = '';
  1338. $v_devmajor = '';
  1339. $v_devminor = '';
  1340. $v_prefix = '';
  1341. $v_binary_data_first = pack("a100a8a8a8a12A12",
  1342. '././@LongLink', 0, 0, 0, $v_size, 0);
  1343. $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
  1344. $v_typeflag, $v_linkname, $v_magic,
  1345. $v_version, $v_uname, $v_gname,
  1346. $v_devmajor, $v_devminor, $v_prefix, '');
  1347. // ----- Calculate the checksum
  1348. $v_checksum = 0;
  1349. // ..... First part of the header
  1350. for ($i=0; $i<148; $i++)
  1351. $v_checksum += ord(substr($v_binary_data_first,$i,1));
  1352. // ..... Ignore the checksum value and replace it by ' ' (space)
  1353. for ($i=148; $i<156; $i++)
  1354. $v_checksum += ord(' ');
  1355. // ..... Last part of the header
  1356. for ($i=156, $j=0; $i<512; $i++, $j++)
  1357. $v_checksum += ord(substr($v_binary_data_last,$j,1));
  1358. // ----- Write the first 148 bytes of the header in the archive
  1359. $this->_writeBlock($v_binary_data_first, 148);
  1360. // ----- Write the calculated checksum
  1361. $v_checksum = sprintf("%6s ", DecOct($v_checksum));
  1362. $v_binary_data = pack("a8", $v_checksum);
  1363. $this->_writeBlock($v_binary_data, 8);
  1364. // ----- Write the last 356 bytes of the header in the archive
  1365. $this->_writeBlock($v_binary_data_last, 356);
  1366. // ----- Write the filename as content of the block
  1367. $i=0;
  1368. while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') {
  1369. $v_binary_data = pack("a512", "$v_buffer");
  1370. $this->_writeBlock($v_binary_data);
  1371. }
  1372. return true;
  1373. }
  1374. // }}}
  1375. /**
  1376. * Read an header
  1377. *
  1378. * @param mixed $v_binary_data The data
  1379. * @param mixed $v_header the header
  1380. *
  1381. * @return boolean True on success
  1382. */
  1383. function _readHeader($v_binary_data, &$v_header)
  1384. {
  1385. if (strlen($v_binary_data)==0) {
  1386. $v_header['filename'] = '';
  1387. return true;
  1388. }
  1389. if (strlen($v_binary_data) != 512) {
  1390. $v_header['filename'] = '';
  1391. $this->_error('Invalid block size : '.strlen($v_binary_data));
  1392. return false;
  1393. }
  1394. if (!is_array($v_header)) {
  1395. $v_header = array();
  1396. }
  1397. // ----- Calculate the checksum
  1398. $v_checksum = 0;
  1399. // ..... First part of the header
  1400. for ($i=0; $i<148; $i++)
  1401. $v_checksum+=ord(substr($v_binary_data,$i,1));
  1402. // ..... Ignore the checksum value and replace it by ' ' (space)
  1403. for ($i=148; $i<156; $i++)
  1404. $v_checksum += ord(' ');
  1405. // ..... Last part of the header
  1406. for ($i=156; $i<512; $i++)
  1407. $v_checksum+=ord(substr($v_binary_data,$i,1));
  1408. $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/"
  1409. ."a8checksum/a1typeflag/a100link/a6magic/a2version/"
  1410. ."a32uname/a32gname/a8devmajor/a8devminor",
  1411. $v_binary_data);
  1412. // ----- Extract the checksum
  1413. $v_header['checksum'] = OctDec(trim($v_data['checksum']));
  1414. if ($v_header['checksum'] != $v_checksum) {
  1415. $v_header['filename'] = '';
  1416. // ----- Look for last block (empty block)
  1417. if (($v_checksum == 256) && ($v_header['checksum'] == 0))
  1418. return true;
  1419. $this->_error('Invalid checksum for file "'.$v_data['filename']
  1420. .'" : '.$v_checksum.' calculated, '
  1421. .$v_header['checksum'].' expected');
  1422. return false;
  1423. }
  1424. // ----- Extract the properties
  1425. $v_header['filename'] = trim($v_data['filename']);
  1426. if ($this->_maliciousFilename($v_header['filename'])) {
  1427. $this->_error('Malicious .tar detected, file "' . $v_header['filename'] .
  1428. '" will not install in desired directory tree');
  1429. return false;
  1430. }
  1431. $v_header['mode'] = OctDec(trim($v_data['mode']));
  1432. $v_header['uid'] = OctDec(trim($v_data['uid']));
  1433. $v_header['gid'] = OctDec(trim($v_data['gid']));
  1434. $v_header['size'] = OctDec(trim($v_data['size']));
  1435. $v_header['mtime'] = OctDec(trim($v_data['mtime']));
  1436. if (($v_header['typeflag'] = $v_data['typeflag']) == "5") {
  1437. $v_header['size'] = 0;
  1438. }
  1439. $v_header['link'] = trim($v_data['link']);
  1440. /* ----- All these fields are removed form the header because
  1441. they do not carry interesting info
  1442. $v_header[magic] = trim($v_data[magic]);
  1443. $v_header[version] = trim($v_data[version]);
  1444. $v_header[uname] = trim($v_data[uname]);
  1445. $v_header[gname] = trim($v_data[gname]);
  1446. $v_header[devmajor] = trim($v_data[devmajor]);
  1447. $v_header[devminor] = trim($v_data[devminor]);
  1448. */
  1449. return true;
  1450. }
  1451. // }}}
  1452. // {{{ _maliciousFilename()
  1453. /**
  1454. * Detect and report a malicious file name
  1455. *
  1456. * @param string $file
  1457. * @return boolean
  1458. */
  1459. function _maliciousFilename($file)
  1460. {
  1461. if (strpos($file, '/../') !== false) {
  1462. return true;
  1463. }
  1464. if (strpos($file, '../') === 0) {
  1465. return true;
  1466. }
  1467. return false;
  1468. }
  1469. // }}}
  1470. /**
  1471. * Read a long header
  1472. *
  1473. * @param mixed $v_header The header to read
  1474. *
  1475. * @return boolean true on success
  1476. */
  1477. function _readLongHeader(&$v_header)
  1478. {
  1479. $v_filename = '';
  1480. $n = floor($v_header['size']/512);
  1481. for ($i=0; $i<$n; $i++) {
  1482. $v_content = $this->_readBlock();
  1483. $v_filename .= $v_content;
  1484. }
  1485. if (($v_header['size'] % 512) != 0) {
  1486. $v_content = $this->_readBlock();
  1487. $v_filename .= $v_content;
  1488. }
  1489. // ----- Read the next header
  1490. $v_binary_data = $this->_readBlock();
  1491. if (!$this->_readHeader($v_binary_data, $v_header))
  1492. return false;
  1493. $v_filename = trim($v_filename);
  1494. $v_header['filename'] = $v_filename;
  1495. if ($this->_maliciousFilename($v_filename)) {
  1496. $this->_error('Malicious .tar detected, file "' . $v_filename .
  1497. '" will not install in desired directory tree');
  1498. return false;
  1499. }
  1500. return true;
  1501. }
  1502. // }}}
  1503. // {{{ _extractInString()
  1504. /**
  1505. * This method extract from the archive one file identified by $p_filename.
  1506. * The return value is a string with the file content, or NULL on error.
  1507. *
  1508. * @param string $p_filename The path of the file to extract in a string.
  1509. * @return string a string with the file content or NULL.
  1510. */
  1511. function _extractInString($p_filename)
  1512. {
  1513. $v_result_str = "";
  1514. While (strlen($v_binary_data = $this->_readBlock()) != 0)
  1515. {
  1516. if (!$this->_readHeader($v_binary_data, $v_header))
  1517. return NULL;
  1518. if ($v_header['filename'] == '')
  1519. continue;
  1520. // ----- Look for long filename
  1521. if ($v_header['typeflag'] == 'L') {
  1522. if (!$this->_readLongHeader($v_header))
  1523. return NULL;
  1524. }
  1525. if ($v_header['filename'] == $p_filename) {
  1526. if ($v_header['typeflag'] == "5") {
  1527. $this->_error('Unable to extract in string a directory '
  1528. .'entry {'.$v_header['filename'].'}');
  1529. return NULL;
  1530. } else {
  1531. $n = floor($v_header['size']/512);
  1532. for ($i=0; $i<$n; $i++) {
  1533. $v_result_str .= $this->_readBlock();
  1534. }
  1535. if (($v_header['size'] % 512) != 0) {
  1536. $v_content = $this->_readBlock();
  1537. $v_result_str .= substr($v_content, 0,
  1538. ($v_header['size'] % 512));
  1539. }
  1540. return $v_result_str;
  1541. }
  1542. } else {
  1543. $this->_jumpBlock(ceil(($v_header['size']/512)));
  1544. }
  1545. }
  1546. return NULL;
  1547. }
  1548. // }}}
  1549. /**
  1550. * Extract a list of files
  1551. *
  1552. * @param string $p_path The path
  1553. * @param array $p_list_detail The list detail
  1554. * @param string $p_mode The mode
  1555. * @param array $p_file_list The list of files
  1556. * @param string $p_remove_path The path to remove
  1557. *
  1558. * @return boolean true on success
  1559. *
  1560. */
  1561. function _extractList($p_path, &$p_list_detail, $p_mode,
  1562. $p_file_list, $p_remove_path)
  1563. {
  1564. $v_result=true;
  1565. $v_nb = 0;
  1566. $v_extract_all = true;
  1567. $v_listing = false;
  1568. $p_path = $this->_translateWinPath($p_path, false);
  1569. if ($p_path == '' || (substr($p_path, 0, 1) != '/'
  1570. && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) {
  1571. $p_path = "./".$p_path;
  1572. }
  1573. $p_remove_path = $this->_translateWinPath($p_remove_path);
  1574. // ----- Look for path to remove format (should end by /)
  1575. if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/'))
  1576. $p_remove_path .= '/';
  1577. $p_remove_path_size = strlen($p_remove_path);
  1578. switch ($p_mode) {
  1579. case "complete" :
  1580. $v_extract_all = TRUE;
  1581. $v_listing = FALSE;
  1582. break;
  1583. case "partial" :
  1584. $v_extract_all = FALSE;
  1585. $v_listing = FALSE;
  1586. break;
  1587. case "list" :
  1588. $v_extract_all = FALSE;
  1589. $v_listing = TRUE;
  1590. break;
  1591. default :
  1592. $this->_error('Invalid extract mode ('.$p_mode.')');
  1593. return false;
  1594. }
  1595. clearstatcache();
  1596. while (strlen($v_binary_data = $this->_readBlock()) != 0)
  1597. {
  1598. $v_extract_file = FALSE;
  1599. $v_extraction_stopped = 0;
  1600. if (!$this->_readHeader($v_binary_data, $v_header))
  1601. return false;
  1602. if ($v_header['filename'] == '') {
  1603. continue;
  1604. }
  1605. // ----- Look for long filename
  1606. if ($v_header['typeflag'] == 'L') {
  1607. if (!$this->_readLongHeader($v_header))
  1608. return false;
  1609. }
  1610. if ((!$v_extract_all) && (is_array($p_file_list))) {
  1611. // ----- By default no unzip if the file is not found
  1612. $v_extract_file = false;
  1613. for ($i=0; $i<sizeof($p_file_list); $i++) {
  1614. // ----- Look if it is a directory
  1615. if (substr($p_file_list[$i], -1) == '/') {
  1616. // ----- Look if the directory is in the filename path
  1617. if ((strlen($v_header['filename']) > strlen($p_file_list[$i]))
  1618. && (substr($v_header['filename'], 0, strlen($p_file_list[$i]))
  1619. == $p_file_list[$i])) {
  1620. $v_extract_file = TRUE;
  1621. break;
  1622. }
  1623. }
  1624. // ----- It is a file, so compare the file names
  1625. elseif ($p_file_list[$i] == $v_header['filename']) {
  1626. $v_extract_file = TRUE;
  1627. break;
  1628. }
  1629. }
  1630. } else {
  1631. $v_extract_file = TRUE;
  1632. }
  1633. // ----- Look if this file need to be extracted
  1634. if (($v_extract_file) && (!$v_listing))
  1635. {
  1636. if (($p_remove_path != '')
  1637. && (substr($v_header['filename'], 0, $p_remove_path_size)
  1638. == $p_remove_path))
  1639. $v_header['filename'] = substr($v_header['filename'],
  1640. $p_remove_path_size);
  1641. if (($p_path != './') && ($p_path != '/')) {
  1642. while (substr($p_path, -1) == '/')
  1643. $p_path = substr($p_path, 0, strlen($p_path)-1);
  1644. if (substr($v_header['filename'], 0, 1) == '/')
  1645. $v_header['filename'] = $p_path.$v_header['filename'];
  1646. else
  1647. $v_header['filename'] = $p_path.'/'.$v_header['filename'];
  1648. }
  1649. if (file_exists($v_header['filename'])) {
  1650. if ( (@is_dir($v_header['filename']))
  1651. && ($v_header['typeflag'] == '')) {
  1652. $this->_error('File '.$v_header['filename']
  1653. .' already exists as a directory');
  1654. return false;
  1655. }
  1656. if ( ($this->_isArchive($v_header['filename']))
  1657. && ($v_header['typeflag'] == "5")) {
  1658. $this->_error('Directory '.$v_header['filename']
  1659. .' already exists as a file');
  1660. return false;
  1661. }
  1662. if (!is_writeable($v_header['filename'])) {
  1663. $this->_error('File '.$v_header['filename']
  1664. .' already exists and is write protected');
  1665. return false;
  1666. }
  1667. if (filemtime($v_header['filename']) > $v_header['mtime']) {
  1668. // To be completed : An error or silent no replace ?
  1669. }
  1670. }
  1671. // ----- Check the directory availability and create it if necessary
  1672. elseif (($v_result
  1673. = $this->_dirCheck(($v_header['typeflag'] == "5"
  1674. ?$v_header['filename']
  1675. :dirname($v_header['filename'])))) != 1) {
  1676. $this->_error('Unable to create path for '.$v_header['filename']);
  1677. return false;
  1678. }
  1679. if ($v_extract_file) {
  1680. if ($v_header['typeflag'] == "5") {
  1681. if (!@file_exists($v_header['filename'])) {
  1682. if (!@mkdir($v_header['filename'], 0777)) {
  1683. $this->_error('Unable to create directory {'
  1684. .$v_header['filename'].'}');
  1685. return false;
  1686. }
  1687. }
  1688. } elseif ($v_header['typeflag'] == "2") {
  1689. if (@file_exists($v_header['filename'])) {
  1690. @unlink($v_header['filename']);
  1691. }
  1692. if (!@symlink($v_header['link'], $v_header['filename'])) {
  1693. $this->_error('Unable to extract symbolic link {'
  1694. .$v_header['filename'].'}');
  1695. return false;
  1696. }
  1697. } else {
  1698. if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) {
  1699. $this->_error('Error while opening {'.$v_header['filename']
  1700. .'} in write binary mode');
  1701. return false;
  1702. } else {
  1703. $n = floor($v_header['size']/512);
  1704. for ($i=0; $i<$n; $i++) {
  1705. $v_content = $this->_readBlock();
  1706. fwrite($v_dest_file, $v_content, 512);
  1707. }
  1708. if (($v_header['size'] % 512) != 0) {
  1709. $v_content = $this->_readBlock();
  1710. fwrite($v_dest_file, $v_content, ($v_header['size'] % 512));
  1711. }
  1712. @fclose($v_dest_file);
  1713. // ----- Change the file mode, mtime
  1714. @touch($v_header['filename'], $v_header['mtime']);
  1715. if ($v_header['mode'] & 0111) {
  1716. // make file executable, obey umask
  1717. $mode = fileperms($v_header['filename']) | (~umask() & 0111);
  1718. @chmod($v_header['filename'], $mode);
  1719. }
  1720. }
  1721. // ----- Check the file size
  1722. clearstatcache();
  1723. if (filesize($v_header['filename']) != $v_header['size']) {
  1724. $this->_error('Extracted file '.$v_header['filename']
  1725. .' does not have the correct file size \''
  1726. .filesize($v_header['filename'])
  1727. .'\' ('.$v_header['size']
  1728. .' expected). Archive may be corrupted.');
  1729. return false;
  1730. }
  1731. }
  1732. } else {
  1733. $this->_jumpBlock(ceil(($v_header['size']/512)));
  1734. }
  1735. } else {
  1736. $this->_jumpBlock(ceil(($v_header['size']/512)));
  1737. }
  1738. /* TBC : Seems to be unused ...
  1739. if ($this->_compress)
  1740. $v_end_of_file = @gzeof($this->_file);
  1741. else
  1742. $v_end_of_file = @feof($this->_file);
  1743. */
  1744. if ($v_listing || $v_extract_file || $v_extraction_stopped) {
  1745. // ----- Log extracted files
  1746. if (($v_file_dir = dirname($v_header['filename']))
  1747. == $v_header['filename'])
  1748. $v_file_dir = '';
  1749. if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == ''))
  1750. $v_file_dir = '/';
  1751. $p_list_detail[$v_nb++] = $v_header;
  1752. if (is_array($p_file_list) && (count($p_list_detail) == count($p_file_list))) {
  1753. return true;
  1754. }
  1755. }
  1756. }
  1757. return true;
  1758. }
  1759. // }}}
  1760. /**
  1761. * Open a file in appen mode
  1762. *
  1763. * @return boolean true on success
  1764. */
  1765. function _openAppend()
  1766. {
  1767. if (filesize($this->_tarname) == 0)
  1768. return $this->_openWrite();
  1769. if ($this->_compress) {
  1770. $this->_close();
  1771. if (!@rename($this->_tarname, $this->_tarname.".tmp")) {
  1772. $this->_error('Error while renaming \''.$this->_tarname
  1773. .'\' to temporary file \''.$this->_tarname
  1774. .'.tmp\'');
  1775. return false;
  1776. }
  1777. if ($this->_compress_type == 'gz')
  1778. $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb");
  1779. elseif ($this->_compress_type == 'bz2')
  1780. $v_temp_tar = @bzopen($this->_tarname.".tmp", "r");
  1781. if ($v_temp_tar == 0) {
  1782. $this->_error('Unable to open file \''.$this->_tarname
  1783. .'.tmp\' in binary read mode');
  1784. @rename($this->_tarname.".tmp", $this->_tarname);
  1785. return false;
  1786. }
  1787. if (!$this->_openWrite()) {
  1788. @rename($this->_tarname.".tmp", $this->_tarname);
  1789. return false;
  1790. }
  1791. if ($this->_compress_type == 'gz') {
  1792. while (!@gzeof($v_temp_tar)) {
  1793. $v_buffer = @gzread($v_temp_tar, 512);
  1794. if ($v_buffer == ARCHIVE_TAR_END_BLOCK) {
  1795. // do not copy end blocks, we will re-make them
  1796. // after appending
  1797. continue;
  1798. }
  1799. $v_binary_data = pack("a512", $v_buffer);
  1800. $this->_writeBlock($v_binary_data);
  1801. }
  1802. @gzclose($v_temp_tar);
  1803. }
  1804. elseif ($this->_compress_type == 'bz2') {
  1805. while (strlen($v_buffer = @bzread($v_temp_tar, 512)) > 0) {
  1806. if ($v_buffer == ARCHIVE_TAR_END_BLOCK) {
  1807. continue;
  1808. }
  1809. $v_binary_data = pack("a512", $v_buffer);
  1810. $this->_writeBlock($v_binary_data);
  1811. }
  1812. @bzclose($v_temp_tar);
  1813. }
  1814. if (!@unlink($this->_tarname.".tmp")) {
  1815. $this->_error('Error while deleting temporary file \''
  1816. .$this->_tarname.'.tmp\'');
  1817. }
  1818. } else {
  1819. // ----- For not compressed tar, just add files before the last
  1820. // one or two 512 bytes block
  1821. if (!$this->_openReadWrite())
  1822. return false;
  1823. clearstatcache();
  1824. $v_size = filesize($this->_tarname);
  1825. // We might have zero, one or two end blocks.
  1826. // The standard is two, but we should try to handle
  1827. // other cases.
  1828. fseek($this->_file, $v_size - 1024);
  1829. if (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) {
  1830. fseek($this->_file, $v_size - 1024);
  1831. }
  1832. elseif (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) {
  1833. fseek($this->_file, $v_size - 512);
  1834. }
  1835. }
  1836. return true;
  1837. }
  1838. // }}}
  1839. /**
  1840. * Append data to a file
  1841. *
  1842. * @param array $p_filelist The list of files
  1843. * @param string $p_add_dir The dir to add the files to
  1844. * @param string $p_remove_dir THe remove dir
  1845. */
  1846. function _append($p_filelist, $p_add_dir='', $p_remove_dir='')
  1847. {
  1848. if (!$this->_openAppend())
  1849. return false;
  1850. if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir))
  1851. $this->_writeFooter();
  1852. $this->_close();
  1853. return true;
  1854. }
  1855. // }}}
  1856. // {{{ _dirCheck()
  1857. /**
  1858. * Check if a directory exists and create it (including parent
  1859. * dirs) if not.
  1860. *
  1861. * @param string $p_dir directory to check
  1862. *
  1863. * @return boolean TRUE if the directory exists or was created
  1864. */
  1865. function _dirCheck($p_dir)
  1866. {
  1867. clearstatcache();
  1868. if ((@is_dir($p_dir)) || ($p_dir == ''))
  1869. return true;
  1870. $p_parent_dir = dirname($p_dir);
  1871. if (($p_parent_dir != $p_dir) &&
  1872. ($p_parent_dir != '') &&
  1873. (!$this->_dirCheck($p_parent_dir)))
  1874. return false;
  1875. if (!@mkdir($p_dir, 0777)) {
  1876. $this->_error("Unable to create directory '$p_dir'");
  1877. return false;
  1878. }
  1879. return true;
  1880. }
  1881. // }}}
  1882. // {{{ _pathReduction()
  1883. /**
  1884. * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar",
  1885. * rand emove double slashes.
  1886. *
  1887. * @param string $p_dir path to reduce
  1888. *
  1889. * @return string reduced path
  1890. *
  1891. */
  1892. function _pathReduction($p_dir)
  1893. {
  1894. $v_result = '';
  1895. // ----- Look for not empty path
  1896. if ($p_dir != '') {
  1897. // ----- Explode path by directory names
  1898. $v_list = explode('/', $p_dir);
  1899. // ----- Study directories from last to first
  1900. for ($i=sizeof($v_list)-1; $i>=0; $i--) {
  1901. // ----- Look for current path
  1902. if ($v_list[$i] == ".") {
  1903. // ----- Ignore this directory
  1904. // Should be the first $i=0, but no check is done
  1905. }
  1906. else if ($v_list[$i] == "..") {
  1907. // ----- Ignore it and ignore the $i-1
  1908. $i--;
  1909. }
  1910. else if ( ($v_list[$i] == '')
  1911. && ($i!=(sizeof($v_list)-1))
  1912. && ($i!=0)) {
  1913. // ----- Ignore only the double '//' in path,
  1914. // but not the first and last /
  1915. } else {
  1916. $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/'
  1917. .$v_result:'');
  1918. }
  1919. }
  1920. }
  1921. $v_result = strtr($v_result, '\\', '/');
  1922. return $v_result;
  1923. }
  1924. // }}}
  1925. /**
  1926. * translate a windows style path
  1927. *
  1928. * @param string $p_path The path
  1929. * @param boolean $p_remove_disk_letter If we have to remove the disk letter
  1930. */
  1931. function _translateWinPath($p_path, $p_remove_disk_letter=true)
  1932. {
  1933. if (defined('OS_WINDOWS') && OS_WINDOWS) {
  1934. // ----- Look for potential disk letter
  1935. if ( ($p_remove_disk_letter)
  1936. && (($v_position = strpos($p_path, ':')) != false)) {
  1937. $p_path = substr($p_path, $v_position+1);
  1938. }
  1939. // ----- Change potential windows directory separator
  1940. if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
  1941. $p_path = strtr($p_path, '\\', '/');
  1942. }
  1943. }
  1944. return $p_path;
  1945. }
  1946. // }}}
  1947. }