bool isZIPArchive(wstring dir, wstring &arch_name){
		vector<wstring>dirs;
		bool isArch = false;
		
		dirs = toDirVector(dir);
		arch_name = dirs[0];

		CZipArchive zip;
		for(int i=1;i<dirs.size();i++){
			arch_name = arch_name + L"\\" + dirs[i];
			
			
			try{
				
				zip.Open(arch_name.c_str(), CZipArchive::OpenMode::zipOpenReadOnly);
				isArch = true;
				zip.Close();
				break;
			}catch(Exception ^){
				zip.CloseFile();
				//continue
			}
		}
		/*if(!zip.IsClosed())
			zip.Close();*/
		//TODO: check if there is opened file
		_fcloseall();
		return isArch;
	}
Exemple #2
0
int WINAPI ZipFile(const char *pszPath,const char *pszZipFile)
{
	try
	{
		CZipArchive zip;//压缩

		CString strZip,strPath;

		strZip.Format("%s",pszZipFile);
		strPath.Format("%s",pszPath);

		zip.Open(strZip, CZipArchive::create, 0  );
		if(zip.AddNewFile(pszPath, 8) == FALSE)
		{
			zip.Close();
			return 0;
		}
		zip.Close();

	}
	catch(...)
	{
		return 0;
	}
	return 1;
}
void DocXDocumentStore::GetDocumentTexts(const CStdString& sFileName, std::vector<std::string>& vDocumentTexts) const
{
	vDocumentTexts.clear();

	CZipArchive zipArchive;
	zipArchive.Open(sFileName, CZipArchive::zipOpenReadOnly);
	if( !zipArchive.IsClosed() )
	{
		CZipWordArray ar;
		zipArchive.FindMatches( L"word\\\\*.xml", ar );
		for( int uIndex = 0; uIndex < ar.GetSize(); uIndex++ )
		{
			CZipFileHeader fhInfo;
			if( zipArchive.GetFileInfo( fhInfo, ar[uIndex] ) )
			{
				const CZipString fileName( fhInfo.GetFileName() );
				if( fileName.find_first_of( '\\' ) == fileName.find_last_of( '\\' ) )
				{
					C2007DocFile mf;
					zipArchive.ExtractFile( ar[uIndex], mf );			
					const CStdStringA sDocText = mf.GetWTInnerText();
					if( sDocText.size() > 0 )
						vDocumentTexts.push_back( sDocText );
				}
			}
		}
		zipArchive.Flush();
		zipArchive.Close();
	}
}
Exemple #4
0
int WINAPI UnZipFile(const char *pszZipFile,const char *pszPath)
{
	if( pszZipFile == NULL || pszPath == NULL )
		return 0;

	CString strZip,strPath;
	strZip.Format("%s",pszZipFile);
	strPath.Format("%s",pszPath);

	CZipArchive zip;
	zip.Open(strZip, CZipArchive::open);
	for (int i = 0; i < zip.GetNoEntries(); i++)//输出文件(!!!没有文件夹)
	{
		if( !zip.ExtractFile(WORD(i) , strPath) )
		{ 
			break;
		}
	}
	zip.Close();

	return 1;
}
Exemple #5
0
bool CSimpleZip::Extract(std::string strDest,std::string strZipFile)
{
	CZipString szArchive;
	szArchive=CZipString(strZipFile);
	CZipString szPath = CZipString(strDest);

	CZipArchive zip;
	
	int iVolumeSize = 0;
	int iMode = CZipArchive::zipOpen;


	try
	{
		zip.Open(szArchive, iMode, iVolumeSize);
	}
	catch(...)
	{
		return FALSE;
	}

	bool ok=true;
	for (int k = 0; k < zip.GetCount(); ++k)
	{
		
		try
		{
			ok = zip.ExtractFile(k, szPath, TRUE);
		}
		catch (...)
		{					
			ok = false;
			break;
		}
	}
	zip.Close();
	return ok;
}
Exemple #6
0
void WorkerThread::runRezip() {
	emit(beginRunRezip());
	emit(stageEvent("Finding and saving modified game data"));
	
	emit(infoEvent("Identifying modified files (including previously modified files)"));
	QMap<QString, uint32_t> newChecksums;
	collectFiles(m_tempPath, &newChecksums);
	QStringList modified; // TODO: also determine removed files?
	QMapIterator<QString, uint32_t> i(newChecksums);
	while (i.hasNext()) {
		i.next();
		if(!m_checksums.contains(i.key()) || m_checksums[i.key()] != i.value()) { modified << i.key(); }
	}
	
	if(modified.empty()) {
		emit(infoEvent("No modified files found"));
		return;
	}
	
	emit(infoEvent("Rezipping modified files"));

	QString gameFileBase = QFileInfo(m_gameFileName).baseName();
	QString diffFileName = m_dataPath + "/" + gameFileBase + __WHDRun__DiffSuffix;
	CZipArchive zip;
	try {
		zip.Open(diffFileName.toUtf8(), CZipArchive::zipCreate);

		// TODO: review that path finding stuff some time.
		QDir tempDir(m_tempPath); tempDir.makeAbsolute();
		foreach(QString externalPath, modified) {
			QDir externalDir(externalPath); externalDir.makeAbsolute();
			QString internalPath = tempDir.relativeFilePath(externalDir.absolutePath());
			zip.AddNewFile((LPCTSTR)externalPath.toUtf8(),
				(LPCTSTR)internalPath.toUtf8(), CZipCompressor::levelBest);
		}

		zip.Close();
	} catch(CZipException ex) {
Exemple #7
0
bool CSimpleZip::Add( const void* src, const unsigned int& srcSize, void* dst, unsigned int& dstSize, std::string& szErrmsg)
{
	if ( NULL==src )
	{
		szErrmsg =  "CSimpleZip: Invalid source.";
		return false;
	}

	bool bRet = false;
	CZipMemFile mfIn;
	CZipMemFile mfOut;
	CZipArchive zip;
	try
	{
		mfIn.Write(src, srcSize);
		zip.Open(mfOut, CZipArchive::zipCreate);
		zip.AddNewFile(mfIn, _T("temp.txt"));
		zip.Close();
		int nLen = (int)mfOut.GetLength();
		if ( NULL==dst || dstSize<nLen )
		{
			dstSize = nLen;
			szErrmsg = "CSimpleZip: The size of destination buffer is too small.";
			return false;
		}
		BYTE* b = mfOut.Detach();
		memcpy_s(dst, dstSize, b, nLen);
		dstSize = nLen;
		free(b);
		bRet = true;
	}
	catch(CZipException& e)
	{
		if (!zip.IsClosed())
			zip.Close();
		szErrmsg =  e.GetErrorDescription().c_str();
	}
	catch(...)
	{
		if (!zip.IsClosed())
			zip.Close();
		szErrmsg =  "CSimpleZip: failed to add, catch exception.";
	}
	return bRet;
}
BOOL CPackage::unZip()
{
	CZipArchive cZip;
	CString		csFile;

	// If there is no fragement, assume package unzipped
	if (m_uFrags == 0)
		// No fragment
		return TRUE;
	csFile.Format( _T( "%s\\%s\\%s"), getDownloadFolder(), m_csID, OCS_DOWNLOAD_BUILD);
	try
	{
		cZip.Open( csFile);
		for(ZIP_INDEX_TYPE i=0; i<cZip.GetCount();i++)
			cZip.ExtractFile(i, m_csPath);
		cZip.Close();
		// Create package ID file into unzip directory only if not in store action 
		if (m_csAction != OCS_DOWNLOAD_ACTION_STORE)
		{
			CStdioFile cFile;

			csFile.Format( _T( "%s\\%s"), m_csPath, OCS_DOWNLOAD_PACKAGE_ID);
			if (cFile.Open( csFile, CFile::modeCreate|CFile::modeWrite|CFile::typeText))
			{
				cFile.WriteString( m_csID);
				cFile.Close();
			}
		}
	}
	catch (CException *pE)
	{		
		pE->Delete();
		cZip.Close( CZipArchive::afAfterException);
		return FALSE;			
	}
	catch (std::exception *pEx)
	{
		cZip.Close( CZipArchive::afAfterException);
		delete pEx;
		return FALSE;			
	}
	return TRUE;
}
Exemple #9
0
bool CSimpleZip::Add(std::string strZipFile,std::list<std::string>& lstFile,std::string strRootPath,bool bFullPath)
{
	CZipArchive zip;

	
	CZipString szArchive;
	int iVolumeSize = 0;
	int iMode = CZipArchive::zipOpen;
	
	szArchive =CZipString(strZipFile);
	if (!ZipPlatform::FileExists(szArchive))
					iMode = CZipArchive::zipCreate;


	CZipPathComponent zpc(szArchive);
	SpanCallback span;
	zip.SetSpanCallback(&span);
	try
	{
		zip.Open(szArchive, iMode, iVolumeSize);
	}
	catch(...)
	{
		return FALSE;
	}
	zip.SetRootPath(strRootPath.c_str());

	FILELIST lFiles;
	
	for(std::list<std::string>::iterator it =lstFile.begin();it!=lstFile.end();it++)
	{
		std::string strFileName;
		strFileName =*it;
		lFiles.push_back(CZipString(strFileName));
	}
	FILELISTADD rev;
	for (FILELISTIT it = lFiles.begin(); it != lFiles.end(); ++it)				
	{
		CZipString sz = zip.PredictFileNameInZip(*it, bFullPath);
		if (!sz.IsEmpty())
			rev.push_back(CZipAddFileInfo(*it, sz));
	}
	lFiles.clear();
//	rev.sort(std::greater<CZipAddFileInfo>());
	FILELISTADDIT it1;
	int iSmartLevel = CZipArchive::zipsmSafeSmart;


	for (it1 = rev.begin(); it1 != rev.end(); ++it1)
	{	
		if (zip.AddNewFile((*it1).m_szFilePath, 5, bFullPath, iSmartLevel))
		{
			
			printf ("%s added\n", (LPCTSTR)(*it1).m_szFileNameInZip);
		}
		else
			printf ("%s not added\n", (LPCTSTR)(*it1).m_szFilePath);
	}

	zip.Close();
	return TRUE;
}
Exemple #10
0
void FindInZip(CZipArchive& zip, FILELIST& l, CZipWordArray& n)
{

	for (FILELISTIT it = l.begin(); it != l.end(); ++it)
		zip.FindMatches(*it, n);
}
BOOL AppMainApp::InitInstance()
{
	pMainDialogWindowCrypt = NULL;
	pMainDialogWindow=NULL;
	if (!InitATL()){
		return FALSE;
	}
	{// На первый запуск...
		char sz1[128]={0};
		char sz2[128]="1";
		CString sAddCal;
		GetCommandLineParameter("addcal",sAddCal);
		if(sAddCal!=""){
			strcpy(sz1,sAddCal);
			SetRegSetting("", "FR_addCalendar", sz1);
			return FALSE;
		}
		CString sAddClo;
		GetCommandLineParameter("addclo",sAddClo);
		if(sAddClo!=""){
			strcpy(sz2,sAddClo);
			SetRegSetting("", "FR_addClock", sz2);
			return FALSE;
		}
		GetRegSetting("", "FR_addClock", sz1, sizeof(sz1));
		bAddOnStartClo=atol(sz1);
		GetRegSetting("", "FR_addCalendar", sz2, sizeof(sz2));
		bAddOnStartCal=atol(sz2);
	}
	{//setup_file
		// Регистрируем файл
		char szWkmRegistered[32]={0};
		GetRegSetting("", "wpc_setupRegistered", szWkmRegistered, sizeof(szWkmRegistered));
		if(szWkmRegistered[0]==0){
			strcpy(szWkmRegistered,"yes");
			SetRegSetting("", "wpc_setupRegistered", szWkmRegistered);
			RegisterExtension("wpc_setup","WireChanger setup file","-setup_file=");
		}
		CString sSetupFile;
		GetCommandLineParameter("setup_file",sSetupFile);
		if(sSetupFile!=""){
			if(isFileExist(sSetupFile)){
				CString sContent,sKeyPart;
				ReadFile(sSetupFile,sContent);
				CString sXML=CDataXMLSaver::GetInstringPart("<SETUP>","</SETUP>",sContent);
				if(sXML==""){
					sKeyPart=sContent;
				}
				// Делаем что сказано...
				if(sKeyPart!=""){
					SaveFile(GetUserFolder()+LICENSE_KEY_FILE,sKeyPart);
					AfxMessageBox(_l("Registration info installed successfully\nRestart WireChanger to see changes"));
				}
			}else{
				AfxMessageBox(Format("Reading setup file error: '%s' not found!",sSetupFile));
			}
			return FALSE;
		}
	}
	CString sExe;
	GetCommandLineParameter("add",sExe,0);
	if(sExe!=""){_XLOG_
		CString sNewFile=CString(GetApplicationDir())+WP_TEMPLATE+"\\"+GetPathPart(sExe,0,0,1,1);
		BOOL b=CopyFile(sExe,sNewFile,TRUE);
		if(!b){
			AfxMessageBox(_l("Error")+": "+_l("Widget already exist"));
		}
		return FALSE;
	}
    // Глобальные настройки
    CString sDats;
    ReadFile(CString(GetApplicationDir())+"inits.txt",sDats);
    AppName()=PROGNAME;
    AddDefsWallps()=1;
	AddDefsInteract()=1;
	if(sDats.GetLength()){
		CString sAppName=CDataXMLSaver::GetInstringPart("app:[","]",sDats);
		if(sAppName.GetLength()!=0){
			AppName()=sAppName;
		}
		AddDefsWallps()=atol(CDataXMLSaver::GetInstringPart("defs:[","]",sDats));
		AddDefsInteract()=atol(CDataXMLSaver::GetInstringPart("intr:[","]",sDats));
	}
    //===========
	CString sConsoleMode;
	GetCommandLineParameter("console",sConsoleMode);
	CString sIniFileInfo;
	ReadFile(CString(GetApplicationDir())+"install.ini",sIniFileInfo);
	if(sIniFileInfo!=""){
		sIniFileInfo+="\r\n";
	}
	if(sConsoleMode=="yes"){
		CString sConsoleSave,sConsoleRest;
		GetCommandLineParameter("wpsave",sConsoleSave);
		GetCommandLineParameter("wprestore",sConsoleRest);
		if(sConsoleSave=="yes"){
			if(sIniFileInfo.Find("[Main]")==-1){
				sIniFileInfo+="[Main]\r\n";
			}
			
			CString sAID,sDte;
			GetCommandLineParameter("affid",sAID);
			GetCommandLineParameter("date",sDte);
			if(sIniFileInfo.Find("AffId=")==-1){
				sIniFileInfo+=CString("AffId=")+sAID+"\r\n";
			}
			if(sIniFileInfo.Find("Date=")==-1){
				sIniFileInfo+=CString("Date=")+sDte+"\r\n";
			}
			if(sIniFileInfo.Find("CPD-W")==-1){
				CRegKey key;
				key.Open(HKEY_CURRENT_USER, "Control Panel\\Desktop");
				if(key!=NULL){
					char szTemp[MAX_PATH]="";
					DWORD lSize,dwType=0;
					lSize = MAX_PATH;
					if(RegQueryValueEx(key.m_hKey,"Wallpaper",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
						sIniFileInfo+="CPD-W=<";
						sIniFileInfo+=szTemp;
						sIniFileInfo+=">\r\n";
					}
					lSize = MAX_PATH;
					if(RegQueryValueEx(key.m_hKey,"WallpaperStyle",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
						sIniFileInfo+="CPD-WS=<";
						sIniFileInfo+=szTemp;
						sIniFileInfo+=">\r\n";
					}
					lSize = MAX_PATH;
					if(RegQueryValueEx(key.m_hKey,"TileWallpaper",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
						sIniFileInfo+="CPD-WT=<";
						sIniFileInfo+=szTemp;
						sIniFileInfo+=">\r\n";
					}
					lSize = MAX_PATH;
					if(RegQueryValueEx(key.m_hKey,"SCRNSAVE.EXE",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
						sIniFileInfo+="CPD-SS=<";
						sIniFileInfo+=szTemp;
						sIniFileInfo+=">\r\n";
					}
				}
				{// На дефолтного
					CRegKey key;
					key.Open(HKEY_USERS, ".DEFAULT\\Control Panel\\Desktop");
					if(key!=NULL){
						char szTemp[MAX_PATH]="";
						DWORD lSize,dwType=0;
						lSize = MAX_PATH;
						if(RegQueryValueEx(key.m_hKey,"Wallpaper",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
							sIniFileInfo+="DCPD-W=<";
							sIniFileInfo+=szTemp;
							sIniFileInfo+=">\r\n";
						}
						lSize = MAX_PATH;
						if(RegQueryValueEx(key.m_hKey,"WallpaperStyle",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
							sIniFileInfo+="DCPD-WS=<";
							sIniFileInfo+=szTemp;
							sIniFileInfo+=">\r\n";
						}
						lSize = MAX_PATH;
						if(RegQueryValueEx(key.m_hKey,"TileWallpaper",NULL, &dwType,(LPBYTE)szTemp, &lSize)== ERROR_SUCCESS){
							sIniFileInfo+="DCPD-WT=<";
							sIniFileInfo+=szTemp;
							sIniFileInfo+=">\r\n";
						}
					}
				}
			}
			if(sIniFileInfo.Find("UserData")==-1 || sIniFileInfo.Find("ConfigFile")==-1){
				sIniFileInfo+="ConfigFile=";
				sIniFileInfo+=objSettings.sIniFile;
				sIniFileInfo+="\r\n";
				sIniFileInfo+="UserData=";
				sIniFileInfo+=GetPathPart(objSettings.sIniFile,1,1,0,0);
				sIniFileInfo+="\r\n";
			}
			SaveFile(CString(GetApplicationDir())+"install.ini",sIniFileInfo);
		}else if(sConsoleRest=="yes"){
			if(sIniFileInfo==""){
				return 0;
			}
			RestoreWP(sIniFileInfo,1);
		}
		return FALSE;
	}
	CString sWait;
	GetCommandLineParameter("wait",sWait);
	DWORD dwStartWait=GetTickCount();
	if(sWait=="yes"){
		while(CheckProgrammRunState(NULL, UNIQUE_TO_TRUSTEE, false) && GetTickCount()-dwStartWait<180000){
			Sleep(1000);
		}
	}
	// Для нормально работы клонов
	if(IsThisProgrammAlreadyRunning()){
		// || IsOtherProgrammAlreadyRunning("WireChanger")
		DWORD dwTarget=BSM_APPLICATIONS;
		BroadcastSystemMessage(BSF_FORCEIFHUNG | BSF_IGNORECURRENTTASK | BSF_POSTMESSAGE, &dwTarget, iWM_THIS, WPARAM(99), LPARAM(99));
		return FALSE;
	}
	// Столбим уникальное за компьютером...
	CheckProgrammRunState("WC3",UNIQUE_TO_COMPUTER,1,"");
	CString sRestore;
	GetCommandLineParameter("restore",sRestore);
	if(sRestore!="" && isFileExist(sRestore)){
		CString sIniPath=GetPathPart(objSettings.sIniFile,1,1,0,0);
		{//Первый проход
			CZipArchive zipFile;
			if(zipFile.Open(sRestore)){
				ZIP_FIND_DATA pFind;
				HANDLE hSearch=zipFile.FindFirstFile("*.*",&pFind);
				while(zipFile.FindNextFile(hSearch, &pFind)){
					CString sFileName=pFind.szFileName;
					if(sFileName!=""){
						CZipFile zI;
						if(zipFile.GetFile(pFind.nDirIndex,&zI)){
							DeleteFile(sIniPath+sFileName);
							zI.SafeSaveToDosk(sIniPath+sFileName,0);
						}
					}
				}
				zipFile.FindClose(hSearch);
				zipFile.Close();
			}
		}
	}
	AfxEnableControlContainer();
	AfxInitRichEdit();
#if WINVER<=0x0050
#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif
#endif
	OleInitialize(NULL);
	//
	CRYPT_START
	objSettings.sLikUser="";
	objSettings.sLikKey="";
	HANDLE hLicenseFile=::CreateFile(GetUserFolder()+LICENSE_KEY_FILE, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (!hLicenseFile || hLicenseFile==INVALID_HANDLE_VALUE){
		// Из локального каталога!
		hLicenseFile=::CreateFile(CString(GetApplicationDir())+LICENSE_KEY_FILE, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	}
	if (hLicenseFile && hLicenseFile!=INVALID_HANDLE_VALUE){
		DWORD dwRead=0;
		char szKey[2048]="";
		objSettings.sLikKey="";
		::ReadFile(hLicenseFile, szKey, sizeof(szKey), &dwRead, NULL);
		objSettings.sLikUser=CDataXMLSaver::GetInstringPart("user:[","]",szKey);
		objSettings.sLikKey=CDataXMLSaver::GetInstringPart("key:[","]",szKey);
		::CloseHandle(hLicenseFile);
	}
#ifdef LIC_HARDCODED_U
	objSettings.sLikUser=LIC_HARDCODED_U;
#endif
#ifdef LIC_HARDCODED_K
	objSettings.sLikKey=LIC_HARDCODED_K;
#endif
	//if(sIniFileInfo.Find("WireChangerEF")!=-1){
		/*
		WC5Elefun	CCC2-HJ3S-88A6-C4TP
		*/
		/*
		WC5IPv6	4HVF-9XF6-DGQ2-94U2	
		*/
		/*
		WK999IPv6	EJCM-VNR7-GZ8F
		*/
		/*Mapi2Pop3
		IPv6	GT8N-6747-AGDM
		*/
		/*
		// Здесь поддержан элефан
		USE_ELEFUN=1;
		objSettings.sLikUser="******";
		objSettings.sLikKey=Recrypt("\xd3\x4c\xc3\x24\x84\x53\x3e\x2a\x2c\x21\x9e\x24\x48\x34\xb5\xb4");//"CCC2-HJ3S-88A6-C4TP";// EXECryptor_DecryptStr()?
		*/
	//}
	UpdateTrialityStatus(objSettings.sLikUser,objSettings.sLikKey);
	if(objSettings.iLikStatus<0){
		CSettings* objAntiDebug=0;
		objAntiDebug->ApplySettings();
		return FALSE;
	}
	CRYPT_END
	objSettings.Load();
	if(sConsoleMode=="help"){
		ShowHelp("Overview");
		return 0;
	}
	{// грузим ddown
		CBitmap bpTmp;
		bpTmp.LoadBitmap(IDB_DDOWN_A);
		_bmp().AddBmpRaw("DDOWN",&bpTmp,GetBitmapSize(bpTmp));
	}
	{// грузим remd
		CBitmap bpTmp;
		bpTmp.LoadBitmap(IDB_REMIND_A);
		_bmp().AddBmpRaw("REMINDER",&bpTmp,GetBitmapSize(bpTmp));
	}
	theApp.MainImageList.Create(16, 16, ILC_COLOR16 | ILC_MASK, 0, 2);
	// Основные иконки
	AddBitmapToIList(theApp.MainImageList,IDB_IMAGELIST);
	for(int i=0;i<theApp.MainImageList.GetImageCount();i++){
		HICON hIcon=theApp.MainImageList.ExtractIcon(i);
		_bmp().AddBmp(_IL(i),hIcon);
		ClearIcon(hIcon);
	}
	_bmp().AddBmpRaw(IDB_BM_LOGO,CSize(LOGO_W,LOGO_H));
	// Пытаемся к пустому окну захимичится
	rFakedRect.SetRect(-10,0,0,0);
	LPCTSTR szClass = AfxRegisterWndClass(NULL);
	m_pFakeWnd = new CWnd;
	m_pFakeWnd->CreateEx(0, szClass, ROOT_WND_NAME, 0, rFakedRect, NULL, 0);
	m_pFakeWnd->ShowWindow(SW_HIDE);
	m_pFakeWnd->EnableWindow(FALSE);
	m_pFakeWnd->SetIcon(::AfxGetApp()->LoadIcon(MAIN_ICON),TRUE);
	m_pFakeWnd->SetIcon(::AfxGetApp()->LoadIcon(MAIN_ICON),FALSE);
	HotkeysSkipDD()=1;
	// Если при запуске небыло найдено ini-файла, показываем опции...
	if(objSettings.bStartWithOptions){
		objSettings.bStartWithOptions=FALSE;
		if(IsStartupWithWindows()==FALSE){
			StartupApplicationWithWindows(TRUE);
		}
		// точней больше не показываем
		// objSettings.OpenOptionsDialog();
	}
	
	// Создаем
	pMainDialogWindow = new AppMainDlg();
	pMainDialogWindowCrypt = pMainDialogWindow;
	if(!pMainDialogWindow){
		return FALSE;
	}
	theApp.m_pMainWnd=pMainDialogWindow;// Сначала задаем главное окно, потом создаем его
	pMainDialogWindow->Create(AppMainDlg::IDD,m_pFakeWnd);
	// Все!
	return TRUE;
}
Exemple #12
0
int hb_CompressFile( const char * szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, const char * szPassWord, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
   ULONG                ulCount        = 0;
   const char *         szDummy;
   char *               szDummyLower   = NULL;
   char *               szFileLower    = hb_strdup( ( char * ) szFile );
   BOOL                 bFileExist     = hb_fsFile( szFile );
   BOOL                 bAdded         = FALSE;
   BOOL                 bReturn        = TRUE;
   DWORD                dwSize;

   CZipArchive          szZip;
   SpanCallbackc        span;
   SpanActionCallbackc  spanac;

   szZip.SetSpanCallback( &span );

   #ifdef HB_OS_WIN_32
   hb_strLower( szFileLower, strlen( szFileLower ) );
   #endif

   try
   {
      if( ( bFileExist && bOverWrite ) || ! bFileExist )
      {
         szZip.Open( szFile, CZipArchive::zipCreate, 0 );
      }
      else
      {
         szZip.Open( szFile, CZipArchive::zipOpen, 0 );
      }
   }

   catch( CZipException )
   {
      bReturn = FALSE;
   }

   catch( ... )
   {
   }

   if( bReturn )
   {

      if( szPassWord != NULL )
      {
         szZip.SetPassword( szPassWord );
      }

      if( pZipI.szComment != NULL )
      {
         szZip.SetGlobalComment( pZipI.szComment );
         hb_xfree( pZipI.szComment );
      }

      if( HB_IS_BLOCK( pProgress ) )
      {
         pProgressInfo = pProgress;
         szZip.SetCallback( &spanac );
      }

      for( ulCount = 1; ( ulCount <= hb_arrayLen( pArray ) ); ulCount++ )
      {
         szDummy        = ( char * ) hb_arrayGetCPtr( pArray, ulCount );
         dwSize         = GetCurrentFileSize( szDummy );
         bAdded         = FALSE;

         szDummyLower   = hb_strdup( ( char * ) szDummy );

         #ifdef HB_OS_WIN_32
         hb_strLower( szDummyLower, strlen( szDummyLower ) );
         #endif

// Prevent adding current archive file !
         if( strstr( szFileLower, szDummyLower ) == NULL && strstr( szDummyLower, szFileLower ) == NULL )
         {
            if( dwSize != ( DWORD ) -1 )
            {
               if( pBlock != NULL )
               {
                  PHB_ITEM FileName = hb_itemPutC( NULL, hb_arrayGetCPtr( pArray, ulCount ) ), FilePos = hb_itemPutNI( NULL, ulCount );


                  hb_vmEvalBlockV( pBlock, 2, FileName, FilePos );

                  hb_itemRelease( FileName );
                  hb_itemRelease( FilePos );
               }

               try
               {
                  if( bPath && ! bAdded )
                  {
                     szZip.AddNewFile( szDummy, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 );
                     bAdded = TRUE;
                  }
                  else if( ! bDrive && ! bPath && ! bAdded )
                  {
                     szZip.AddNewFile( szDummy, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 );
                  }

               }
               catch( ... )
               {
               }
            }
         }
         hb_xfree( szDummyLower );
      }
   }
   hb_xfree( szFileLower );
   try
   {
      szZip.Close();
   }

   catch( CZipException )
   {
      bReturn = FALSE;
   }

   catch( ... )
   {
   }

   return ( int ) bReturn;


}
Exemple #13
0
void WorkerThread::runUnzip() {
	emit(beginRunUnzip());
	emit(stageEvent("Extracting and merging game data"));
	
	emit(infoEvent("Unzipping original game files"));
	CZipArchive zip;
	try {
	    zip.Open(m_gameFileName.toStdString().c_str(), CZipArchive::zipOpenReadOnly);
		
		ZIP_SIZE_TYPE totalSize = 0;
		for(ZIP_INDEX_TYPE i = 0; i < zip.GetCount(); i++) {
			totalSize += zip.GetFileInfo(i)->m_uUncomprSize; // uncompressed size
			QString name = QString::fromUtf8(zip.GetFileInfo(i)->GetFileName());
			if(!validName(name)) {
				emit(errorEvent("Game pack contains illegal file names (e.g. " + name + ")"));
				emit(infoEvent("A near future release of WHDRun will fix this problem, sorry for the inconvenience"));
				m_die = true;
				return;
			}
		}
		emit(unzipTotalSize(totalSize));

		ZIP_SIZE_TYPE progress = 0;
		for(ZIP_INDEX_TYPE i = 0; i < zip.GetCount(); i++) {
			progress += zip.GetFileInfo(i)->m_uUncomprSize;
			zip.ExtractFile(i, m_tempPath.toUtf8());
			emit(unzipProgress(progress));
		}

	    zip.Close();
    } catch(CZipException ex) {
		zip.Close(CZipArchive::afAfterException);
		emit(errorEvent(QString("Error while unzipping: %1").arg((LPCTSTR)ex.GetErrorDescription())));
		m_die = true; // no need to rezip
		return;
	}

	emit(infoEvent("Collecting checksums of unmodified files"));
	emit(beginCollect());
	m_checksums.clear();
	collectFiles(m_tempPath, &m_checksums); // TODO: progress for this? (should always be quick)
	
	QString gameFileBase = QFileInfo(m_gameFileName).baseName();
	QString diffFileName = m_dataPath + "/" + gameFileBase + __WHDRun__DiffSuffix;
	if(QFileInfo(diffFileName).exists()) {
		emit(infoEvent("Merging original game files with previously modified files"));
		CZipArchive zip;
		try {
		    zip.Open(diffFileName.toUtf8(), CZipArchive::zipOpenReadOnly);

			//TODO: progress infoEvent for this? (should always be quick)
			for (ZIP_INDEX_TYPE i = 0; i < zip.GetCount(); i++) {
				zip.ExtractFile(i, m_tempPath.toUtf8());
			}

		    zip.Close();
	    } catch(CZipException ex) {
			zip.Close(CZipArchive::afAfterException);
			emit(errorEvent(QString("Error while unzipping changes: %1").arg((LPCTSTR)ex.GetErrorDescription())));
			m_die = true; // no need to rezip
			return;
		}
	}
	
	emit(endRunUnzip());
}
DWORD ProgressDialog::UpgradeAsync() {
  typedef std::list<CString> BackupFiles;

  CZipArchive ar;
  if (!ar.Open(upgradeFilePath_)) {
    ::PostMessage(m_hWnd, WM_UPGRADE_DONE, FALSE, 0);
    return 0;
  }

  bool copySuccess = true;
  TCHAR filePath[MAX_PATH];
  BackupFiles backupFiles;
  WORD fileCount = ar.GetCount();
  for (WORD i = 0; i < fileCount; i++) {
    CZipFileHeader *fileInfo = ar.GetFileInfo(i);
    if (fileInfo->IsDirectory()) {
      continue;
    }
    const CZipString &fileName = fileInfo->GetFileName();
    _tcscpy(filePath, appDir_);
    PathAddBackslash(filePath);
    _tcscat(filePath, fileName);
    if (PathFileExists(filePath)) {
      TCHAR backupFilePath[MAX_PATH];
      _tcscpy(backupFilePath, appDir_);
      PathAddBackslash(backupFilePath);
      _tcscat(backupFilePath, fileName);
      _tcscat(backupFilePath, _T(".bak"));
      if (PathFileExists(backupFilePath)) {
        DeleteFile(backupFilePath);
      }
      if (!MoveFile(filePath, backupFilePath)) {
        copySuccess = false;
        break;
      }
      backupFiles.push_back((LPCTSTR)fileName);
    }
    if (!ar.ExtractFile(i, appDir_)) {
      copySuccess = false;
      break;
    }
  }
  
  if (copySuccess) {
    AfxGetApp()->WriteProfileString(_T(""), _T("Version"), appVersion_);

    // remove backup files.
    for (BackupFiles::const_iterator i = backupFiles.begin(); i != backupFiles.end(); ++i) {
      TCHAR backupFilePath[MAX_PATH];
      _tcscpy(backupFilePath, appDir_);
      PathAddBackslash(backupFilePath);
      _tcscat(backupFilePath, *i);
      _tcscat(backupFilePath, _T(".bak"));

      DeleteFile(backupFilePath);
    }
  } else {
    // upgrade failed, restore backup.
    for (BackupFiles::const_iterator i = backupFiles.begin(); i != backupFiles.end(); ++i) {
      TCHAR backupFilePath[MAX_PATH];
      _tcscpy(backupFilePath, appDir_);
      PathAddBackslash(backupFilePath);
      _tcscat(backupFilePath, *i);
      _tcscat(backupFilePath, _T(".bak"));

      TCHAR filePath[MAX_PATH];
      _tcscpy(filePath, appDir_);
      PathAddBackslash(filePath);
      _tcscat(filePath, *i);

      DeleteFile(filePath);
      MoveFile(backupFilePath, filePath);
    }
  }

  ::PostMessage(m_hWnd, WM_UPGRADE_DONE, TRUE, 0);

  return 0;
}
Exemple #15
0
bool CSimpleZip::Extract( const void* src, const unsigned int& srcSize, void* dst, unsigned int& dstSize, std::string& szErrmsg)
{
	if ( NULL==src )
	{
		szErrmsg = "CSimpleZip: Invalid source.";
		return false;
	}

	bool bRet = false;
	CZipMemFile mfIn;
	CZipMemFile mfOut;
	CZipArchive zip;
	CZipFileHeader fhInfo;
	try
	{
		mfIn.Write(src, srcSize);
		zip.Open(mfIn, CZipArchive::zipOpen);
		if ( !zip.GetFileInfo(fhInfo, 0) )
		{
			szErrmsg = "CSimpleZip: Failed to GetFileInfo";
			zip.Close();
			return false;
		}

		if ( NULL==dst || dstSize<fhInfo.m_uUncomprSize )
		{
			dstSize = fhInfo.m_uUncomprSize;
			szErrmsg = "CSimpleZip: The size of destination buffer is too small.";
			return false;
		}

		mfOut.SetLength( fhInfo.m_uUncomprSize );
		((CZipAbstractFile*)&mfOut)->SeekToBegin(); // may be needed when mfOut was used previously
		if ( !zip.ExtractFile(0, mfOut) )
		{
			szErrmsg =  "CSimpleZip: Failed to ExtractFile";
			zip.Close();
			return false;
		}
		zip.Close();
		BYTE* b = mfOut.Detach();
		//int nLen = (int)mfOut.GetLength();			// this is an error length value 
		memcpy_s(dst, dstSize, b, fhInfo.m_uUncomprSize);
		dstSize = fhInfo.m_uUncomprSize;
		free(b);
		bRet = true;
	}
	catch(CZipException& e)
	{
		if (!zip.IsClosed())
			zip.Close();
		szErrmsg =  e.GetErrorDescription().c_str();
	}
	catch(...)
	{
		if (!zip.IsClosed())
			zip.Close();
		szErrmsg =  "CSimpleZip: Failed to Extract, catch exception.";
	}
	return bRet;
}
Exemple #16
0
int hb_CmpTdSpan( const char * szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, const char * szPassWord, int iSpanSize, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
   ULONG                ulCount     = 0;
   const char *         szDummy;
   DWORD                dwSize;
   BOOL                 bAdded      = FALSE;
   BOOL                 bReturn     = TRUE;
   BOOL                 bFileExist  = hb_fsFile( szFile );

   CZipArchive          szZip;
   SpanCallbackc        span;
   SpanActionCallbackc  spanac;

   szZip.SetSpanCallback( &span );


   if( iSpanSize == 0 )
   {
      iSpanSize = 1457664;
   }

   try
   {
      if( ( bFileExist && bOverWrite ) || ! bFileExist )
      {
         szZip.Open( szFile, CZipArchive::zipCreateSpan, iSpanSize );
      }
      else
      {
         bReturn = FALSE;
         return ( int ) bReturn;
      }
   }

   catch( CZipException )
   {
      bReturn = FALSE;
   }

   catch( ... )
   {
   }

   //if (! bReturn )
   //{

   if( szPassWord != NULL )
   {
      szZip.SetPassword( szPassWord );
   }

   if( pZipI.szComment != NULL )
   {
      szZip.SetGlobalComment( pZipI.szComment );
      hb_xfree( pZipI.szComment );
   }

   if( HB_IS_BLOCK( pProgress ) )
   {
      pProgressInfo = pProgress;
      szZip.SetCallback( &spanac );
   }

   for( ulCount = 1; ( ulCount <= hb_arrayLen( pArray ) ); ulCount++ )
   {
      szDummy  = ( char * ) hb_arrayGetCPtr( pArray, ulCount );
      dwSize   = GetCurrentFileSize( szDummy );

      bAdded   = FALSE;

      if( dwSize != ( DWORD ) -1 )
      {
         if( pBlock != NULL )
         {
            PHB_ITEM FileName = hb_itemPutC( NULL, hb_arrayGetCPtr( pArray, ulCount ) ), FilePos = hb_itemPutNI( NULL, ulCount );

            hb_vmEvalBlockV( pBlock, 2, FileName, FilePos );

            hb_itemRelease( FileName );
            hb_itemRelease( FilePos );
         }

         try
         {

            if( bPath && ! bAdded )
            {
               szZip.AddNewFile( szDummy, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 );
               bAdded = TRUE;
            }
            else if( ! bDrive && ! bPath && ! bAdded )
            {
               szZip.AddNewFile( szDummy, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 );
            }

         }
         catch( ... )
         {
         }
      }
   }
   //}

   try
   {
      szZip.Close();
   }

   catch( CZipException )
   {
      bReturn = FALSE;
   }

   catch( ... )
   {
   }


   return ( int ) bReturn;
}
/**
	@brief	

	@author BHK	

	@date 2009-04-28 오전 11:10:50	

	@param	

	@return		
*/
void CSaveProductToRevisionDlg::OnBnClickedOk()
{
	char* pData = NULL;

	CELoadDocData& docData = CELoadDocData::GetInstance();
	
	InsertLoadItemInCableSizingResultDoc();

	const string rMDBFilePath = docData.GetProjectMDBFilePath();

	CADODB adoDB;
	const STRING_T rConnectionString = STRING_T(PROVIDER) + _T("Data Source=") + rMDBFilePath + DB_PASSWORD;
	if(TRUE == adoDB.DBConnect(rConnectionString))
	{
		CString strDesc;
		GetDlgItemText(IDC_EDIT_DESC , strDesc);

		CString strZipFilePath;
		map<CString , CString > ZipFilePathMap;
		if((_T("LOAD SUMMARY-BUS") == m_rProductName) || (_T("LOAD SUMMARY-SUBBUS") == m_rProductName))
		{
			strZipFilePath = string(docData.GetProjectFolderPath() + _T("Load Summary Result\\BUS_LoadSummary.zip")).c_str();
			ZipFilePathMap.insert(make_pair(_T("Load Summary-BUS") , strZipFilePath));
			strZipFilePath = string(docData.GetProjectFolderPath() + _T("Load Summary Result\\SubBUS_LoadSummary.zip")).c_str();
			ZipFilePathMap.insert(make_pair(_T("Load Summary-SubBUS") , strZipFilePath));
		}
		else if(_T("TRANSFORMER SIZING") == m_rProductName)
		{
			CTransformerSizingResultDoc::SaveTransformerSizingResultData();

			CZipArchive zip;
			CString strProjectPath = docData.GetProjectFolderPath().c_str();
			strZipFilePath = strProjectPath + _T("Transformer Sizing\\Transformer Sizing.zip");
			{
				if(!strZipFilePath.IsEmpty())
				{
					zip.Open(strZipFilePath , CZipArchive::create );
					zip.AddNewFile(strProjectPath + _T("Transformer Sizing\\Transformer Sizing.txt") , -1 , false);
					zip.Close();
				}
			}
			ZipFilePathMap.insert(make_pair(m_rProductName , strZipFilePath));
		}
		else if(_T("AUTO POWER CABLE") == m_rProductName)
		{
			CZipArchive zip;
			CString strProjectPath = docData.GetProjectFolderPath().c_str();
			strZipFilePath = strProjectPath + _T("Cable Sizing Result\\Cable Sizing Result.zip");
			{
				if(!strZipFilePath.IsEmpty())
				{
					zip.Open(strZipFilePath , CZipArchive::create );
					CString strDir = strProjectPath + CString(_T("Cable Sizing Result\\*.BUS"));
					CFileFind file;

					vector<string> rInterestingFileEntry;
					///! 확장자가 *.BUS 파일을 찾는다.
					BOOL bFound = file.FindFile(strDir);
					if(bFound)
					{
						while(bFound)
						{
							bFound = file.FindNextFile();
							if(file.IsDots()) continue;

							const CString rFileName = file.GetFileTitle().MakeUpper();
							zip.AddNewFile(strProjectPath + CString(_T("Cable Sizing Result\\")) + rFileName + _T(".BUS") , -1 , false);
						}
					}
					zip.Close();
				}
			}
			ZipFilePathMap.insert(make_pair(m_rProductName , strZipFilePath));
		}
		else if(_T("AUTO CONTROL CABLE") == m_rProductName)
		{
			CZipArchive zip;
			CString strProjectPath = docData.GetProjectFolderPath().c_str();
			strZipFilePath = strProjectPath + _T("Control Cable Result\\Control Cable Result.zip");
			{
				if(!strZipFilePath.IsEmpty())
				{
					zip.Open(strZipFilePath , CZipArchive::create );
					CString strDir = strProjectPath + CString(_T("Control Cable Result\\*.BUS"));
					CFileFind file;

					vector<string> rInterestingFileEntry;
					///! 확장자가 *.BUS 파일을 찾는다.
					BOOL bFound = file.FindFile(strDir);
					if(bFound)
					{
						while(bFound)
						{
							bFound = file.FindNextFile();
							if(file.IsDots()) continue;

							const CString rFileName = file.GetFileTitle().MakeUpper();
							zip.AddNewFile(strProjectPath + CString(_T("Control Cable Result\\")) + rFileName + _T(".BUS") , -1 , false);
						}
					}
					zip.Close();
				}
			}
			ZipFilePathMap.insert(make_pair(m_rProductName , strZipFilePath));
		}
		else if(_T("CABLE SIZING TABLE") == m_rProductName)
		{
			CZipArchive zip;
			CString strProjectPath = docData.GetProjectFolderPath().c_str();
			strZipFilePath = strProjectPath + _T("Cable Sizing Table\\Cable Sizing Table.zip");
			{
				if(!strZipFilePath.IsEmpty())
				{
					zip.Open(strZipFilePath , CZipArchive::create );
					
					CString strDir = strProjectPath + CString(_T("Cable Sizing Table\\*.TXT"));
					CFileFind file;

					vector<string> rInterestingFileEntry;
					///! 확장자가 *.TXT 파일을 찾는다.
					BOOL bFound = file.FindFile(strDir);
					if(bFound)
					{
						while(bFound)
						{
							bFound = file.FindNextFile();
							if(file.IsDots()) continue;

							const CString rFileName = file.GetFileTitle().MakeUpper();
							zip.AddNewFile(strProjectPath + CString(_T("Cable Sizing Table\\")) + rFileName + _T(".TXT") , -1 , false);
						}
					}

					zip.Close();
				}
			}
			ZipFilePathMap.insert(make_pair(m_rProductName , strZipFilePath));
		}
		else if((_T("CABLE SCHEDULE") == m_rProductName) || (_T("DRUM SCHEDULE") == m_rProductName))
		{
			CZipArchive zip;
			CString strProjectPath = docData.GetProjectFolderPath().c_str() , rKeyString;
			if(_T("Cable Schedule") == m_rProductName)
				rKeyString = _T("Cable Schedule Result");
			else	rKeyString = _T("Drum Schedule Result");
			strZipFilePath = strProjectPath + rKeyString + _T("\\") + rKeyString + _T(".zip");
			{
				if(!strZipFilePath.IsEmpty())
				{
					zip.Open(strZipFilePath , CZipArchive::create );
					
					CString strDir = strProjectPath + rKeyString + CString(_T("\\*.TXT"));
					CFileFind file;

					vector<string> rInterestingFileEntry;
					///! 확장자가 *.TXT 파일을 찾는다.
					BOOL bFound = file.FindFile(strDir);
					if(bFound)
					{
						while(bFound)
						{
							bFound = file.FindNextFile();
							if(file.IsDots()) continue;

							const CString rFileName = file.GetFileTitle().MakeUpper();
							zip.AddNewFile(strProjectPath + rKeyString + CString(_T("\\")) + rFileName + _T(".TXT") , -1 , false);
						}
					}

					zip.Close();
				}
			}
			ZipFilePathMap.insert(make_pair(m_rProductName , strZipFilePath));
		}

		if(!ZipFilePathMap.empty())
		{
			++m_nLastRevNo;
			for(map<CString , CString>::iterator itr = ZipFilePathMap.begin();itr != ZipFilePathMap.end();++itr)
			{
				CString strFormat = _T("INSERT INTO T_PRODUCT_REVISION(C_PRODUCT_NAME,C_REVISION_NO,C_DATE,C_DESC) VALUES('%s',%d,'%s','%s')");
				CString strSQL;

				CTime CurTime = CTime::GetCurrentTime();
				CString strTimeData = CurTime.Format(_T("%Y년 %m월 %d일 - %H시 %M분"));

				strSQL.Format(strFormat , itr->first , m_nLastRevNo , strTimeData , strDesc);
				adoDB.ExecuteQuery(strSQL.operator LPCTSTR());

				strSQL = _T("SELECT * FROM T_PRODUCT_REVISION WHERE C_PRODUCT_NAME = '") + itr->first + _T("' ORDER BY C_REVISION_NO DESC");
				adoDB.OpenQuery(strSQL.operator LPCTSTR());
				LONG lRecordCount = 0L;
				adoDB.GetRecordCount(&lRecordCount);

				CFile f(itr->second , CFile::modeRead);
				ULONGLONG fSize = f.GetLength();
				if(NULL == pData) pData = (char*)calloc(1 , sizeof(char)*fSize);
				if(pData)
				{
					f.Read(pData,fSize);
					const int nFieldCount = adoDB.GetFieldCount();
					for(int i = 0;i < nFieldCount;++i)
					{
						if(_T("C_DATA") == adoDB.GetFieldName(i))
						{
							adoDB.AppendChunk(0 , i , pData , fSize);
							break;
						}
					}
					free((void*)pData);
					pData = NULL;
				}
			}
		}
	}
	else
	{
		AfxMessageBox(_T("Fail to connect database"));
	}
	
	OnOK();
}
Exemple #18
0
int hb_CmpTdSpanStd( char * szFile, char * szFiletoCompress, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, char * szPassWord, int iSpanSize, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress )
{
   DWORD                dwSize;
   BOOL                 bAdded      = FALSE;
   BOOL                 bReturn     = TRUE;
   BOOL                 bFileExist  = hb_fsFile( szFile );

   CZipArchive          szZip;
   SpanCallbackc        span;
   SpanActionCallbackc  spanac;

   szZip.SetSpanCallback( &span );


   if( iSpanSize == 0 )
   {
      iSpanSize = 1457664;
   }

   try
   {
      if( ( bFileExist && bOverWrite ) || ! bFileExist )
      {
         szZip.Open( szFile, CZipArchive::zipCreateSpan, iSpanSize );
      }
      else
      {
         return ( int ) false;
      }
   }

   catch( CZipException )
   {
      bReturn = FALSE;
   }

   catch( ... )
   {
   }

   if( szPassWord != NULL )
   {
      szZip.SetPassword( szPassWord );
   }

   if( pZipI.szComment != NULL )
   {
      szZip.SetGlobalComment( pZipI.szComment );
      hb_xfree( pZipI.szComment );
   }

   if( HB_IS_BLOCK( pProgress ) )
   {
      pProgressInfo = pProgress;
      szZip.SetCallback( &spanac );
   }
   if( bReturn )
   {
      try
      {
         if( szPassWord != NULL )
         {
            szZip.SetPassword( szPassWord );
         }

         dwSize = GetCurrentFileSize( szFiletoCompress );

         if( pBlock != NULL )
         {
            PHB_ITEM FileName = hb_itemPutC( NULL, szFiletoCompress  );

            hb_vmEvalBlockV(  pBlock, 1, FileName );

            hb_itemRelease( FileName );

         }

         #if defined( __WIN32__ ) || defined( __MINGW32__ )
         if( bDrive && ! bAdded )
         {
            if( ! szZip.AddNewFileDrv( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) )
            {
               bReturn = FALSE;
            }
            else
            {
               bAdded = TRUE;
            }
         }
         #endif

         if( bPath && ! bAdded )
         {
            if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) )
            {
               bReturn = FALSE;
            }
            else
            {
               bAdded = TRUE;
            }
         }
         else if( ! bDrive && ! bPath && ! bAdded )
         {
            if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 ) )
            {
               bReturn = FALSE;
            }
         }

      }
      catch( ... )
      {
      }
   }

   try
   {
      szZip.Close();
   }

   catch( CZipException )
   {
      bReturn = FALSE;
   }

   catch( ... )
   {
   }
   if( pProgressInfo )
   {
      hb_itemRelease( pProgressInfo );
   }

   return ( int ) bReturn;
}
Exemple #19
0
UINT CScormEngine::CreatePackage(HWND hWndParent)
{
   // Reset progress (should be zero anyway)
   m_dwProgress = 0;
   m_dwCurrentFile = 0;
   m_bCancelRequested = false;

   // Create a temporary directory
   _TCHAR tszPath[MAX_PATH];
   _TCHAR tszDirectory[MAX_PATH];
   bool success = LIo::CreateTempDir(_T("SCO"), tszPath, tszDirectory);

   if (success)
   {
      m_csBaseTempPath = tszPath;
      m_csRelTempPath = tszDirectory;
      m_csTargetDir = m_csBaseTempPath + m_csRelTempPath + CString(_T("\\"));
   }

   //MessageBox(hWndParent, tszDirectory, tszPath, MB_OK | MB_ICONINFORMATION);

   if (success)
      DefineScormKeywords();

   CString csImsManifest;
   if (success)
      success = LoadXmlResource(csImsManifest, IDR_XML_IMSMANIFEST);

   if (success && !m_bCancelRequested)
   {
      // Let's write the imsmanifest File.
      LTextBuffer tbImsManifest(csImsManifest);
      int nKwCount = m_aGeneralKeywords.GetSize();
      for (int i=0; i<nKwCount; ++i)
         tbImsManifest.ReplaceAll(m_aGeneralKeywords[i], m_aGeneralValues[i]);

      success = tbImsManifest.SaveFile(m_csTargetDir + _T("imsmanifest.xml"), 
         LFILE_TYPE_TEXT_UTF8, false); // Do not write a UTF8 BOM.
   }

/*   CString csScoMetadata;
   if (success)
      success = LoadXmlResource(csScoMetadata, IDR_XML_SCOMETADATA);

   if (success && !m_bCancelRequested)
   {
      // And now the scometadata.xml file.
      LTextBuffer tbScoMetadata(csScoMetadata);
      int nKwCount = m_aGeneralKeywords.GetSize();
      for (int i=0; i<nKwCount; ++i)
         tbScoMetadata.ReplaceAll(m_aGeneralKeywords[i], m_aGeneralValues[i]);

      success = tbScoMetadata.SaveFile(m_csTargetDir + _T("scometadata.xml"),
         LFILE_TYPE_TEXT_UTF8, false); // No UTF8 BOM, thank you.
   }*/

   if (success && !m_bCancelRequested)
   {
      CZipArchive zip;
      CScormZipCallback zipCallback(this);
      zip.SetCallback(&zipCallback);
      zip.Open(m_csTargetDir + m_csTargetFile + _T(".zip"), CZipArchive::zipCreate);
      zip.AddNewFile(m_csTargetDir + _T("imsmanifest.xml"), _T("imsmanifest.xml"));
//      zip.AddNewFile(m_csTargetDir + _T("scometadata.xml"), _T("scometadata.xml"));
      zip.AddNewFile(m_csRealIndexFileName, m_csIndexFileName);
      int nFileCount = m_aSourceFiles.GetSize();
      for (int i=0; i<nFileCount; ++i)
         zip.AddNewFile(m_aSourceFiles[i], m_aTargetFiles[i]);
      zip.Close();
   }

   if (m_bCancelRequested)
      return ERROR_CANCELLED;

   return success ? S_OK : E_FAIL;
}
Exemple #20
0
void extractRestoreFiles( string filepath, bool known )
{
    cout << "Extracting restore files" << endl;
    CZipArchive zip;
    ZIP_INDEX_TYPE index;
    
    try
    {
        zip.Open(_T(filepath.c_str()));
    
        cout << "Extracting ramdisk" << endl;
        if( known )
        {
            index = zip.FindFile(_T("694-5259-38.dmg"));
            zip.ExtractFile(index, _T(cwd.c_str()));
            ramdisk = (cwd + "/694-5259-38.dmg");
        }
        else
        {
            CZipIndexesArray indexes;
            zip.FindMatches(_T("*.dmg"), indexes, false);	 
            for (ZIP_ARRAY_SIZE_TYPE i = 0; i < indexes.GetCount(); i++)
            {
                ZIP_INDEX_TYPE ind = indexes[i];        
                if(zip[ind]->m_uUncomprSize > (10*1024*1024) && zip[ind]->m_uUncomprSize < (20*1024*1024) )
                {
                    zip.ExtractFile(ind, _T(cwd.c_str()));   
                    FILE *f = fopen((cwd + "/" + zip[ind]->GetFileName()).c_str(), "rb");
            		if(!f)
            		{
                        continue; 
                    }
                    else
                    {
                        unsigned char magic[4];
                        fread(magic, 1, 4, f);
                        if( magic[0] == 0x38 &&
                            magic[1] == 0x39 &&
                            magic[2] == 0x30 &&
                            magic[3] == 0x30 )
                        {
                            ramdisk = cwd + "/" + zip[ind]->GetFileName();
                            fclose(f);
                            break;
                        }  
                        fclose(f);  
                    }            
                }
            }
        }			
        
        cout << "Extracting kernelcache" << endl; 
        if(known)
        {  
            index = zip.FindFile(_T("kernelcache.restore.release.s5l8900xrb"));
            zip.ExtractFile(index, _T(cwd.c_str()));
            kernelcache = (cwd + "/kernelcache.restore.release.s5l8900xrb");
        }
        else
        {
            CZipIndexesArray indexes;
            zip.FindMatches (_T("*kernelcache*"), indexes, false);	
            if(indexes.GetCount() > 0)
            { 
                zip.ExtractFile(indexes[0], _T(cwd.c_str())); 
                kernelcache = cwd + "/" + zip[indexes[0]]->GetFileName();
            }
        }
        zip.Close();
    }
    catch(...)
    {
        cout << "Error extracting restore file" << endl;   
    }

}
DWORD WINAPI zipCompress(LPVOID lpParam){
	_filename = COMPRESS_PREPARING;
	sTime = time(NULL);

	CZipArchive zip;
	vector<__int64>filesize;
	_size_all = 1;

	/*char b[123];
	sprintf(b, "%d", spanSize);
	MessageBox(0, b, "", 0);*/
	
	if(spanSize == 0)
		zip.Open(archive_name, CZipArchive::OpenMode::zipCreate);
	else
		zip.Open(archive_name, CZipArchive::OpenMode::zipCreateSpan, spanSize);
	zip.SetPassword(passwd);
	//zip.SetAutoFlush();
	
	_filename = COMPRESS_GETTING_FILE_SIZES;
	for (int i=0; i<int(filename.size()); ++i) {
      FILE* f=fopen(filename[i].c_str(), "rb");
      if(f){
		_fseeki64(f, 0LL, SEEK_END);
		filesize.push_back(_ftelli64(f));
        _size_all += _ftelli64(f);
        fclose(f);
      }
    }

	for(int i=0;i<filename.size();i++){
		_filename = filename[i];
		//zip.AddNewFile(filename[i].c_str(), MEM);
		zip.AddNewFile(filename[i].c_str(), filename[i].c_str(), MEM);
		_done_all += filesize[i];
		
		CZipFileHeader fhInfo;
		zip.GetFileInfo(fhInfo, i);
		_compressed += fhInfo.GetEffComprSize() + fhInfo.GetSize() + fhInfo.GetExtraFieldSize();
		
	}
	zip.Close();

	/*FILE *f = fopen(archive_name, "rb");
	if(f){
		_fseeki64(f, 0LL, SEEK_END);
		_compressed = _ftelli64(f);
		fclose(f);
	}*/

	if(sfx_arch){ //do³¹czamy modu³ sfx
		_filename = COMPRESS_ADDING_SFX_MOD;
		
		/*archive_name[strlen(archive_name)-3] = '\0';
		sprintf(archive_name, "%sexe", archive_name);*/

		//odczytujemy œcie¿kê do modu³u
		HANDLE hProc = GetCurrentProcess();
		HMODULE hMod;
        DWORD cbNeeded;
		char processName[MAX_PATH];

        EnumProcessModules(hProc, &hMod, sizeof(hMod), &cbNeeded);
        GetModuleFileNameEx(hProc, hMod, processName, MAX_PATH);
        
		for(int i=strlen(processName)-1;i>=0;i--){
			if(processName[i] == '\\' || processName[i] == '/'){
				processName[i+1] = '\0';
				sprintf(processName, "%skgb_arch_sfx_zip.mod", processName);
				break;
			}
		}

		FILE *sfx = fopen(processName, "rb");

		//MessageBox(0, "", "", 0);
		if(sfx == NULL){
			MessageBox(0, "An internal error has occured, please reinstall KGB Archiver!", "KGB Archiver", 0);
			_fcloseall();
			DeleteFile(archive_name);
			return false;
		}

		//MessageBox(0, archive_name, "", 0);

		FILE *archive = fopen(archive_name, "rb");
		if(archive == NULL){
			_fcloseall();
			return false;
		}
		//MessageBox(0, "", "", 0);

		archive_name[strlen(archive_name)-3] = '\0';
		sprintf(archive_name, "%sexe", archive_name);

		//MessageBox(0, archive_name, "", 0);

		FILE *archive_sfx = fopen(archive_name, "wb");
		if(archive_sfx == NULL){
			_fcloseall();
			return false;
		}

		//MessageBox(0, "2", "", 0);

		int count=0;
		char buffer[65536];
		while(!feof(sfx)){
			count = fread(buffer, sizeof(char), sizeof(buffer), sfx);
			fwrite(buffer, sizeof(char), count, archive_sfx);
		}
		while(!feof(archive)){
			count = fread(buffer, sizeof(char), sizeof(buffer), archive);
			fwrite(buffer, sizeof(char), count, archive_sfx);
		}
		fclose(archive);
		fclose(sfx);
		fclose(archive_sfx);

		archive_name[strlen(archive_name)-3] = '\0';
		sprintf(archive_name, "%szip", archive_name);
		DeleteFile(archive_name);
	}

	_done_all++;

	return true;
}
bool CWebCDCovers::DownloadImage(CString strLetter, CString strName, CString strFilename, RESOURCEHOST* pHost, HWND hwndProgress, HWND hwndStatus, CString& strLocalFilename)
{
	// get the html page for the image source
	*m_pbCancelDownload = false;

	WCC_GETIMAGEREQUEST* pfn_wccRequest = (WCC_GETIMAGEREQUEST*) GetProcAddress (pHost->hInst, "GetImageRequest");
	WCC_GETIMAGEURL* pfn_wccImgURL = (WCC_GETIMAGEURL*) GetProcAddress (pHost->hInst, "GetImageURL");

	char szUrl[300], szHeaders[300], szData[300];
	int nMethod;
	pfn_wccRequest (strFilename.GetBuffer (0), strLetter.GetBuffer (0), "", szUrl, &nMethod, szHeaders, szData);

	CString strHTML = (*szUrl == 0) ? strFilename.GetBuffer (0) :
		CHttpRequest::DownloadBuffer (szUrl, nMethod, szHeaders, szData,
			m_pbCancelDownload, m_dwDownloadId, m_nError);

	// MCH 29/08/04
	// Send version info to the DLL
	strcpy (szData, ((CCdCoverCreator2App*) AfxGetApp ())->GetVersion ().GetBuffer (-1));

	// get the URL of the image
	CString strURL;
	if (!pfn_wccImgURL (strHTML.GetBuffer (0), strURL.GetBuffer (500), &nMethod, szHeaders, szData))
		return false;
	strURL.ReleaseBuffer ();

	// generate a local temporary file name
	strLocalFilename = ((CCdCoverCreator2App*) AfxGetApp ())->GetImageCacheDir () + strURL.Mid (strURL.ReverseFind ('/') + 1);
	if (strLocalFilename.Find (".php?") >= 0)
	{
		// MCH 15/09/04
		// www.darktown.to sends again JPGs, but via a PHP script. Filename provided as HTTP header which is not available here
		strLocalFilename = ((CCdCoverCreator2App*) AfxGetApp ())->GetImageCacheDir ();
		strLocalFilename.AppendFormat ("dld%d.jpg", GetTickCount ());
	}

	// get the jpeg image
	*m_pbCancelDownload = false;
	CHttpRequest::DownloadFile (strURL, nMethod, szHeaders, szData, strLocalFilename,
		m_pbCancelDownload, m_dwDownloadId, m_nError, 0, hwndProgress, hwndStatus);

	if (m_nError)
		return false;

	// MCH 29/08/04
	// if the download is a zip file, extract the image
	if (strLocalFilename.Right (4).MakeLower () == ".zip")
	{
		CString strPath = strLocalFilename.Left (strLocalFilename.ReverseFind ('\\'));
		CString strZipFile = strLocalFilename;

		// set up and open a zip archive, get the image files inside the zip file
		CZipArchive zip;
		zip.Open (strZipFile);
		CZipWordArray ar;
		zip.FindMatches ("*.jp*g", ar);

		strLocalFilename.Empty ();

		// extract the image files
		for (int i = 0; i < ar.GetSize (); i++)
		{
			// set the local file name
			CZipFileHeader info;
			zip.GetFileInfo (info, i);
			if (!strLocalFilename.IsEmpty ())
				strLocalFilename += ";";
			strLocalFilename += strPath + "\\" + info.GetFileName ();
			
			// extract the file
			zip.ExtractFile (ar.GetAt (i), strPath, false);
		}

		zip.Close ();

		// delete the zip file
		::DeleteFile (strZipFile);
	}

	return true;
}