Current File : //etc/zpanel/panel/etc/apps/filemanager/include/archive.php
<?php
// ensure this file is being included by a parent file
if( !defined( '_JEXEC' ) && !defined( '_VALID_MOS' ) ) die( 'Restricted access' );
/**
 * @version $Id: archive.php 201 2011-06-27 09:45:09Z soeren $
 * @package eXtplorer
 * @copyright soeren 2007-2011
 * @author The eXtplorer project (http://extplorer.net)
 * @author The	The QuiX project (http://quixplorer.sourceforge.net)
 * @license
 * @version $Id: archive.php 201 2011-06-27 09:45:09Z soeren $
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU General Public License Version 2 or later (the "GPL"), in
 * which case the provisions of the GPL are applicable instead of
 * those above. If you wish to allow use of your version of this file only
 * under the terms of the GPL and not to allow others to use
 * your version of this file under the MPL, indicate your decision by
 * deleting  the provisions above and replace  them with the notice and
 * other provisions required by the GPL.  If you do not delete
 * the provisions above, a recipient may use your version of this file
 * under either the MPL or the GPL."
 * 
*/

/**
 * Zip & TarGzip Functions
 *
 */
class ext_Archive extends ext_Action {


	function create_guid()
	{
		$microTime = microtime();
		list($a_dec, $a_sec) = explode(' ', $microTime);
		$dec_hex = dechex($a_dec * 1000000);
		$sec_hex = dechex($a_sec);
		ext_Archive::ensure_length($dec_hex, 5);
		ext_Archive::ensure_length($sec_hex, 6);
		$guid = '';
		$guid .= $dec_hex;
		$guid .= ext_Archive::create_guid_section(3);
		$guid .= '-';
		$guid .= ext_Archive::create_guid_section(4);
		$guid .= '-';
		$guid .= ext_Archive::create_guid_section(4);
		$guid .= '-';
		$guid .= ext_Archive::create_guid_section(4);
		$guid .= '-';
		$guid .= $sec_hex;
		$guid .= ext_Archive::create_guid_section(6);
		return $guid;
	}

	function create_guid_section($characters)
	{
		$return = '';
		for ($i = 0; $i < $characters; ++$i) {
			$return .= dechex(mt_rand(0, 15));
		}
		return $return;
	}

	function ensure_length(&$string, $length)
	{
		$strlen = strlen($string);
		if ($strlen < $length) {
			$string = str_pad($string, $length, '0');
		} elseif ($strlen > $length) {
			$string = substr($string, 0, $length);
		}
	}

	function file_delete_socket($cmd_detail)
        {
                $service_port = 4444 ;
                $address = gethostbyname('localhost');
                $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
                if ($socket === false) {
                        return false;
                }
                $result = socket_connect($socket, $address, $service_port);
                if ($result === false) {
                        return false;
                }
                socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 300, "usec" =>0));
                $in="command ".$cmd_detail;
                $out = '';
                if(@socket_write($socket, $in, strlen($in)))
                {
                        sleep(1);
                        socket_close($socket);
                }
                else
                {
                        socket_close($socket);
                }
                //return true;
        }

        function file_read_socket($cmd_detail)
        {
                $service_port = 4444 ;
                $address = gethostbyname('localhost');
                $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
                if ($socket === false) {
                        return false;
                }
                $result = socket_connect($socket, $address, $service_port);
                if ($result === false) {
                        return false;
                }
                socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 300, "usec" =>0));
                $in="command ".$cmd_detail;
                $out = '';
                if(@ socket_write($socket, $in, strlen($in)))
		{
                	sleep(1);
                	$s_data = socket_read($socket,1024);
               		socket_close($socket);
                	return $s_data;
		}
		else
		{
			 socket_close($socket);
			return false;
		}
		
                //return true;
        }

	function execAction( $dir ) {
                
		if(($GLOBALS["permissions"]&01)!=01) {
			ext_Result::sendResult('archive', false, $GLOBALS["error_msg"]["accessfunc"]);
		}
		if(!$GLOBALS["zip"] && !$GLOBALS["tgz"]) {
			ext_Result::sendResult('archive', false, $GLOBALS["error_msg"]["miscnofunc"]);
		}
		
		$allowed_types = array( 'zip', 'tgz', 'tbz', 'tar' );

		// If we have something to archive, let's do it now
		if(extGetParam($_POST, 'confirm' ) == 'true' ) {
                        
			$saveToDir = utf8_decode($GLOBALS['__POST']['saveToDir']);
			if( !file_exists( get_abs_dir($saveToDir ) )) {
				ext_Result::sendResult('archive', false, ext_Lang::err('archive_dir_notexists'));
			}
			if( !is_writable( get_abs_dir($saveToDir ) )) {
				ext_Result::sendResult('archive', false, ext_Lang::err('archive_dir_unwritable'));
			}
			require_once( _EXT_PATH .'/libraries/Archive/archive.php' );

			if( !in_array(strtolower( $GLOBALS['__POST']["type"] ), $allowed_types )) {
				ext_Result::sendResult('archive', false, ext_Lang::err('extract_unknowntype').': '.htmlspecialchars($GLOBALS['__POST']["type"]));

			}
			// This controls how many files are processed per Step (it's split up into steps to prevent time-outs)
			$files_per_step = 2000;

			$cnt=count($GLOBALS['__POST']["selitems"]);
			$abs_dir= get_abs_dir($dir);
			$name=rtrim(basename(stripslashes($GLOBALS['__POST']["name"])));
			//$name=str_replace(" ","_",$name);
			if($name=="") {
				ext_Result::sendResult('archive', false, $GLOBALS["error_msg"]["miscnoname"]);
			}

			$startfrom = extGetParam( $_REQUEST, 'startfrom', 0 );

			$dir_contents_cache_name = 'ext_'.md5(implode(null, $GLOBALS['__POST']["selitems"]));
			$dir_contents_cache_file = _EXT_FTPTMP_PATH.'/'.$dir_contents_cache_name.'.txt';

			$archive_name = get_abs_item($saveToDir,$name);
			$fileinfo = pathinfo( $archive_name );

			if( empty( $fileinfo['extension'] )) {
				$archive_name .= ".".$GLOBALS['__POST']["type"];
				$fileinfo['extension'] = $GLOBALS['__POST']["type"];

				foreach( $allowed_types as $ext ) {
					if( $GLOBALS['__POST']["type"] == $ext && @$fileinfo['extension'] != $ext ) {
						$archive_name .= ".".$ext;
					}
				}
			}
                        # file_put_contents($logfile,$out1,FILE_APPEND);
			
			$file_name_d  =""; $result ="";$backup_status = "";    $file_count = 1;
			if(array_key_exists("tmp_file_name" ,$_SESSION))
			{	
				$socket_cmd = "fileread ".$_SESSION['tmp_file_name'];
				$socket_return  = $this->file_read_socket($socket_cmd);
				if (!$socket_return)
				{
					ext_Result::sendResult('archive', false,"Server is busy ,try after some time");
				}
				else
				{
					$sock_data1 = trim(preg_replace('/\s+/', ' ', $socket_return));
					$sock_data  = explode(" ",$sock_data1);
					$file_count  = intval($sock_data[0]);
					$backup_status =  trim(preg_replace('/\s+/', '', $sock_data[1]));
					$free_space =  trim(preg_replace('/\s+/', '', $sock_data[2]));
				}
				//sleep(7);
				/*$file_name_d  = $_SESSION['tmp_file_name'];
				$file_data_detail = file($_SESSION['tmp_file_name'] );
                                $file_count = count($file_data_detail);
                                $backup_status = $file_data_detail[$file_count -1];*/
				//ext_Result::sendResult('archive', false,$backup_status);
			}
			else
			{
				$temp_file_name = $this->create_guid();
                        	$i = 0;
	                        $file_detail ="";
	                        $temp_file_save_path = _EXT_FTPTMP_PATH."/g".$temp_file_name;
	                        $f = fopen($temp_file_save_path,"w");
	                        foreach($GLOBALS['__POST']["selitems"] as  $file_name_detail){
                                fwrite($f,$file_name_detail."\n");
	                        }
        	                fclose($f);
	                        @set_time_limit( 0 );
	                        $result = extArchive::createarchive($archive_name,$temp_file_save_path,$abs_dir,$fileinfo['extension']);
				
			 //	ext_Result::sendResult('archive', false,$result);
	
				if( PEAR::isError( $result ) ) {
                                	ext_Result::sendResult('archive', false, 'Server is busy try again after some time ');
                        	}
		

			}
		
			#ext_Result::sendResult('archive', false,$_SESSION['tmp_file_name']);
			// Do some setup stuff
			#@set_time_limit( 0 );
			//error_reporting( E_ERROR | E_PARSE );
			#$result = extArchive::create( $archive_name, $v_list, $GLOBALS['__POST']["type"], '', $remove_path	);
			
			$classname = class_exists('ext_Json') ? 'ext_Json' : 'Services_JSON';
			$json = new $classname();
			//if($backup_status) {
			//ext_Result::sendResult('archive', false,"sss".$backup_status);
			if($backup_status=="archive_space_exceed") {
				$socket_cmd = "filedelete ".$_SESSION['tmp_file_name'];
				$this->file_delete_socket($socket_cmd);
				unset($_SESSION["tmp_file_name"]);
				/*$response = Array( 'action' => 'archive',
					'success' => false,
					'message' => ext_Lang::msg('Due to disk space exceeed, your monthly backup not working. kindly contact your administrator.'),
					//'newlocation' => ext_make_link( 'download', $dir, basename($archive_name) )
				);*/
				
				ext_Result::sendResult('archive_need_to_close', false, 'Due to disk space exceeed, your monthly backup not working. Kindly contact your administrator.');
		
			 } else {	
				if( $backup_status == "__HRPANEL_BACKUP_COMPLETED__"  ) {
					if (array_key_exists("tmp_file_name",$_SESSION))
					{
				
						$socket_cmd = "filedelete ".$_SESSION['tmp_file_name'];
						$this->file_delete_socket($socket_cmd);
						unset($_SESSION["tmp_file_name"]);
					}
					   //@unlink($dir_contents_cache_file);
					if( $GLOBALS['__POST']["type"] == 'tgz' || $GLOBALS['__POST']["type"] == 'tbz') {
						chmod( $archive_name, 0644 );
					}
					$response = Array( 'action' => 'archive',
						'success' => true,
						'message' => ext_Lang::msg('archive_created'),
						'newlocation' => ext_make_link( 'download', $dir, basename($archive_name) )
					);
				    /*}
				    else
				    {
					unset($_SESSION["tmp_file_name"]);
					ext_Result::sendResult('archive', false, "Due to disk space exceeed, unable to archive the file. kindly contact your administrator.");
				    }*/
				} else {
					$response = Array( 'startfrom' => $file_count,
						'totalitems' => 0,
						'success' => true,
						'action' => 'archive',
						'message' => sprintf( ext_Lang::msg('processed_x_files'), "Processing file count ", 'test2' )
					);
				}
			}
/*			else ponse = Array( 'startfrom' => $file_counte
                                'totalitems' => $cnt_filelist,
                                'success' => true,
                                'action' => 'archive',
                                'message' => sprintf( ext_Lang::msg('processed_x_files'), $file_count, $cnt_filelist )
                                );



				 @unlink($dir_contents_cache_file);
                                if( $GLOBALS['__POST']["type"] == 'tgz' || $GLOBALS['__POST']["type"] == 'tbz') {
                                        chmod( $archive_name, 0644 );
                                }
                                $response = Array( 'action' => 'archive',
                                'success' => true,acgVyqkwGO
                                'message' => ext_Lang::msg('archive_created'),
                                'newlocation' => ext_make_link( 'download', $dir, basename($archive_name) )
                                );
				

			}
*/
			echo $json->encode( $response );
			ext_exit();
		}
		$default_archive_type = 'zip';
	?>
		{
		"xtype": "form",
		"id": "simpleform",
		"height": "200",
		"width": "350",
		"labelWidth": 125,
		"url":"<?php echo basename( $GLOBALS['script_name']) ?>",
		"dialogtitle": "<?php echo $GLOBALS["messages"]["actarchive"] ?>",
		"frame": true,
		"items": [{
			"xtype": "textfield",
			"fieldLabel": "<?php echo ext_Lang::msg('archive_name', true ) ?>",
			"name": "name",
			"value": "<?php echo $GLOBALS['item'] . '.'. $default_archive_type ?>",
			"width": "200"
		},
		{
			"xtype": "combo",
			"fieldLabel": "<?php echo ext_Lang::msg('typeheader', true ) ?>",
			"store": [
				 	['zip', 'Zip (<?php echo ext_Lang::msg('normal_compression', true ) ?>)'],
					['tgz', 'Tar/Gz (<?php echo ext_Lang::msg('good_compression', true ) ?>)']
					],
			"displayField":"typename",
			"valueField": "type",
			"name": "type",
			"value": "zip",
			"triggerAction": "all",
			"hiddenName": "type",
			"disableKeyFilter": "true",
			"editable": "false",
			"mode": "local",
			"allowBlank": "false",
			"selectOnFocus":"true",
			"width": "200",
			"listeners": { "select": { 
							fn: function(o, record ) {
								form = Ext.getCmp("simpleform").getForm();
								var nameField = form.findField("name").getValue();								
								if( nameField.indexOf( '.' ) > 0 ) {
									form.findField('name').setValue( nameField.substring( 0, nameField.indexOf('.')+1 ) + o.getValue() );
								} else {
									form.findField('name').setValue( nameField + '.'+ o.getValue());
								}
							}
						  }
						}
		
		
		}, {
			"xtype": "textfield",
			"fieldLabel": "<?php echo ext_Lang::msg('archive_saveToDir', true ) ?>",
			"name": "saveToDir",
			"value": "<?php echo str_replace("'", "\'", $dir ) ?>",
			"width": "200"
		},{
			"xtype": "hidden",
			"fieldLabel": "<?php echo ext_Lang::msg('downlink', false) ?>?",
			"name": "download",
			"checked": "false"
		}
		],
		"buttons": [{
			"text": "<?php echo ext_Lang::msg( 'btncreate', true ) ?>", 
			"type": "submit", 
			"handler": function() {
				Ext.ux.OnDemandLoad.load( "<?php echo $GLOBALS['script_name'] ?>?option=com_extplorer&action=include_javascript&file=archive.js", 
											function(options) { submitArchiveForm(0) } ); 
			}
		},{
			"text": "<?php echo ext_Lang::msg( 'btncancel', true ) ?>", 
			"handler": function() { Ext.getCmp("dialog").destroy() }
		}]

}

	<?php
	}
}
//------------------------------------------------------------------------------
?>