function create_zip_Zip($files = array(), $destination = '')
{
    if (count($files)) {
        //create the archive
        if (file_exists($destination)) {
            unlink($destination);
        }
        $zip = new Zip();
        $zip->setZipFile($destination);
        foreach ($files as $file) {
            $zip->addFile(file_get_contents($file), str_replace('/', '', strrchr($file, '/')));
        }
        $zip->finalize();
        $zip->setZipFile($destination);
        //check to make sure the file exists
        return (string) file_exists($destination);
    } else {
        return "No valid files found. Exiting<br/>";
    }
}
Example #2
0
     // Preferrably use the zip extension
     if (extension_loaded('zip')) {
         $save_to_zip = $export_dir . $export_name . '.zip';
         $zip = new ZipArchive();
         $res = $zip->open($save_to_zip, ZipArchive::CREATE);
         if ($res === TRUE) {
             $zip->addFile($save_to, "{$export_name}.xml");
             $zip->close();
         } else {
             die("{$hesklang['eZIP']} <{$save_to_zip}>\n");
         }
     } elseif (class_exists('ZipArchive')) {
         require HESK_PATH . 'inc/zip/Zip.php';
         $zip = new Zip();
         $zip->addLargeFile($save_to, "{$export_name}.xml");
         $zip->finalize();
         $zip->setZipFile($save_to_zip);
     } else {
         require HESK_PATH . 'inc/zip/pclzip.lib.php';
         $zip = new PclZip($save_to_zip);
         $zip->add($save_to, PCLZIP_OPT_REMOVE_ALL_PATH);
     }
     // Delete XML, just leave the Zip archive
     hesk_unlink($save_to);
     // Echo memory peak usage
     $flush_me .= hesk_date() . " | " . sprintf($hesklang['pmem'], @memory_get_peak_usage(true) / 1048576) . "<br />\r\n";
     // We're done!
     $flush_me .= hesk_date() . " | {$hesklang['fZIP']}<br /><br />";
     $flush_me .= '<a href="' . $save_to_zip . '">' . $hesklang['ch2d'] . "</a>\n";
 } else {
     hesk_unlink($save_to);
 public function backup_items($items)
 {
     $dir = SNS_BACKUPS_PATH . $this->filename;
     if (!class_exists('Zip', false)) {
         require_once SNS_LIB_PATH . 'Zip.php';
     }
     $warns = array('not_readable' => array());
     $zip = new Zip();
     $zip->setZipFile($dir . '.zip');
     self::$zipFile = $zip;
     foreach ($items as $name => $path) {
         if ($name == Sns_Option::DB) {
             $sql_file = SNS_BACKUPS_PATH . 'wp_dump.sql';
             Sns_Log::log_action('Exporting DB');
             Sns_Backup::export_db($sql_file);
             Sns_Log::log_action('Exporting DB', SNS_LOG_END);
             $stream = @fopen($sql_file, 'rb');
             if ($stream) {
                 $zip->addLargeFile($stream, 'wp_dump.sql');
             }
             @unlink($sql_file);
             continue;
         }
         Sns_Log::log_action('Backup item - ' . $name);
         $itemZip = new Zip();
         $itemZip->setZipFile(SNS_BACKUPS_PATH . $name . '.zip');
         $path = realpath($path);
         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS));
         $exclude = array(realpath(SNS_BACKUP_ROOT), realpath(SNS_BACKUPS_PATH), realpath(WP_CONTENT_DIR . SNS_DS . 'debug.log'));
         for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
             $file = $iterator->current();
             $continue = false;
             foreach ($exclude as $excludeFile) {
                 if (strpos($file, $excludeFile) !== false) {
                     $continue = true;
                 }
             }
             if ($continue) {
                 continue;
             }
             if (file_exists($file) && is_readable($file)) {
                 $stream = @fopen($file, 'rb');
                 if ($stream) {
                     $file = substr($file, strlen($path));
                     $itemZip->addLargeFile($stream, $file);
                 }
             } else {
                 $warns['not_readable'][] = $file;
             }
         }
         $itemZip->finalize();
         $stream = @fopen(SNS_BACKUPS_PATH . $name . '.zip', 'rb');
         if ($stream) {
             $zip->addLargeFile($stream, $name . '.zip');
         }
         @unlink(SNS_BACKUPS_PATH . $name . '.zip');
         Sns_Log::log_action('Backup item - ' . $name, SNS_LOG_END);
     }
     Sns_Log::log_action('Summarize item backups');
     $zip->finalize();
     Sns_Log::log_action('Summarize item backups', SNS_LOG_END);
     $this->hash;
     $this->filename;
     $this->save();
     return $warns;
 }
Example #4
0
 /**
  * Creates a new archive with the specified name and files
  * @param string $name Path to the archive with name and extension
  * @param array $files A numeric array of files
  * @param string $replace
  * @param string $fullPath
  * @return int How many files has been successfully handled
  */
 public function getArchive($name, array $files, $replace = ABSPATH, $fullPath = false)
 {
     set_time_limit(300);
     if (!class_exists('Zip', false)) {
         /** @var backupBup $backup */
         $backup = $this->getModule();
         $backup->loadLibrary('zip');
     }
     $zip = new Zip();
     $zip->setZipFile($name);
     if ($fullPath) {
         $absPath = null;
     } else {
         $absPath = str_replace('/', DS, ABSPATH);
     }
     foreach ($files as $filename) {
         $file = $absPath . $filename;
         if ($fullPath) {
             $file = str_replace('\\\\', DS, $filename);
         }
         if (file_exists($file) && is_readable($file) && (substr(basename($file), 0, 3) != 'pcl' && substr($file, -2) != 'gz')) {
             $stream = @fopen($file, 'rb');
             if ($stream) {
                 $zip->addLargeFile($stream, $filename);
             }
         }
     }
     $zip->finalize();
     if (false !== strpos($name, 'backup_')) {
         // if backup created - remove all temporary files from tmp directory
         $this->clearTmpDirectory();
     }
     /* backward */
     return rand(100, 1000);
 }
 public function scanner($check_session = true, $show_results = true)
 {
     // Start scanning process
     error_reporting(0);
     ini_set('memory_limit', '256M');
     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         define(DIRSEP, '\\');
     } else {
         define(DIRSEP, '/');
     }
     // Skip the 2nd scan process
     $lockFile = $this->tmp_dir . 'scan.lock';
     if (file_exists($lockFile) && time() - filemtime($lockFile) < 60 * 5) {
         $error_msg = 'Another Scanning Process in the memory. Exit.';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     register_shutdown_function('self::AntivirusFileLock');
     $lockFp = fopen($lockFile, 'w');
     // Register any shutdown of the script
     register_shutdown_function('self::AntivirusFinished');
     $error_msg = 'Start Scan Process ver. ' . $this->antivirus_version . ' [scanner ver. ' . self::$scanner_version . ']';
     if (self::$debug) {
         self::DebugLog($error_msg, true);
     }
     // Load extra settings
     if (file_exists($this->work_dir . 'settings.php')) {
         $error_msg = '=> Extra settings loaded';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         require_once $this->work_dir . 'settings.php';
         if (count($avp_settings)) {
             foreach ($avp_settings as $k => $v) {
                 $v_txt = $v;
                 if ($v === false) {
                     $v_txt = 'BOOL: false';
                 }
                 if ($v === true) {
                     $v_txt = 'BOOL: true';
                 }
                 $error_msg = 'Setting Value: ' . strtoupper($k) . ' = ' . $v_txt;
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 if (strtolower($v) == 'false') {
                     $v = false;
                 }
                 if (strtolower($v) == 'true') {
                     $v = true;
                 }
                 define(strtoupper($k), $v);
             }
         }
     }
     // Analyze of exclude folders
     if (file_exists($this->work_dir . 'exclude_folders.php')) {
         $error_msg = '=> Exclude folders file loaded';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         require_once $this->work_dir . 'exclude_folders.php';
     }
     $tmp_result = set_time_limit(7200);
     $error_msg = 'Change Time limit: ' . self::$bool_list[intval($tmp_result)] . ' , Value: ' . ini_get('max_execution_time');
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Current Memory limit: ' . ini_get('memory_limit');
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'OS info: ' . PHP_OS . ' (' . php_uname() . ')';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'PHP ver: ' . PHP_VERSION;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     unlink($this->tmp_dir . 'flag_terminated.tmp');
     unlink($this->tmp_dir . 'filelist.txt');
     /*if (!class_exists("HTTPClient"))
             {
                 include_once($this->work_dir.'HttpClient.class.php');
             }
     		
     		$HTTPClient = new HTTPClient();*/
     // Some Init data
     $membership = $this->membership;
     $scan_path = $this->scan_path;
     $access_key = $this->access_key;
     $domain = $this->domain;
     $email = $this->email;
     $session_report_key = $this->session_report_key;
     // Some logs
     $error_msg = 'Domain: ' . $domain;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Scan path: ' . $scan_path;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Session report key: ' . $session_report_key;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'Report URL: https://www.siteguarding.com/antivirus/viewreport?report_id=' . $session_report_key;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = 'TMP folder: ' . $this->tmp_dir;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if (trim($domain) == '') {
         $error_msg = 'Domain is empty. Please contact SiteGuarding.com support.';
         echo $error_msg;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     if (trim($session_report_key) == '') {
         $error_msg = 'Session key is empty. Please contact SiteGuarding.com support.';
         echo $error_msg;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     if (trim($scan_path) == '') {
         $error_msg = 'Scan Path is empty. Please contact SiteGuarding.com support.';
         echo $error_msg;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         exit;
     }
     //session_start();
     $current_task = 0;
     $total_tasks = 0;
     $total_tasks += 1;
     // Analyze what way to use for packing
     $total_tasks += 1;
     // Pack files
     $total_tasks += 1;
     // Send files
     $total_tasks += 1;
     // Get report
     /**
      * Analyze what way to use for packing
      */
     $ssh_flag = false;
     if (function_exists('exec')) {
         // Pack files with ssh
         $ssh_flag = true;
     }
     if (defined('SETTINGS_ONLY_ZIP') && SETTINGS_ONLY_ZIP) {
         $ssh_flag = false;
     }
     // Update progress
     $current_task += 1;
     self::UpdateProgressValue($current_task, $total_tasks, 'Initialization.');
     if (self::$debug) {
         self::DebugLog('line');
     }
     $files_list = array();
     if (defined('DEBUG_FILELIST') && DEBUG_FILELIST) {
         self::DebugFile($this->work_dir, true);
     }
     $error_msg = 'Collecting info about the files [METHOD 2]';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $exclude_folders_real = array();
     if (count($exclude_folders)) {
         foreach ($exclude_folders as $k => $ex_folder) {
             $ex_folder = $scan_path . trim($ex_folder);
             $exclude_folders_real[$k] = trim(str_replace(DIRSEP . DIRSEP, DIRSEP, $ex_folder));
         }
     } else {
         $exclude_folders_real = array();
     }
     $this->exclude_folders_real = $exclude_folders_real;
     $error_msg = 'Excluded Folders: ' . count($exclude_folders_real);
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $error_msg = print_r($exclude_folders_real, true);
     if (self::$debug && count($exclude_folders_real) > 0) {
         self::DebugLog($error_msg);
     }
     $dirList = array();
     $dirList[] = $scan_path;
     // Scan all dirs
     while (true) {
         $dirList = array_merge(self::ScanFolder(array_shift($dirList), $files_list), $dirList);
         if (count($dirList) < 1) {
             break;
         }
     }
     $error_msg = 'Save collected file_list';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $collected_filelist = $this->tmp_dir . 'filelist.txt';
     $fp = fopen($collected_filelist, 'w');
     $status = fwrite($fp, implode("\n", $files_list));
     fclose($fp);
     if ($status === false) {
         $error_msg = 'Cant save information about the collected files ' . $collected_filelist;
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         // Turn ZIP mode
         $ssh_flag = false;
     }
     $error_msg = 'Total files: ' . count($files_list);
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if (self::$debug) {
         self::DebugLog('line');
     }
     if ($ssh_flag) {
         // SSH way
         $error_msg = 'Start - Pack with SSH';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         $cmd = 'cd ' . $scan_path . '' . "\n" . 'tar -czf ' . $this->tmp_dir . 'pack.tar -T ' . $collected_filelist;
         $output = array();
         $result = exec($cmd, $output);
         if (file_exists($this->tmp_dir . 'pack.tar') === false) {
             $ssh_flag = false;
             $error_msg = 'Change pack method from SSH to PHP (ZipArchive)';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
         }
     }
     if (!$ssh_flag) {
         // PHP way
         $error_msg = 'Start - Pack with ZipArchive';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         $file_zip = $this->tmp_dir . 'pack.zip';
         if (file_exists($file_zip)) {
             unlink($file_zip);
         }
         $pack_dir = $scan_path;
         if (class_exists('ZipArchive')) {
             // open archive
             $zip = new ZipArchive();
             if ($zip->open($file_zip, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) === TRUE) {
                 foreach ($files_list as $file_name) {
                     $file_name = $this->scan_path . $file_name;
                     if (strstr(realpath($file_name), "stark") == FALSE) {
                         $short_key = str_replace($scan_path, "", $file_name);
                         $s = $zip->addFile(realpath($file_name), $short_key);
                         if (!$s) {
                             $error_msg = 'Couldnt add file: ' . $file_name;
                             if (self::$debug) {
                                 self::DebugLog($error_msg);
                             }
                         }
                     }
                 }
                 // close and save archive
                 $zip->close();
                 //$result['msg'][] = 'Archive created successfully';
             } else {
                 $error_msg = 'Error: Couldnt open ZIP archive.';
                 echo $error_msg;
                 self::UpdateProgressValue($current_task, $total_tasks, $error_msg);
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 exit;
             }
         } else {
             $error_msg = 'Error: ZipArchive class is not exist.';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
         }
         $error_msg = 'ZipArchive method - finished';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         // Check if zip file exists
         if (!file_exists($file_zip)) {
             $error_msg = 'Error: zip file is not exists. Use OwnZipClass';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $error_msg = 'OwnZipClass method - started';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $zip = new Zip();
             $zip->setZipFile($file_zip);
             foreach ($files_list as $file_name_short) {
                 $file_name = trim($this->scan_path . $file_name_short);
                 $handle = fopen($file_name, "r");
                 if (filesize($file_name) > 0) {
                     $zip->addFile(fread($handle, filesize($file_name)), $file_name_short, filectime($file_name), NULL, TRUE, Zip::getFileExtAttr($file_name));
                 }
                 fclose($handle);
             }
             $zip->finalize();
             $error_msg = 'OwnZipClass method - finished';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $ssh_flag = false;
         }
     }
     // Update progress
     $current_task += 1;
     self::UpdateProgressValue($current_task, $total_tasks, 'Collecting information about the files.');
     /**
      * Send files to SG server
      */
     if ($ssh_flag) {
         $archive_filename = $this->tmp_dir . "pack.tar";
         $archive_format = 'tar';
     } else {
         $archive_filename = $this->tmp_dir . "pack.zip";
         $archive_format = 'zip';
     }
     $error_msg = 'Pack file: ' . $archive_filename;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     // Check if pack file is exist
     if (file_exists($archive_filename) === false) {
         $error_msg = 'Error: Pack file is not exist. Probably not enough space on the server.';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         echo $error_msg;
         exit;
     }
     $tar_size = filesize($archive_filename);
     $error_msg = 'Pack file is ' . round($tar_size / 1024 / 1024, 2) . 'Mb';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if (self::$debug) {
         self::DebugLog('line');
     }
     $error_msg = 'Start - Send Packed files to SG server';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     $archive_file_url = "/" . str_replace($this->scan_path, "", $this->tmp_dir) . 'pack.' . $archive_format;
     $archive_file_url = str_replace("\\", "/", $archive_file_url);
     $error_msg = 'Pack URL: ' . $archive_file_url;
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     if ($tar_size < 32 * 1024 * 1024 || $membership == 'pro') {
         // Send file
         $post_data = base64_encode(json_encode(array('domain' => $domain, 'access_key' => $access_key, 'email' => $email, 'session_report_key' => $session_report_key, 'archive_format' => $archive_format, 'archive_file_url' => $archive_file_url)));
         $flag_CallBack = false;
         if (defined('CALLBACK_PACK_FILE') && CALLBACK_PACK_FILE) {
             // Callback option
             $flag_CallBack = true;
         } else {
             $result = self::UploadSingleFile($archive_filename, 'uploadfiles_ver2', $post_data);
             if ($result === false) {
                 $error_msg = 'Can not upload pack file for analyze';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 $flag_CallBack = true;
             } else {
                 $error_msg = 'Pack file sent for analyze - OK';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 $flag_CallBack = false;
             }
         }
         // CallBack method
         if ($flag_CallBack) {
             $error_msg = 'Start to use CallBack method';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             $post_data = base64_encode(json_encode(array('domain' => $domain, 'access_key' => $access_key, 'email' => $email, 'session_report_key' => $session_report_key, 'archive_format' => $archive_format, 'archive_file_url' => $archive_file_url)));
             $result = self::UploadSingleFile_Callback($post_data);
             if ($result === false) {
                 $error_msg = 'CallBack method - failed';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 $error_msg = 'Can not upload pack file for analyze';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
                 echo $error_msg;
                 exit;
             } else {
                 $error_msg = 'CallBack method - OK';
                 if (self::$debug) {
                     self::DebugLog($error_msg);
                 }
             }
         }
     } else {
         $error_msg = 'Pack file is too big (' . $error_msg . '), please contact SiteGuarding.com support or upgrade to PRO version.';
         if (self::$debug) {
             self::DebugLog($error_msg);
         }
         echo $error_msg;
         exit;
     }
     // Update progress
     $current_task += 1;
     self::UpdateProgressValue($current_task, $total_tasks, 'Analyzing the files. Preparing the report.');
     if (self::$debug) {
         self::DebugLog('line');
     }
     /**
      * Check and Get report from SG server
      */
     $error_msg = 'Start - Report generating';
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
     for ($i = 1; $i <= 10 * 60; $i++) {
         sleep(5);
         /*$post_data = array(
         			'data'=> base64_encode(json_encode(array(
         				'domain' => $domain,
         				'access_key' => $access_key,
         				'session_report_key' => $session_report_key)))
         		);*/
         $post_data = base64_encode(json_encode(array('domain' => $domain, 'access_key' => $access_key, 'session_report_key' => $session_report_key)));
         //$result_json = $HTTPClient->post(self::$SITEGUARDING_SERVER.'?action=getreport_ver2', $post_data);
         $link = self::$SITEGUARDING_SERVER . '?action=getreport_ver2&data=' . $post_data;
         $result_json = file_get_contents($link);
         if ($result_json === false) {
             $error_msg = 'Report can not be generated. Please try again or contact support';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             echo $error_msg;
             exit;
         }
         $result_json = (array) json_decode($result_json, true);
         //if (self::$debug) self::DebugLog(print_r($result_json, true));
         if ($result_json['status'] == 'ready') {
             echo $result_json['text'];
             // Update progress
             $current_task += 1;
             self::UpdateProgressValue($current_task, $total_tasks, 'Done. Sending your report.');
             $error_msg = 'Done. Sending your report by email';
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             // Send email to user with the report
             $email_result = self::SendEmail($email, $result_json['text']);
             if ($email_result) {
                 $error_msg = 'Report Sent - OK';
             } else {
                 $error_msg = 'Report Sent - FAILED';
             }
             if (self::$debug) {
                 self::DebugLog($error_msg);
             }
             exit;
         }
     }
     $error_msg = 'Finished [Report is not sent]' . "\n";
     if (self::$debug) {
         self::DebugLog($error_msg);
     }
 }
Example #6
0
	public function createDownloadPackage($type, $itemIdArray, $parentId, $version)
	{
		$app = JFactory::getApplication();
		// If set no_counting_download_time, storeId will be used to check if download file in "no counting download" period
		sort($itemIdArray);
		$storeId = md5($type . serialize($itemIdArray) . $version);

		if ($type == 'document')
		{
			$params = JUDownloadHelper::getParams($parentId);
		}
		else
		{
			$params = JUDownloadHelper::getParams(null, $parentId);
		}

		$noCountingDownloadSecond = (int) $params->get('no_counting_download_time', 300);
		if ($noCountingDownloadSecond > 0)
		{
			$storeIdArray = (array) $app->getUserState('com_judownload.download.storeid');
		}
		else
		{
			$storeIdArray = array();
		}

		$user = JFactory::getUser();

		$downloadZippedFileMode      = $params->get('download_zipped_file_mode', 'temp');
		$downloadOneFileNoZippedMode = $params->get('download_one_file_no_zipped_mode', 'temp');

		// Min download speed.
		$minDownloadSpeed = (int) $params->get('min_download_speed', 10);
		$minDownloadSpeed = $minDownloadSpeed > 0 ? $minDownloadSpeed : 10;
		$minDownloadSpeed = $minDownloadSpeed * 1024; //KBps

		// Min live time of download package.
		$adjustFileLiveTime = (int) $params->get('adjust_file_live_time', 60);
		$adjustFileLiveTime = $adjustFileLiveTime >= 0 ? $adjustFileLiveTime : 60;

		// Time download package created.
		$createdTimeDate  = JFactory::getDate()->toSql();
		$createdTimeStamp = strtotime($createdTimeDate);

		// Trigger JU Download after download
		$dispatcher = JDispatcher::getInstance();
		JPluginHelper::importPlugin('judownload');

		// Physical file path to download, to be used in temp folder mode
		$downloadFilePath = '';

		// True if file is zipped by zip class
		$zipFile = false;

		// Get comment for zip package.
		$zipCommentConfig = $params->get('zip_comment', '');

		// Zip comment parsed from $zipCommentConfig case by case
		$zipComment = '';

		if ($type == 'document')
		{
			// Get category id.
			$categoryId      = $parentId;
			$documentIdArray = $itemIdArray;
			// Download multi documents in the same cat
			if (count($documentIdArray) > 1)
			{
				// In this case : user downloading category.
				// Sort array document id.
				sort($documentIdArray);

				// Create zip package.
				$zip     = new Zip();
				$zipFile = true;

				// Parse zip comment
				$zipComment = $this->parseCommentTxt($zipCommentConfig, $categoryId);

				// File id array in all download documents to reference in tmp file table
				$fileIdArrayInTmpZip = array();
				foreach ($documentIdArray AS $documentId)
				{
					$documentObject = JUDownloadHelper::getDocumentById($documentId);
					$documentTitle  = $this->filterFileFolderName($documentObject->title);
					$documentTitle  = trim($documentTitle);
					$fileObjectList = $this->getAllFilesOfDocument($documentId);
					// If document has file, add document title as a folder contains files
					if (count($fileObjectList))
					{
						$zip->addDirectory($documentTitle);
					}

					// File id array in document to log document.download
					$fileIdArray  = array();
					$documentSize = 0;
					foreach ($fileObjectList AS $fileObject)
					{
						$physicalFilePath = $this->getPhysicalFilePath($fileObject->id);

						if (JFile::exists($physicalFilePath))
						{
							$filePathInZip = $documentTitle . '/' . $this->filterFileFolderName($fileObject->rename);

							// Add file extension to file path, if the extension is not the same original file
							$fileExtOri   = JFile::getExt($physicalFilePath);
							$fileExtInZip = JFile::getExt($filePathInZip);
							if ($fileExtInZip != $fileExtOri)
							{
								$filePathInZip = $filePathInZip . '.' . $fileExtOri;
							}
							$filePathInZip = trim($filePathInZip);

							$zip->addLargeFile($physicalFilePath, $filePathInZip);
							$documentSize += $fileObject->size;
							if (!in_array($storeId, $storeIdArray))
							{
								$this->updateFileDownloadCounter($fileObject->id);
							}
						}
						$fileIdArray[]         = $fileObject->id;
						$fileIdArrayInTmpZip[] = $fileObject->id;
					}

					if (!in_array($storeId, $storeIdArray))
					{
						$this->updateDocumentDownloadCounter($documentId);

						$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $documentSize));

						// Add log when download
						$logData = array(
							'user_id'   => $user->id,
							'event'     => 'document.download',
							'item_id'   => $documentId,
							'doc_id'    => $documentId,
							'value'     => $documentSize,
							'reference' => implode(',', $fileIdArray)
						);

						JUDownloadFrontHelperLog::addLog($logData);
					}
				}
				// End - Zip file

				$categoryObject = JUDownloadHelper::getCategoryById($categoryId);
				$zipFileName    = $this->makeSafeFileName($categoryObject->title) . ".zip";
			}
			//Download one document
			else
			{
				/*
				 * Download document when not isset cat_id
				 * Download document we only get first element of documentIds array
				 */
				$documentId     = $documentIdArray[0];
				$documentObject = JUDownloadHelper::getDocumentById($documentId);

				$documentTitle  = $this->filterFileFolderName($documentObject->title);
				$fileObjectList = $this->getAllFilesOfDocument($documentId);

				// Zip file even document has only one file, we can change this later here...
				// Create zip download package.
				$zip     = new Zip();
				$zipFile = true;

				// Parse zip comment
				$zipComment = $this->parseCommentTxt($zipCommentConfig, $categoryId, $documentId);

				$documentTitle = trim($documentTitle);
				//Add document title as a folder contains files
				$zip->addDirectory($documentTitle);

				$fileIdArray  = array();
				$documentSize = 0;
				foreach ($fileObjectList AS $fileObject)
				{
					// One document allow to download by version
					$physicalFilePath = $this->getPhysicalFilePath($fileObject->id, $version);

					if (JFile::exists($physicalFilePath))
					{
						$filePathInZip = $documentTitle . '/' . $this->filterFileFolderName($fileObject->rename);

						// Add file extension to file path, if the extension is not the same original file
						$fileExtOri   = JFile::getExt($physicalFilePath);
						$fileExtInZip = JFile::getExt($filePathInZip);
						if ($fileExtInZip != $fileExtOri)
						{
							$filePathInZip = $filePathInZip . '.' . $fileExtOri;
						}
						$filePathInZip = trim($filePathInZip);

						$zip->addLargeFile($physicalFilePath, $filePathInZip);
						$documentSize += $fileObject->size;
						if (!in_array($storeId, $storeIdArray))
						{
							$this->updateFileDownloadCounter($fileObject->id, $version);
						}
					}
					$fileIdArray[] = $fileObject->id;
				}
				// End - Zip file

				if (!in_array($storeId, $storeIdArray))
				{
					$this->updateDocumentDownloadCounter($documentId);

					$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $documentSize));

					// Add log
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.download',
						'item_id'   => $documentId,
						'doc_id'    => $documentId,
						'value'     => $documentSize,
						'reference' => implode(',', $fileIdArray) . ($version ? ':' . $version : '')
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}

				$zipFileName = $this->makeSafeFileName($documentObject->title . " " . $version) . ".zip";
			}
		}
		elseif ($type == 'file')
		{
			$fileIdArray = $itemIdArray;
			$documentId  = $parentId;
			//Download multi files in one document
			if (count($fileIdArray) > 1)
			{
				$documentObject = JUDownloadHelper::getDocumentById($documentId);

				$documentTitle  = $this->filterFileFolderName($documentObject->title);
				$mainCategoryId = JUDownloadFrontHelperCategory::getMainCategoryId($documentId);

				$zip     = new Zip();
				$zipFile = true;

				// Parse zip comment
				$zipComment = $this->parseCommentTxt($zipCommentConfig, $mainCategoryId, $documentId);

				$documentTitle = trim($documentTitle);
				$zip->addDirectory($documentTitle);

				$documentSize = 0;
				foreach ($fileIdArray AS $fileId)
				{
					// One document allow to download by version
					$physicalFilePath = $this->getPhysicalFilePath($fileId, $version);

					if (JFile::exists($physicalFilePath))
					{
						$fileObject    = $this->getFileObject($fileId);
						$filePathInZip = $documentTitle . '/' . $this->filterFileFolderName($fileObject->rename);

						// Add file extension to file path, if the extension is not the same original file
						$fileExtOri   = JFile::getExt($physicalFilePath);
						$fileExtInZip = JFile::getExt($filePathInZip);
						if ($fileExtInZip != $fileExtOri)
						{
							$filePathInZip = $filePathInZip . '.' . $fileExtOri;
						}
						$filePathInZip = trim($filePathInZip);

						$zip->addLargeFile($physicalFilePath, $filePathInZip);
						$documentSize += $fileObject->size;
						if (!in_array($storeId, $storeIdArray))
						{
							$this->updateFileDownloadCounter($fileId, $version);
						}
					}
				}
				// End - Zip file

				// Sort $fileIdArrayInTmpZip before add log and store it to tmp files table
				sort($fileIdArray);

				if (!in_array($storeId, $storeIdArray))
				{
					$this->updateDocumentDownloadCounter($documentId);

					$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $documentSize));

					// Add log
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.download',
						'item_id'   => $documentId,
						'doc_id'    => $documentId,
						'value'     => $documentSize,
						'reference' => implode(',', $fileIdArray) . ($version ? ':' . $version : '')
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}

				$zipFileName = $this->makeSafeFileName($documentObject->title . " " . $version) . ".zip";
			}
			//Download one file
			elseif (count($fileIdArray) == 1)
			{
				$zipOneFile = $params->get('zip_one_file', 0);

				$fileId     = $itemIdArray[0];
				$fileObject = $this->getFileObject($fileId);

				// One file allow to download by version
				$physicalFilePath = $this->getPhysicalFilePath($fileId, $version);
				$physicalFilePath = JPath::clean($physicalFilePath);

				$fileExtOri = JFile::getExt($physicalFilePath);

				$configAllowZipFile = $params->get('allow_zip_file', 1);

				// Download one file no zipped (File can be zip file or not, but we still using var $zipFileName for general download file name)
				if ($fileExtOri == "zip" || !$zipOneFile || !$configAllowZipFile)
				{
					$zipFile = false;

					// In this case, $zipFileName is file name(zipped or not)
					$zipFileName = $this->filterFileFolderName($fileObject->rename);
					$zipFileName = $this->makeSafeFileName(JFile::stripExt($zipFileName) . " " . $version) . "." . JFile::getExt($zipFileName);
					// Add file extension to file path, if the extension is not the same original file
					$fileExtInZip = JFile::getExt($zipFileName);
					if ($fileExtInZip != $fileExtOri)
					{
						$zipFileName = $zipFileName . '.' . $fileExtOri;
					}
					$zipFileName = trim($zipFileName);
				}
				// Download one file zipped
				else
				{
					// Initialize zip object.
					$zip     = new Zip();
					$zipFile = true;

					$mainCategoryId = JUDownloadFrontHelperCategory::getMainCategoryId($documentId);
					// Parse zip comment
					$zipComment = $this->parseCommentTxt($zipCommentConfig, $mainCategoryId, $documentId);

					if (JFile::exists($physicalFilePath))
					{
						$filePathInZip = $this->filterFileFolderName($fileObject->rename);

						// Add file extension to file path, if the extension is not the same original file
						$fileExtInZip = JFile::getExt($filePathInZip);
						if ($fileExtInZip != $fileExtOri)
						{
							$filePathInZip = $filePathInZip . '.' . $fileExtOri;
						}
						$filePathInZip = trim($filePathInZip);

						$zip->addLargeFile($physicalFilePath, $filePathInZip);
					}
					// End - Zip file

					$zipFileName = $this->filterFileFolderName($fileObject->rename);
					$zipFileName = $this->makeSafeFileName(JFile::stripExt($zipFileName) . " " . $version) . ".zip";
					$zipFileName = trim($zipFileName);
				}

				if (!in_array($storeId, $storeIdArray))
				{
					$this->updateDocumentDownloadCounter($documentId, $version);
					$this->updateFileDownloadCounter($fileId, $version);

					$dispatcher->trigger('onAfterDownloadDocument', array($documentId, $fileIdArray, $fileObject->size));

					// Add log
					$logData = array(
						'user_id'   => $user->id,
						'event'     => 'document.download',
						'item_id'   => $documentId,
						'doc_id'    => $documentId,
						'value'     => $fileObject->size,
						'reference' => $fileId . ($version ? ':' . $version : '')
					);

					JUDownloadFrontHelperLog::addLog($logData);
				}
			}
		}
		// Only support download file/document, invalid type -> return false
		else
		{
			return false;
		}

		$serverTime      = JFactory::getDate()->toSql();
		$serverTimeStamp = strtotime($serverTime);

		// Store ID of download file(s) into session
		if ($noCountingDownloadSecond > 0)
		{
			$storeIdArray                   = (array) $app->getUserState('com_judownload.download.storeid');
			$storeIdArray[$serverTimeStamp] = $storeId;
			$storeIdArray                   = array_unique($storeIdArray);
			$app->setUserState('com_judownload.download.storeid', $storeIdArray);
		}

		// Last download time to calculate download interval
		$session = JFactory::getSession();
		$session->set('judl-last-download-time', $serverTime);

		// If use zip class to zip files, set comment then close the archive
		if ($zipFile)
		{
			// Set comment for zip file
			$zip->setComment($zipComment);

			// Close the archive
			$zip->finalize();
		}

		// Send email by event for each document when download
		$docIdArray = array();
		if ($type == 'file')
		{
			$docIdArray[] = $parentId;
		}
		else
		{
			$docIdArray = $itemIdArray;
		}

		$docIdArray = array_unique($docIdArray);
		//Send mail by event
		foreach ($docIdArray AS $docId)
		{
			JUDownloadFrontHelperMail::sendEmailByEvent('document.download', $docId);
		}

		// Download ZIPPED file
		if ($zipFile)
		{
			// Directly download(from zip resource by PHP)
			$resourceFilePath   = $zip->getZipFile();
			$transport          = 'php';
			$speed              = (int) $params->get('max_download_speed', 200);
			$resume             = $params->get('resume_download', 1);
			$downloadMultiParts = $params->get('download_multi_parts', 1);

			$downloadResult = JUDownloadHelper::downloadFile($resourceFilePath, $zipFileName, $transport, $speed, $resume, $downloadMultiParts);

			if ($downloadResult !== true)
			{
				$this->setError($downloadResult);

				return false;
			}
		}
		// Download ONE NO ZIPPED file, in this case $zipFileName is the download file name, file can be zip file or not
		else
		{
			// Directly download
			$transport          = $downloadOneFileNoZippedMode;
			$speed              = (int) $params->get('max_download_speed', 200);
			$resume             = $params->get('resume_download', 1);
			$downloadMultiParts = $params->get('download_multi_parts', 1);

			$downloadResult = JUDownloadHelper::downloadFile($physicalFilePath, $zipFileName, $transport, $speed, $resume, $downloadMultiParts);

			if ($downloadResult !== true)
			{
				$this->setError($downloadResult);

				return false;
			}
		}

		return true;
	}
Example #7
0
 function download_archive()
 {
     global $wpdb, $current_user;
     if (!is_user_logged_in()) {
         exit;
     }
     $user_ID = $_GET['id'];
     $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
     $path = '' . SP_CDM_UPLOADS_DIR_URL . '' . $user_ID . '/';
     $return_file = "Account.zip";
     $zip = new Zip();
     $r = $wpdb->get_results($wpdb->prepare("SELECT *  FROM " . $wpdb->prefix . "sp_cu   where uid = %d  order by date desc", $user_ID), ARRAY_A);
     //@unlink($dir.$return_file);
     for ($i = 0; $i < count($r); $i++) {
         $zip->addFile(file_get_contents($dir . $r[$i]['file']), $r[$i]['file'], filectime($dir . $r[$i]['file']));
     }
     $zip->finalize();
     // as we are not using getZipData or getZipFile, we need to call finalize ourselves.
     $zip->setZipFile($dir . $return_file);
     header("Location: " . $path . $return_file . "");
 }
Example #8
0
 /**
  * Creates a new archive with the specified name and files
  * @param string $name Path to the archive with name and extension
  * @param array $files A numeric array of files
  * @param string $replace
  * @return int How many files has been successfully handled
  */
 public function getArchive($name, array $files, $replace = ABSPATH)
 {
     set_time_limit(300);
     if (!class_exists('Zip', false)) {
         /** @var backupBup $backup */
         $backup = $this->getModule();
         $backup->loadLibrary('zip');
     }
     $zip = new Zip();
     $zip->setZipFile($name);
     foreach ($files as $file) {
         $filename = str_replace($replace, '', $file);
         if (file_exists($file) && is_readable($file) && (substr(basename($file), 0, 3) != 'pcl' && substr($file, -2) != 'gz')) {
             $stream = @fopen($file, 'rb');
             if ($stream) {
                 $zip->addLargeFile($stream, $filename);
             }
         }
     }
     $zip->finalize();
     /* backward */
     return rand(100, 1000);
 }
Example #9
0
function sp_Admin_uploadFile($files, $user_ID)
{
    global $wpdb;
    $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
    $count = sp_array_remove_empty($files['dlg-upload-file']['name']);
    if ($history == 1) {
        $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
        $filename = '' . sp_client_upload_filename($user_ID) . '' . $files['dlg-upload-file']['name'][0] . '';
        $filename = strtolower($filename);
        $filename = sanitize_file_name($filename);
        $filename = remove_accents($filename);
        $target_path = $dir . $filename;
        move_uploaded_file($files['dlg-upload-file']['tmp_name'][0], $target_path);
        $ext = preg_replace('/^.*\\./', '', $filename);
        if (get_option('sp_cu_user_projects_thumbs_pdf') == 1 && class_exists('imagick')) {
            $info = new Imagick();
            $formats = $info->queryFormats();
            if (in_array(strtoupper($ext), $formats)) {
                cdm_thumbPdf($target_path);
            }
        }
        return $filename;
    } else {
        if (count($count) > 1) {
            //echo $count;
            //	echo '<pre>';
            //print_r($files);exit;
            //echo '</pre>';
            $fileTime = date("D, d M Y H:i:s T");
            $zip = new Zip();
            for ($i = 0; $i < count($files['dlg-upload-file']['name']); $i++) {
                if ($files['dlg-upload-file']['error'][$i] == 0) {
                    $filename = '' . sp_client_upload_filename($user_ID) . '' . $files['dlg-upload-file']['name'][$i] . '';
                    $filename = strtolower($filename);
                    $filename = sanitize_file_name($filename);
                    $filename = remove_accents($filename);
                    $target_path = $dir . $filename;
                    move_uploaded_file($files['dlg-upload-file']['tmp_name'][$i], $target_path);
                    $zip->addFile(file_get_contents($target_path), $filename, filectime($target_path));
                }
            }
            $zip->finalize();
            // as we are not using getZipData or getZipFile, we need to call finalize ourselves.
            $return_file = "" . rand(100000, 100000000000) . "_Archive.zip";
            $zip->setZipFile($dir . $return_file);
            return $return_file;
        } else {
            $dir = '' . SP_CDM_UPLOADS_DIR . '' . $user_ID . '/';
            $filename = '' . sp_client_upload_filename($user_ID) . '' . $files['dlg-upload-file']['name'][1] . '';
            $filename = strtolower($filename);
            $filename = sanitize_file_name($filename);
            $filename = remove_accents($filename);
            $target_path = $dir . $filename;
            move_uploaded_file($files['dlg-upload-file']['tmp_name'][1], $target_path);
            $ext = preg_replace('/^.*\\./', '', $filename);
            if (get_option('sp_cu_user_projects_thumbs_pdf') == 1 && class_exists('imagick')) {
                $info = new Imagick();
                $formats = $info->queryFormats();
                if (in_array(strtoupper($ext), $formats)) {
                    cdm_thumbPdf($target_path);
                }
            }
            return $filename;
        }
    }
}