Subversion Repositories spk

Rev

Rev 149 | Rev 158 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
6 cycrow 1
// SpkFile.cpp: implementation of the CSpkFile class.
2
//
3
//////////////////////////////////////////////////////////////////////
4
 
5
#include "BaseFile.h"
6
 
7
//////////////////////////////////////////////////////////////////////
8
// Construction/Destruction
9
//////////////////////////////////////////////////////////////////////
10
 
11
#include "spk.h"
12
 
13
#include "DirIO.h"
14
#include "File_IO.h"
15
#include "CatFile.h"
16
#include "Packages.h"
88 cycrow 17
#include "TextDB.h"
6 cycrow 18
 
46 cycrow 19
#include <Package/InstallText.h>
6 cycrow 20
 
46 cycrow 21
// remove these eventually
22
using namespace SPK;
23
using namespace Package;
6 cycrow 24
 
25
CArchiveFile::~CArchiveFile()
26
{
27
	Delete ();
28
}
29
 
30
CArchiveFile::CArchiveFile() : CBaseFile ()
31
{
32
	SetDefaults ();
33
}
34
 
35
void CBaseFile::SetDefaults ()
36
{
46 cycrow 37
	_setDefaults();
38
 
6 cycrow 39
	m_pIconFile = NULL;
40
 
41
	m_bAutoGenerateUpdateFile = false;
42
	m_SHeader.iValueCompression = SPKCOMPRESS_ZLIB;
43
	m_SHeader2.iFileCompression = SPKCOMPRESS_ZLIB;
44
	m_SHeader2.iDataCompression = SPKCOMPRESS_LZMA;
45
	m_pParent = NULL;
50 cycrow 46
	_changed();
6 cycrow 47
	m_bUpdate = false;
130 cycrow 48
	_bCombineFiles = false;
6 cycrow 49
 
50
	ClearError();
51
 
52
	m_iLoadError = 0;
53
 
54
	m_bFullyLoaded = false;
55
	m_bSigned = false;
56
	m_bEnable = m_bGlobal = m_bProfile = m_bModifiedEnabled = true;
57
	m_bOverrideFiles = false;
58
}
59
 
88 cycrow 60
CBaseFile::CBaseFile() : _pTextDB(NULL)
6 cycrow 61
{
62
	SetDefaults ();
63
}
64
CBaseFile::~CBaseFile()
65
{
66
	Delete();
67
}
68
 
69
void CBaseFile::Delete ()
70
{
71
	m_lFiles.clear(true);
72
 
73
	if ( m_pIconFile )
74
	{
75
		delete m_pIconFile;
76
		m_pIconFile = NULL;
77
	}
78
 
88 cycrow 79
	if ( _pTextDB ) {
80
		delete _pTextDB;
81
		_pTextDB = NULL;
82
	}
83
 
6 cycrow 84
	m_lNames.clear(true);
85
}
86
 
121 cycrow 87
CyString CBaseFile::GetLanguageName ( int lang ) const
6 cycrow 88
{
89
	for ( CListNode<SNames> *node = m_lNames.Front(); node; node = node->next() )
90
	{
91
		SNames *n = node->Data();
92
		if ( n->iLanguage == lang )
93
			return n->sName;
94
	}
50 cycrow 95
	return this->name();
6 cycrow 96
}
97
 
98
 
99
/*
100
##########################################################################################
101
##################                Base Class Functions                  ##################
102
##########################################################################################
103
*/
104
 
131 cycrow 105
const CLinkList<C_File> *CBaseFile::fileList() const
106
{
107
	return &m_lFiles;
108
}
53 cycrow 109
CLinkList<C_File> *CBaseFile::fileList(int type) const
6 cycrow 110
{
111
	CLinkList<C_File> *list = new CLinkList<C_File>;
112
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
113
	{
114
		C_File *f = node->Data();
115
		if ( f->GetFileType() == type )
116
			list->push_back(f);
117
	}
118
 
119
	return list;
120
}
121
 
13 cycrow 122
C_File *CBaseFile::GetNextFile(C_File *prev) const
6 cycrow 123
{
124
	int type = -1;
125
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
126
	{
127
		C_File *f = node->Data();
128
		if ( type == -1 )
129
		{
130
			if ( f == prev )
131
				type = f->GetFileType();
132
		}
133
		else
134
		{
135
			if ( f->GetFileType() == type )
136
				return f;
137
		}
138
	}
139
 
140
	return NULL;
141
}
142
 
13 cycrow 143
C_File *CBaseFile::GetPrevFile(C_File *next) const
6 cycrow 144
{
145
	if ( !next )
146
		return NULL;
147
 
148
	int type = -1;
149
	for ( CListNode<C_File> *node = m_lFiles.Back(); node; node = node->prev() )
150
	{
151
		C_File *f = node->Data();
152
		if ( type == -1 )
153
		{
154
			if ( f == next )
155
				type = f->GetFileType();
156
		}
157
		else
158
		{
159
			if ( f->GetFileType() == type )
160
				return f;
161
		}
162
	}
163
 
164
	return NULL;
165
}
166
 
13 cycrow 167
C_File *CBaseFile::GetFirstFile(int type) const
6 cycrow 168
{
169
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
170
	{
171
		C_File *f = node->Data();
172
		if ( f->GetFileType() == type )
173
			return f;
174
	}
175
 
176
	return NULL;
177
}
178
 
179
int CBaseFile::CheckFile ( CyString filename, float *version )
180
{
91 cycrow 181
	CFileIO File(filename);
182
	if ( !File.startRead() ) return 0;
183
	Utils::String line = File.readEndOfLine();
51 cycrow 184
	Utils::String type = line.token(";", 1);
185
	File.close();
6 cycrow 186
 
187
	// check for old version
51 cycrow 188
	if ( line.left(3) == "HiP" ) return SPKFILE_OLD;
6 cycrow 189
 
190
	// check for format
51 cycrow 191
	if ( version ) *version = line.token(";", 2);
6 cycrow 192
 
51 cycrow 193
	if ( type == "BaseCycrow" )	return SPKFILE_BASE;
194
	if ( type == "SPKCycrow" )	return SPKFILE_SINGLE;
195
	if ( type == "XSPCycrow" )	return SPKFILE_SINGLESHIP;
196
	if ( type == "MSPKCycrow" )	return SPKFILE_MULTI;
6 cycrow 197
	return SPKFILE_INVALID;
198
}
199
 
200
void CBaseFile::ClearFileData()
201
{
88 cycrow 202
	for ( CListNode<C_File> *f = m_lFiles.Front(); f; f = f->next() )
6 cycrow 203
	{
88 cycrow 204
		f->Data()->DeleteData();
6 cycrow 205
	}
206
}
207
 
130 cycrow 208
Utils::String CBaseFile::getNameValidFile() const
6 cycrow 209
{
130 cycrow 210
	Utils::String name = this->name();
211
	name.removeChar(':');
212
	name.removeChar('/');
213
	name.removeChar('\\');
214
	name.removeChar('*');
215
	name.removeChar('?');
216
	name.removeChar('"');
217
	name.removeChar('<');
218
	name.removeChar('>');
219
	name.removeChar('|');
220
	return name;
221
}
6 cycrow 222
 
223
void CBaseFile::SwitchFilePointer(C_File *oldFile, C_File *newFile)
224
{
225
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
226
	{
227
		C_File *f = node->Data();
228
		if ( f == oldFile )
229
		{
230
			node->ChangeData(newFile);
231
			break;
232
		}
233
	}
234
}
235
 
236
bool CBaseFile::AnyFileType ( int type )
237
{
238
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
239
	{
240
		C_File *f = node->Data();
241
		if ( f->GetFileType() == type )
242
			return true;
243
	}
244
 
245
	return false;
246
}
247
 
248
void CBaseFile::AddFile ( C_File *file )
249
{
250
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
251
	{
252
		C_File *f = node->Data();
130 cycrow 253
		if ( f->fileType() != file->fileType() )
6 cycrow 254
			continue;
130 cycrow 255
		if ( f->name() != file->name () )
6 cycrow 256
			continue;
257
		if ( f->GetDir() != file->GetDir() )
258
			continue;
127 cycrow 259
		if ( f->game() != file->game() )
6 cycrow 260
			continue;
261
 
262
		m_lFiles.remove(node, true);
263
		break;
264
	}
265
 
88 cycrow 266
	_addFile(file);
6 cycrow 267
}
268
 
127 cycrow 269
C_File *CBaseFile::AddFile(CyString file, CyString dir, int type, int game)
6 cycrow 270
{
127 cycrow 271
	return addFile(file.ToString(), dir.ToString(), (FileType)type, game);
272
}
155 cycrow 273
C_File *CBaseFile::addFile(const Utils::String &file, const Utils::String &dir, FileType type, int game, bool packed)
127 cycrow 274
{
275
	C_File *newfile = new C_File(file);
276
	newfile->SetDir(dir);
130 cycrow 277
	newfile->setFileType(type);
127 cycrow 278
	newfile->setGame(game);
6 cycrow 279
 
155 cycrow 280
	if (packed)
281
	{
282
		if (newfile->PCKFile())
283
		{
284
			newfile->setFilename(CFileIO(newfile->filePointer()).changeFileExtension("pck"));
285
		}
286
	}
287
 
6 cycrow 288
	// first check if the file already exists
289
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
290
	{
291
		C_File *f = node->Data();
130 cycrow 292
		if ( f->fileType() != newfile->fileType() )
6 cycrow 293
			continue;
130 cycrow 294
		if ( f->name() != newfile->name () )
6 cycrow 295
			continue;
134 cycrow 296
		if ( f->dir() != newfile->dir() )
6 cycrow 297
			continue;
130 cycrow 298
		if (f->game() != newfile->game())
299
		{
300
			//same file, for different game, check if they are the same and combine them
301
			if (_bCombineFiles)
302
			{
303
				char *data = NULL;
304
				char *newData = NULL;
305
				size_t size = 0;
306
				size_t newSize = 0;
307
 
308
				if (f->GetData() && f->GetDataSize())
143 cycrow 309
					data = (char *)f->UncompressData((long *)&size, NULL);
130 cycrow 310
				else if(f->isExternalFile())
311
					data = CFileIO(f->filePointer()).ReadToData(&size);
312
				if (newfile->GetData() && newfile->GetDataSize())
143 cycrow 313
					newData = (char *)f->UncompressData((long *)&newSize, NULL);
130 cycrow 314
				else
315
					newData = CFileIO(newfile->filePointer()).ReadToData(&newSize);
316
 
317
				// compare bytes
318
				bool matched = false;
319
				if (size == newSize)
320
				{
321
					matched = true;
322
					for (unsigned long i = 0; i < size; ++i)
323
					{
324
						if (data[i] != newData[i])
325
						{
326
							matched = false;
327
							break;
328
						}
329
					}
330
				}
331
 
143 cycrow 332
				if (data)
130 cycrow 333
					delete data;
143 cycrow 334
				if (newData)
130 cycrow 335
					delete newData;
336
 
337
				if (matched)
338
				{
339
					if(!f->game() || f->game() == GAME_ALLNEW)
340
						newfile->setGame(0);
341
					else
342
						newfile->setGame(newfile->game() | f->game());
343
					m_lFiles.remove(node, true);
344
					break;
345
				}
346
			}
6 cycrow 347
			continue;
130 cycrow 348
		}
6 cycrow 349
 
350
		// must already exist, delete this one
351
		m_lFiles.remove(node, true);
352
		break;
353
	}
354
 
88 cycrow 355
	_addFile(newfile);
6 cycrow 356
 
357
	return newfile;
358
}
359
 
360
bool CBaseFile::AddFileNow ( CyString file, CyString dir, int type, CProgressInfo *progress )
361
{
362
	C_File *f = AddFile ( file, dir, type );
363
	if ( !f->ReadFromFile () )
364
		return false;
365
 
366
	// compress the file
367
	return f->CompressData ( m_SHeader2.iDataCompression, progress );
368
}
369
 
155 cycrow 370
C_File *CBaseFile::appendFile(const Utils::String &file, int type, int game, bool packed, const Utils::String &dir, CProgressInfo *progress )
6 cycrow 371
{
155 cycrow 372
	C_File *newfile = addFile(file, dir, static_cast<FileType>(type), game, packed);
6 cycrow 373
	if ( !newfile )
374
		return NULL;
375
 
376
	// read the file into memory
155 cycrow 377
	if (newfile->GetData() && newfile->GetDataSize())
378
	{
379
		// now compress the file
380
		if (newfile->CompressData(m_SHeader2.iDataCompression, progress))
381
			return newfile;
382
	}
6 cycrow 383
	if ( newfile->ReadFromFile () )
384
	{
385
		// now compress the file
386
		if ( newfile->CompressData ( m_SHeader2.iDataCompression, progress ) )
387
			return newfile;
388
	}
389
	else if ( newfile->GetLastError() == SPKERR_MALLOC )
390
	{
391
		if ( newfile->CompressFile ( progress ) )
392
			return newfile;
393
	}
394
 
395
	m_lFiles.pop_back ();
396
	delete newfile;
397
 
398
	return NULL;
399
}
400
 
401
C_File *CBaseFile::FindFileAt ( int filetype, int pos )
402
{
403
	int count = 0;
404
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
405
	{
406
		C_File *file = node->Data();
407
		if ( file->GetFileType() != filetype )
408
			continue;
409
 
410
		if ( count == pos )
411
			return file;
412
 
413
		++count;
414
	}
415
 
416
	return NULL;
417
}
418
 
419
C_File *CBaseFile::FindFile ( CyString filename, int type, CyString dir, int game )
420
{
421
	CyString lfile = filename.ToLower();
422
	lfile = lfile.FindReplace ( "\\", "/" );
423
 
424
	lfile = lfile.GetToken ( lfile.NumToken('/'), '/' );
425
 
426
	CListNode<C_File> *node = m_lFiles.Front();
427
	while ( node )
428
	{
429
		C_File *f = node->Data();
430
		node = node->next();
431
 
432
		if ( type != f->GetFileType() )
433
			continue;
434
		if ( dir != f->GetDir() )
435
			continue;
127 cycrow 436
		if ( game != f->game() )
6 cycrow 437
			continue;
438
		if ( f->GetName().ToLower() == lfile )
439
			return f;
440
	}
441
	return NULL;
442
}
443
 
444
bool CBaseFile::RemoveFile ( CyString file, int type, CyString dir, int game )
445
{
446
	C_File *f = FindFile (file, type, dir, game);
447
	if ( !f )
448
		return false;
449
	return RemoveFile ( f );
450
}
451
 
452
bool CBaseFile::RemoveFile ( C_File *file )
453
{
454
	int count = 0;
455
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
456
	{
457
		C_File *f = node->Data();
458
		if ( f == file )
459
			return RemoveFile ( count );
460
		++count;
461
	}
462
	return false;
463
}
464
 
465
bool CBaseFile::RemoveFile ( int pos )
466
{
467
	if ( (pos < 0) || (pos >= m_lFiles.size()) )
468
		return false;
469
 
470
	C_File *file = m_lFiles.Get ( pos );
471
	m_lFiles.erase ( pos + 1 );
472
 
473
	if ( file )
474
		delete file;
475
 
50 cycrow 476
	_changed();
6 cycrow 477
 
478
	return true;
479
}
480
 
481
 
129 cycrow 482
void CBaseFile::removeAllFiles(FileType type, int game)
6 cycrow 483
{
484
	if ( m_lFiles.empty() )
485
		return;
486
 
487
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
488
	{
129 cycrow 489
		if (game == 0 && node->Data()->game() && node->Data()->game() != GAME_ALLNEW)
490
			continue;
491
		if ( game > -1 )
492
		{
493
			unsigned int fileGame = node->Data()->game() & ~GAME_ALLNEW;
494
			if (fileGame != (1 << game))
495
			{
496
				// just remove the game from file
497
				if (fileGame & (1 << game))
498
					node->Data()->setGame(node->Data()->game() & ~(1 << game));
6 cycrow 499
				continue;
129 cycrow 500
			}
6 cycrow 501
		}
129 cycrow 502
		if ( type == FILETYPE_UNKNOWN || node->Data()->GetFileType() == type )
6 cycrow 503
			node->DeleteData();
504
	}
505
 
506
	m_lFiles.RemoveEmpty();
507
 
50 cycrow 508
	_changed();
6 cycrow 509
}
510
 
511
void CBaseFile::RecompressAllFiles ( int type, CProgressInfo *progress )
512
{
513
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
514
	{
515
		C_File *file = node->Data();
516
		if ( progress )
517
			progress->UpdateFile(file);
518
 
519
		if ( file->GetCompressionType() == type )
520
			continue;
521
 
522
		if ( !file->GetData() )
523
			file->ReadFromFile();
524
 
525
		file->ChangeCompression ( type, progress );
526
	}
527
}
528
 
47 cycrow 529
void CBaseFile::CompressAllFiles ( int type, CProgressInfo *progress, CProgressInfo *overallProgress, int level )
6 cycrow 530
{
47 cycrow 531
	if ( overallProgress ) overallProgress->SetMax(m_lFiles.size());
532
 
533
	int iCount = 0;
6 cycrow 534
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
535
	{
536
		C_File *file = node->Data();
537
		if ( progress )
538
			progress->UpdateFile(file);
539
 
540
		if ( !file->GetData() )
541
			file->ReadFromFile();
542
 
543
		file->CompressData ( type, progress, level );
47 cycrow 544
 
545
		if ( overallProgress ) overallProgress->SetDone(++iCount);
6 cycrow 546
	}
547
}
548
 
549
bool CBaseFile::UncompressAllFiles ( CProgressInfo *progress )
550
{
551
	int countFile = 0;
552
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
553
	{
554
		C_File *fit = node->Data();
555
		if ( progress )
556
		{
557
			progress->UpdateFile ( fit );
558
			progress->UpdateProgress(countFile++, m_lFiles.size());
559
		}
560
 
561
		bool uncomprToFile = false;
562
 
563
		if ( progress )
564
			progress->SwitchSecond();
565
 
127 cycrow 566
		if(!fit->isExternalFile())
6 cycrow 567
		{
127 cycrow 568
			if (!fit->UncompressData(progress))
6 cycrow 569
			{
127 cycrow 570
				if (fit->GetCompressionType() == SPKCOMPRESS_7ZIP)
6 cycrow 571
				{
127 cycrow 572
					if (!fit->UncompressToFile("temp", this, false, progress))
573
						return false;
574
					else
575
					{
576
						uncomprToFile = true;
577
						fit->SetFullDir("temp");
578
					}
6 cycrow 579
				}
127 cycrow 580
 
581
				if (!uncomprToFile)
582
					return false;
6 cycrow 583
			}
584
		}
585
 
586
		if ( progress )
587
			progress->SwitchSecond();
588
	}
589
	return true;
590
}
591
 
592
long CBaseFile::GetFullFileSize()
593
{
594
	long fullsize = 1000;
595
 
596
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
597
		fullsize += node->Data()->GetUncompressedDataSize();
598
 
599
	if ( m_pIconFile )
600
		fullsize += m_pIconFile->GetUncompressedDataSize();
601
 
602
	return fullsize;
603
}
604
 
605
/*
606
	Func:   GetEndOfLine
607
	Input:  id - The file id for the current file to read from
608
	        line - Pointed to hold the line number thats read
609
			upper - true if it converts to uppercase
610
	Return: String - the string it has read
611
	Desc:   Reads a string from a file, simlar to readLine() classes, reads to the end of the line in a file
612
*/
613
CyString CBaseFile::GetEndOfLine ( FILE *id, int *line, bool upper )
614
{
615
	CyString word;
616
 
617
	char c = fgetc ( id );
618
	if ( c == -1 )
619
		return "";
620
 
621
	while ( (c != 13) && (!feof(id)) && (c != '\n') )
622
	{
623
		word += c;
624
		c = fgetc ( id );
625
	}
626
 
627
	if ( line )
628
		++(*line);
629
 
630
	if ( upper )
631
		return word.ToUpper();
632
 
633
	return word;
634
}
635
 
636
int CBaseFile::CountFiles ( int filetype )
637
{
638
	int i = 0;
639
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
640
	{
641
		C_File *file = node->Data();
642
		if ( file->GetFileType() != filetype )
643
			continue;
644
		++i;
645
	}
646
 
647
	return i;
648
}
649
 
650
void CBaseFile::ClearNames ()
651
{
652
	m_lNames.clear(true);
653
}
654
void CBaseFile::RemoveLanguageName ( int lang )
655
{
656
	SNames *n;
657
	for ( n = m_lNames.First(); n; n = m_lNames.Next() )
658
	{
659
		if ( n->iLanguage == lang )
660
		{
661
			m_lNames.RemoveCurrent();
662
			delete n;
50 cycrow 663
			_changed();
6 cycrow 664
		}
665
	}
666
}
667
 
46 cycrow 668
void CBaseFile::AddLanguageName ( int lang, const Utils::String &name )
6 cycrow 669
{
670
	// first check for an existing language
671
	SNames *n;
672
	for ( n = m_lNames.First(); n; n = m_lNames.Next() )
673
	{
674
		if ( n->iLanguage == lang )
675
		{
676
			n->sName = name;
677
			return;
678
		}
679
	}
680
 
681
	// not found, add a new entry
682
	n = new SNames;
683
	n->iLanguage = lang;
684
	n->sName = name;
685
	m_lNames.push_back ( n );
686
 
50 cycrow 687
	_changed();
6 cycrow 688
}
689
 
690
CyString CBaseFile::GetFullPackageName(CyString format, int lang)
691
{
692
	if ( format.Empty() )
693
		return GetFullPackageName(lang);
694
 
50 cycrow 695
	CyString args[3] = { this->GetLanguageName(lang), this->version(), this->author() };
6 cycrow 696
	return format.Args(args, 3);
697
}
698
 
699
/*
700
	Func:   CreateFilesLine
701
	Return: String - returns the full string for files list
702
	Desc:   Creates a signle line list of all the files
703
*/
704
CyString CBaseFile::CreateFilesLine ( bool updateheader, CProgressInfo *progress )
705
{
706
	CyString line;
707
 
708
	if ( progress )
709
	{
710
		progress->SetDone(0);
711
		progress->UpdateStatus(STATUS_COMPRESS);
712
	}
713
 
714
	if ( updateheader )
715
	{
716
		m_SHeader2.iNumFiles = 0;
717
		m_SHeader2.lFullSize = 0;
718
	}
719
 
720
	if ( m_pIconFile )
721
	{
722
		// no data, read it from file
723
		if ( !m_pIconFile->GetData() )
724
			m_pIconFile->ReadFromFile ();
725
 
726
		// compress the file
727
		if ( !m_pIconFile->CompressData ( m_SHeader2.iDataCompression, progress ) )
728
			m_pIconFile->SetDataCompression(SPKCOMPRESS_NONE);
729
 
730
		line += CyString("Icon:") + (m_pIconFile->GetDataSize() + (long)4) + ":" + m_pIconFile->GetUncompressedDataSize() + ":" + (long)m_pIconFile->GetCompressionType() + ":" + m_sIconExt + "\n";
731
		if ( updateheader )
732
		{
733
			++m_SHeader2.iNumFiles;
734
			m_SHeader2.lFullSize += (m_pIconFile->GetDataSize() + 4);
735
		}
736
	}
737
 
738
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
739
	{
740
		C_File *file = node->Data();
741
		if ( progress )
742
			progress->UpdateFile ( file );
743
 
744
		// no data, read it from file
745
		if ( !file->GetData() )
746
		{
747
			if ( !file->ReadFromFile () )
748
			{
749
				if ( file->GetLastError() == SPKERR_MALLOC )
750
				{
751
					if ( !file->CompressFile ( progress ) )
752
						continue;
753
				}
754
			}
755
		}
756
 
757
		if ( !file->GetData() )
758
			continue;
759
 
760
		// compress the file
761
		if ( !file->CompressData ( m_SHeader2.iDataCompression, progress ) )
762
		{
763
			file->SetDataCompression(SPKCOMPRESS_NONE);
764
			file->SetUncompressedDataSize(file->GetDataSize());
765
		}
766
 
767
		CyString command = GetFileTypeString ( file->GetFileType() );
768
		if ( command.Empty() )
769
			continue;
770
 
771
		if ( file->IsShared() )
772
			command = CyString("$") + command;
773
 
774
		if ( file->GetDir().Empty() )
128 cycrow 775
			line += (command + ":" + (file->GetDataSize() + (long)4) + ":" + file->GetUncompressedDataSize() + ":" + (long)file->GetCompressionType() + ":" + (long)file->GetCreationTime() + ":" + ((file->IsCompressedToFile()) ? "1" : "0") + ":" + file->GetFilename() + ":NULL:" + (long)file->game() + "\n");
6 cycrow 776
		else
128 cycrow 777
			line += (command + ":" + (file->GetDataSize() + (long)4) + ":" + file->GetUncompressedDataSize() + ":" + (long)file->GetCompressionType() + ":" + (long)file->GetCreationTime() + ":" + ((file->IsCompressedToFile()) ? "1" : "0") + ":" + file->GetFilename() + ":" + file->GetDir() + ":" + (long)file->game() + "\n");
6 cycrow 778
 
779
		if ( updateheader )
780
		{
781
			++m_SHeader2.iNumFiles;
782
			m_SHeader2.lFullSize += (file->GetDataSize() + 4);
783
		}
784
	}
785
 
786
	return line;
787
}
788
 
789
 
790
/*
791
######################################################################################
792
##########							Reading Functions			    		##########
793
######################################################################################
794
*/
795
 
796
void CBaseFile::ReadAllFilesToMemory ()
797
{
798
	// no file to read from
50 cycrow 799
	if ( this->filename().empty() ) return;
6 cycrow 800
 
801
	// now open the file
58 cycrow 802
	CFileIO File(this->filename());
803
	if ( !File.startRead() ) return;
6 cycrow 804
 
805
	// read the header
58 cycrow 806
	File.readEndOfLine();
6 cycrow 807
	// skip past values
58 cycrow 808
	File.seek(4 + m_SHeader.lValueCompressSize);
6 cycrow 809
 
810
	// read the next header
58 cycrow 811
	File.readEndOfLine();
6 cycrow 812
	// skip past files
58 cycrow 813
	File.seek(4 + m_SHeader2.lSize);
6 cycrow 814
 
815
	if ( m_pIconFile )
816
	{
817
		if ( (!m_pIconFile->GetData()) && (!m_pIconFile->Skip()) )
51 cycrow 818
			m_pIconFile->readFromFile(File, m_pIconFile->GetDataSize());
6 cycrow 819
		else
58 cycrow 820
			File.seek(4 + m_pIconFile->GetDataSize());
6 cycrow 821
	}
822
 
823
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
824
	{
825
		C_File *fit = node->Data();
826
		if ( (!fit->GetData()) && (!fit->Skip()) )
51 cycrow 827
			fit->readFromFile(File, fit->GetDataSize());
6 cycrow 828
		else
58 cycrow 829
			File.seek(4 + fit->GetDataSize());
6 cycrow 830
	}
831
 
51 cycrow 832
	File.close();
6 cycrow 833
}
834
 
835
bool CBaseFile::ReadFileToMemory(C_File *f)
836
{
62 cycrow 837
	if ( this->filename().empty() || !f ) return false;		// no filename to load from
51 cycrow 838
	if ( f->GetData() && f->GetDataSize() ) return true;	// already loaded the data
839
	if ( !m_lFiles.FindData(f) ) return false;				// unable to find file entry
6 cycrow 840
 
841
	// now open the file
58 cycrow 842
	CFileIO *File = _startRead();
843
	if ( !File ) return false;
6 cycrow 844
 
58 cycrow 845
	if ( m_pIconFile ) File->seek(4 + m_pIconFile->GetDataSize());
51 cycrow 846
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
6 cycrow 847
		C_File *fit = node->Data();
51 cycrow 848
		if (fit == f ) {
58 cycrow 849
			fit->readFromFile(*File, fit->GetDataSize());
6 cycrow 850
			break;
851
		}
58 cycrow 852
		else File->seek(4 + fit->GetDataSize());
6 cycrow 853
	}
854
 
58 cycrow 855
	delete File;
6 cycrow 856
	return true;
857
}
858
 
58 cycrow 859
CFileIO *CBaseFile::_startRead()
6 cycrow 860
{
861
	// no file to read from
58 cycrow 862
	if ( this->filename().empty() ) return NULL;
6 cycrow 863
 
864
	// now open the file
58 cycrow 865
	CFileIO *File = new CFileIO(this->filename());
866
	if ( !File->startRead() ) return NULL;
6 cycrow 867
 
868
	// read the header
58 cycrow 869
	File->readEndOfLine();
6 cycrow 870
	// skip past values
58 cycrow 871
	File->seek(4 + m_SHeader.lValueCompressSize);
6 cycrow 872
 
873
	// read the next header
58 cycrow 874
	File->readEndOfLine();
6 cycrow 875
	// skip past files
58 cycrow 876
	File->seek(4 + m_SHeader2.lSize);
6 cycrow 877
 
58 cycrow 878
	return File;
879
}
6 cycrow 880
 
88 cycrow 881
void CBaseFile::_addFile(C_File *file, bool dontChange)
882
{
883
	if ( !dontChange ) {
884
		file->UpdateSigned();
885
		_changed();
886
	}
887
	m_lFiles.push_back(file);
888
 
889
	_updateTextDB(file);
890
}
891
 
892
void CBaseFile::_updateTextDB(C_File *file)
893
{
894
	if ( !_pTextDB ) _pTextDB = new CTextDB();
895
 
896
	if ( file->GetFileType() == FILETYPE_TEXT ) {
897
		Utils::String baseFile = CFileIO(file->filePointer()).baseName();
898
		int lang = (baseFile.isin("-L")) ? baseFile.right(3) : baseFile.truncate(-4);
899
 
900
		// read in the text file to the database
901
		_pTextDB->parseTextFile(0, 0, file->filePointer(), lang);
902
	}
903
}
904
 
905
void CBaseFile::_resetTextDB()
906
{
907
	if ( _pTextDB ) delete _pTextDB;
908
	_pTextDB = new CTextDB();
909
 
910
	for(CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next()) {
911
		_updateTextDB(node->Data());
912
	}
913
}
914
 
58 cycrow 915
void CBaseFile::ReadIconFileToMemory ()
916
{
917
	if ( !m_pIconFile )	return;
918
	CFileIO *File = _startRead();
919
	if ( !File ) return;
920
 
921
	if ( (!m_pIconFile->GetData()) && (!m_pIconFile->Skip()) )
922
		m_pIconFile->readFromFile(*File, m_pIconFile->GetDataSize());
923
	else
924
		File->seek(4 + m_pIconFile->GetDataSize());
925
 
926
	delete File;
6 cycrow 927
}
928
 
14 cycrow 929
void CBaseFile::_install_adjustFakePatches(CPackages *pPackages)
6 cycrow 930
{
931
	CyStringList lPatches;
14 cycrow 932
	int startfake = pPackages->FindNextFakePatch();
6 cycrow 933
 
14 cycrow 934
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
935
	{
936
		C_File *fit = node->Data();
937
		// only do fake patchs
938
		if ( !fit->IsFakePatch() )
939
			continue;
940
 
941
		// we should only have cat and dat files, but lets check just incase they have been added incorrectly
942
		if ( !fit->CheckFileExt ("cat") && !fit->CheckFileExt("dat") )
943
			continue;
944
 
945
		// search for the name on the list
946
		SStringList *opposite = lPatches.FindString(fit->GetBaseName());
947
		CyString newname;
948
		if ( opposite )
949
			newname = opposite->data;
950
		else
951
		{
952
			newname = CyString::Number((long)startfake).PadNumber(2);
953
			lPatches.PushBack(fit->GetBaseName(), newname);
954
		}
955
 
956
		// rename the file
957
		fit->FixOriginalName();
50 cycrow 958
		CLog::logf(CLog::Log_Install, 2, "Adjusting fake patch number, %s => %s", fit->GetNameDirectory(this).c_str(), (newname + "." + fit->GetFileExt()).c_str());
14 cycrow 959
		fit->SetName ( newname + "." + fit->GetFileExt() );
960
 
961
		// find the next gap
962
		if ( !opposite ) {
963
			startfake = pPackages->FindNextFakePatch(startfake + 1);
964
		}
965
	}
966
 
967
}
968
 
43 cycrow 969
void CBaseFile::_install_renameText(CPackages *pPackages)
14 cycrow 970
{
130 cycrow 971
	int starttext = pPackages->findNextTextFile();
43 cycrow 972
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
973
		C_File *fit = node->Data();
130 cycrow 974
		if ( !fit->isAutoTextFile() )
43 cycrow 975
			continue;
6 cycrow 976
 
130 cycrow 977
		Utils::String newname = SPK::FormatTextName(starttext, pPackages->GetLanguage(), (pPackages->GetCurrentGameFlags() & EXEFLAG_TCTEXT));
43 cycrow 978
		fit->FixOriginalName();
130 cycrow 979
		CLog::logf(CLog::Log_Install, 2, "Adjusting text file, %s => %s", fit->getNameDirectory(this).c_str(), (newname + "." + fit->fileExt()).c_str());
980
		fit->setName(newname + "." + fit->fileExt());
6 cycrow 981
 
43 cycrow 982
		++starttext;
983
	}
984
}
6 cycrow 985
 
50 cycrow 986
bool CBaseFile::_install_setEnabled(bool bEnable, C_File *fit)
987
{
988
	if ( !bEnable )
989
	{
990
		if ( (fit->GetFileType() == FILETYPE_UNINSTALL) || (fit->GetFileType() == FILETYPE_README) || (fit->GetFileType() == FILETYPE_ADVERT) )
991
			bEnable = true;
992
		else if ( (fit->GetFileType() == FILETYPE_EXTRA) && (fit->GetDir().Left(7).ToLower() == "Extras/") )
993
			bEnable = true;
994
		else if ( (IsPatch()) && (fit->GetFileType() == FILETYPE_MOD) && (!fit->IsFakePatch()) )
995
			bEnable = true;
996
 
997
		if ( bEnable ) CLog::logf(CLog::Log_Install, 3, "Filetype(%d) is always enabled, setting enabled flag", fit->GetFileType());
998
	}
999
 
1000
	return bEnable;
1001
}
1002
 
1003
bool CBaseFile::_install_uncompress(C_File *fit, CProgressInfo *progress, CyStringList *errorStr, bool *uncomprToFile)
1004
{
1005
	*uncomprToFile = false;
134 cycrow 1006
	_sLastError = fit->getNameDirectory(this);
1007
	_iLastError = SPKERR_UNCOMPRESS;
96 cycrow 1008
 
50 cycrow 1009
	if ( !fit->UncompressData ( progress ) )
1010
	{
1011
		CLog::log(CLog::Log_Install, 2, "Failed to uncompress data, attempting file decompression");
1012
		if ( fit->GetCompressionType() == SPKCOMPRESS_7ZIP )
1013
		{
1014
			if ( fit->UncompressToFile ( NullString, this, false, progress ) )
1015
				*uncomprToFile = true;
1016
		}
1017
 
1018
		if ( !uncomprToFile )
1019
		{
1020
			if ( errorStr )
134 cycrow 1021
				errorStr->PushBack(CyString(_sLastError), ERRORLOG_OLD(SPKINSTALL_UNCOMPRESS_FAIL));
50 cycrow 1022
			CLog::log(CLog::Log_Install, 1, "Unable to decompress file, skipping");
1023
			return false;
1024
		}
1025
	}
1026
	ClearError ();
1027
 
1028
	return true;
1029
}
1030
 
1031
bool CBaseFile::_install_checkVersion(C_File *pFile, const Utils::String &sDestination)
1032
{
1033
	// new check if we should install the file
1034
	// first get the version
1035
	if ( !m_bOverrideFiles && pFile->ReadScriptVersion() )
1036
	{
1037
		CLog::log(CLog::Log_Install, 2, "Checking for existing file version");
1038
		C_File checkfile;
1039
		CyString checkfilename = sDestination;
1040
		if ( !checkfilename.Empty() ) checkfilename += "/";
1041
		checkfilename += pFile->GetNameDirectory(this);
1042
		checkfile.SetFilename ( checkfilename );
127 cycrow 1043
		checkfile.setFileType(pFile->fileType());
50 cycrow 1044
		if ( checkfile.CheckValidFilePointer() ) {
1045
			if ( checkfile.ReadScriptVersion() > pFile->GetVersion() ) {
1046
				CLog::log(CLog::Log_Install, 1, "Newer version of the file found in directory, skipping");
1047
				return false;
1048
			}
1049
		}
1050
	}
1051
 
1052
	return true;
1053
}
1054
 
1055
Utils::String CBaseFile::_install_adjustFilepointer(C_File *pFile, bool bEnabled, const Utils::String &sDestination)
1056
{
130 cycrow 1057
	Utils::String filename = sDestination;
1058
	if ( !filename.empty() ) filename += "/";
50 cycrow 1059
 
130 cycrow 1060
	if ( (IsPatch()) && (pFile->fileType() == FILETYPE_MOD) )
50 cycrow 1061
		pFile->SetDir ( CyString("Patch") );
1062
 
1063
	if ( pFile->IsInMod() )
1064
	{
1065
		if ( bEnabled )
130 cycrow 1066
			pFile->setFilename(filename + pFile->GetInMod().ToString() + "::" + pFile->getNameDirectory(this));
50 cycrow 1067
		else
130 cycrow 1068
			pFile->setFilename(filename + "PluginManager/DisabledFiles.cat::" + pFile->getNameDirectory(this));
50 cycrow 1069
	}
1070
	else
130 cycrow 1071
		pFile->setFilename ( filename + pFile->getNameDirectory(this) );
50 cycrow 1072
 
1073
	if ( !bEnabled )
1074
	{
1075
		if ( !pFile->IsInMod() )
1076
		{
1077
			if ( pFile->IsFakePatch() )
130 cycrow 1078
				pFile->setFilename ( filename + "PluginManager/Disabled/FakePatches/FakePatch_" + this->getNameValidFile() + "_" + this->author() + "_" + pFile->name() );
1079
			else if ( pFile->isAutoTextFile() )
1080
				pFile->setFilename ( filename + "PluginManager/Disabled/TextFiles/Text_" + this->getNameValidFile() + "_" + this->author() + "_" + pFile->name() );
50 cycrow 1081
			else
130 cycrow 1082
				pFile->SetFullDir ( filename + "PluginManager/Disabled/" + pFile->getDirectory(this) );
50 cycrow 1083
		}
1084
		pFile->SetDisabled(true);
1085
	}
1086
 
129 cycrow 1087
	CLog::logf(CLog::Log_Install, 2, "Adjusting the file pointer to correct install destintation, %s", pFile->filePointer().c_str());
50 cycrow 1088
 
130 cycrow 1089
	return filename;
50 cycrow 1090
}
1091
 
1092
C_File *CBaseFile::_install_checkFile(C_File *pFile, CyStringList *errorStr, bool *bDoFile, CLinkList<C_File> *pFileList)
1093
{
1094
	if ( !pFile->IsFakePatch() && pFile->GetFileType() != FILETYPE_README )
1095
	{
1096
		C_File *cFile;
1097
		for ( cFile = pFileList->First(); cFile; cFile = pFileList->Next() )
1098
		{
1099
			if ( !cFile->MatchFile(pFile) ) continue;
1100
			if ( !m_bOverrideFiles && !cFile->CompareNew(pFile) ) {
134 cycrow 1101
				if ( errorStr ) errorStr->PushBack(pFile->GetNameDirectory(this), ERRORLOG_OLD(SPKINSTALL_SKIPFILE));
50 cycrow 1102
				CLog::log(CLog::Log_Install, 1, "Newer version of the file already installed, skipping");
1103
				*bDoFile = false;
1104
			}
1105
			break;
1106
		}
1107
 
1108
		return cFile;
1109
	}
1110
 
1111
	return NULL;
1112
}
1113
 
1114
bool CBaseFile::_install_checkFileEnable(C_File *pCheckFile, C_File *fit, const Utils::String &sDestination, bool bEnabled, CyStringList *errorStr)
1115
{
1116
	// found a file, check if its in the disabled directory
125 cycrow 1117
	Utils::String dir = CFileIO(pCheckFile->filePointer()).dir();
1118
	Utils::String lastDir = CDirIO(dir).topDir().lower();
50 cycrow 1119
 
1120
	// if its disabled, rename it so its enabled
125 cycrow 1121
	if ( ((pCheckFile->IsDisabled()) || (lastDir == "disabled") || (dir.lower().isin("/disabled/"))) && (bEnabled) )
50 cycrow 1122
	{
125 cycrow 1123
		CLog::logf(CLog::Log_Install, 2, "Existing file, %s, is disabled, re-enabling it", pCheckFile->filePointer().c_str());
50 cycrow 1124
		// first check if the directory exists
1125
		if ( pCheckFile->IsInMod() ) {
125 cycrow 1126
			CyString tofile = pCheckFile->filePointer().token("::", 2);
50 cycrow 1127
 
1128
			CCatFile tocat;
125 cycrow 1129
			int err = tocat.open(fit->filePointer().token("::", 1), "", CATREAD_CATDECRYPT, true);
50 cycrow 1130
			if ( (err == CATERR_NONE) || (err == CATERR_CREATED) ) {
129 cycrow 1131
				tocat.AppendFile(pCheckFile->filePointer(), tofile.ToString());
125 cycrow 1132
				CLog::logf(CLog::Log_Install, 2, "Adding existing file into new mod File, %s => %s", fit->filePointer().token("::", 1).c_str(), tofile.c_str());
50 cycrow 1133
			}
1134
 
1135
			CCatFile fromcat;
125 cycrow 1136
			err = fromcat.open(pCheckFile->filePointer().token("::", 1), "", CATREAD_CATDECRYPT, false);
50 cycrow 1137
			if ( err == CATERR_NONE ) {
124 cycrow 1138
				fromcat.removeFile(tofile.ToString());
125 cycrow 1139
				CLog::logf(CLog::Log_Install, 2, "Removing file from existing mod, %s::%s", pCheckFile->filePointer().token("::", 1).c_str(), tofile.c_str());
50 cycrow 1140
			}
1141
 
125 cycrow 1142
			CLog::logf(CLog::Log_Install, 1, "Adjusting existing file name %s => %s", pCheckFile->filePointer().c_str(), fit->filePointer().c_str());
50 cycrow 1143
			pCheckFile->SetFilename ( fit->GetFilePointer() );
1144
			CLog::logf(CLog::Log_Install, 2, "Adjusting In Mod setting, %s => %s", pCheckFile->GetInMod().c_str(), fit->GetInMod().c_str());
1145
			pCheckFile->SetInMod(fit->GetInMod());
1146
		}
1147
		else {
1148
			CyString to = pCheckFile->GetDirectory(this);
1149
			CDirIO Dir(sDestination);
121 cycrow 1150
			if ( !Dir.exists(to.ToString()) ) {
50 cycrow 1151
				if ( !Dir.Create ( to ) ) {
134 cycrow 1152
					if ( errorStr )	errorStr->PushBack(to, ERRORLOG_OLD(SPKINSTALL_CREATEDIRECTORY_FAIL));
50 cycrow 1153
					return false;
1154
				}
134 cycrow 1155
				if ( errorStr )	errorStr->PushBack(to, ERRORLOG_OLD(SPKINSTALL_CREATEDIRECTORY));
50 cycrow 1156
			}
1157
 
1158
			CyString destfile = CyString(sDestination) + "/" + pCheckFile->GetNameDirectory(this);
52 cycrow 1159
			if ( CFileIO(destfile).ExistsOld() ) CFileIO::Remove(destfile.ToString());
50 cycrow 1160
			CLog::logf(CLog::Log_Install, 1, "Adjusting existing filename, %s => %s", pCheckFile->GetFilePointer().c_str(), destfile.c_str());
1161
			rename ( pCheckFile->GetFilePointer().c_str(), destfile.c_str() );
1162
			pCheckFile->SetFilename ( CyString(sDestination) + "/" + pCheckFile->GetNameDirectory(this) );
1163
		}
1164
		pCheckFile->SetDisabled(false);
1165
 
134 cycrow 1166
		if ( errorStr ) errorStr->PushBack(pCheckFile->GetNameDirectory(this), ERRORLOG_OLD(SPKINSTALL_ENABLEFILE));
50 cycrow 1167
	}
1168
 
1169
	return true;
1170
}
51 cycrow 1171
 
1172
bool CBaseFile::_install_createDirectory(CDirIO &Dir, const Utils::String &sTo, C_File *pFile, CyStringList *errorStr)
1173
{
134 cycrow 1174
	_sLastError = sTo;
1175
	if ( !sTo.contains( "::" ) )
51 cycrow 1176
	{
121 cycrow 1177
		if ( !Dir.exists(sTo) )
51 cycrow 1178
		{
1179
			CLog::logf(CLog::Log_Install, 2, "Creating directory to install file into, %s", sTo.c_str());
1180
			if ( !Dir.Create(sTo) )
1181
			{
1182
				if ( errorStr )
134 cycrow 1183
					errorStr->PushBack(CyString(sTo), ERRORLOG_OLD(SPKINSTALL_CREATEDIRECTORY_FAIL));
51 cycrow 1184
				return false;
1185
			}
1186
			if ( errorStr )
134 cycrow 1187
				errorStr->PushBack(CyString(sTo), ERRORLOG_OLD(SPKINSTALL_CREATEDIRECTORY));
51 cycrow 1188
		}
1189
	}
1190
	else {
129 cycrow 1191
		CLog::logf(CLog::Log_Install, 2, "Adjusting file extension for file in mod, %s => %s", pFile->filePointer().c_str(), CCatFile::PckChangeExtension(pFile->filePointer()).c_str());
134 cycrow 1192
		pFile->setFilename(CCatFile::PckChangeExtension(pFile->filePointer()));
51 cycrow 1193
	}
1194
 
1195
	return true;
1196
}
1197
 
1198
void CBaseFile::_install_writeFile(C_File *pFile, const Utils::String &sDestination, CyStringList *errorStr)
1199
{
134 cycrow 1200
	_iLastError = SPKERR_WRITEFILE;
1201
	_sLastError = pFile->filePointer();
1202
	Utils::String sInstalledFile = pFile->getNameDirectory(this);
51 cycrow 1203
	if ( pFile->IsDisabled() )
1204
	{
134 cycrow 1205
		sInstalledFile = pFile->filePointer().findRemove(sDestination);
51 cycrow 1206
		if ( sInstalledFile[0] == '/' || sInstalledFile[0] == '\\' )
134 cycrow 1207
			sInstalledFile.erase(0, 1);
51 cycrow 1208
	}
1209
 
129 cycrow 1210
	if ( !pFile->writeFilePointer() )
51 cycrow 1211
	{
1212
		CLog::log(CLog::Log_Install, 1, "Failed to write the file");
1213
		if ( errorStr )
134 cycrow 1214
			errorStr->PushBack(CyString(sInstalledFile), ERRORLOG_OLD(SPKINSTALL_WRITEFILE_FAIL));
51 cycrow 1215
	}
1216
	else
1217
	{
1218
		CLog::log(CLog::Log_Install, 1, "File written successfully");
1219
		CLog::log(CLog::Log_Install, 2, "Checking signed status of the file");
1220
		pFile->UpdateSigned();
1221
		if ( errorStr )
134 cycrow 1222
			errorStr->PushBack(CyString(sInstalledFile), ERRORLOG_OLD(SPKINSTALL_WRITEFILE));
51 cycrow 1223
 
1224
		switch(pFile->GetFileType())
1225
		{
1226
			case FILETYPE_SCRIPT:
1227
			case FILETYPE_UNINSTALL:
1228
				CLog::log(CLog::Log_Install, 2, "Updating file signature");
1229
				pFile->UpdateSignature();
1230
				break;
1231
		}
1232
	}
1233
}
1234
 
43 cycrow 1235
bool CBaseFile::InstallFiles ( CyString destdir, CProgressInfo *progress, CLinkList<C_File> *filelist, CyStringList *errorStr, bool enabled, CPackages *packages )
1236
{
50 cycrow 1237
	//TODO: add errorStr and progress as member variables
43 cycrow 1238
	if ( enabled ) {
14 cycrow 1239
		this->_install_adjustFakePatches(packages);
43 cycrow 1240
		if ( packages ) this->_install_renameText(packages);
6 cycrow 1241
	}
1242
 
50 cycrow 1243
	bool bFailed = false;
1244
 
6 cycrow 1245
	CDirIO Dir(destdir);
1246
	int fileCount = 0;
1247
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
1248
	{
1249
		C_File *fit = node->Data();
1250
 
50 cycrow 1251
		// start the install process, check if we need to the file enabled or disabled
1252
		CLog::logf(CLog::Log_Install, 1, "Preparing to install file: %s", fit->GetNameDirectory(this).c_str());
1253
		bool fileEnabled = _install_setEnabled(enabled, fit);
1254
 
1255
		// check if the file is for the correct game version
147 cycrow 1256
		if (!fit->isForGame(packages->GetGame())) 
1257
		{
1258
			CLog::logf(CLog::Log_Install, 1, "File didn't match game version, skipping, %d != %d", fit->game(), packages->GetGame());
1259
			continue;
6 cycrow 1260
		}
1261
 
50 cycrow 1262
		// update the progress display to show we are processing this file
1263
		if ( progress ) {
1264
			if ( progress->IsSecond() ) progress->SwitchSecond();
6 cycrow 1265
			progress->UpdateFile ( fit );
1266
			progress->UpdateProgress(fileCount++, m_lFiles.size());
1267
			progress->SwitchSecond();
1268
		}
1269
 
1270
		// first uncompress the file
50 cycrow 1271
		//TODO: add this flag to C_File
1272
		bool uncomprToFile;
1273
		if ( !this->_install_uncompress(fit, progress, errorStr, &uncomprToFile) ) {
1274
			bFailed = true;
1275
			continue;
6 cycrow 1276
		}
1277
 
50 cycrow 1278
		bool dofile = _install_checkVersion(fit, destdir.ToString());
6 cycrow 1279
 
1280
		// change file pointer
125 cycrow 1281
		Utils::String sInstallDir = _install_adjustFilepointer(fit, fileEnabled, destdir.ToString());
6 cycrow 1282
 
1283
		C_File *adjustPointer = NULL;
1284
 
50 cycrow 1285
		if ( filelist ) {
98 cycrow 1286
			C_File *cFile = _install_checkFile(fit, errorStr, &dofile, filelist);
6 cycrow 1287
 
1288
			// no matching file found, adding to main list
50 cycrow 1289
			if ( !cFile ) filelist->push_back ( fit );
6 cycrow 1290
			else
1291
			{
1292
				// if the file is not enabled, we need to check for any that might be enabled
51 cycrow 1293
				if ( !fileEnabled ) //_install_checkDisabled(cFile, destdir, errorStr);
6 cycrow 1294
				{
50 cycrow 1295
					//TODO: check what this is actually doing
6 cycrow 1296
					if ( !cFile->GetUsed() )
1297
					{
1298
						CFileIO rFile(cFile->GetFilePointer());
52 cycrow 1299
						if ( rFile.exists() )
6 cycrow 1300
						{
1301
							if ( errorStr )
1302
							{
52 cycrow 1303
								if ( rFile.remove() )
134 cycrow 1304
									errorStr->PushBack(cFile->GetFilePointer().Remove(destdir), ERRORLOG_OLD(SPKINSTALL_DELETEFILE));
6 cycrow 1305
								else
134 cycrow 1306
									errorStr->PushBack(cFile->GetFilePointer().Remove(destdir), ERRORLOG_OLD(SPKINSTALL_DELETEFILE_FAIL));
6 cycrow 1307
							}
1308
						}
1309
						cFile->SetFilename(fit->GetFilePointer());
1310
						cFile->SetDisabled(true);
1311
					}
1312
					else
1313
					{
125 cycrow 1314
						fit->SetFullDir ( CyString(sInstallDir) + fit->GetDirectory(this) );
51 cycrow 1315
						fit->SetDisabled(false);
6 cycrow 1316
					}
1317
				}
1318
				// move it to enabled
50 cycrow 1319
				else {
1320
					if ( !this->_install_checkFileEnable(cFile, fit, destdir.ToString(), fileEnabled, errorStr) ) {
1321
						bFailed = true;
1322
						continue;
6 cycrow 1323
					}
1324
				}
1325
 
1326
				adjustPointer = cFile;
50 cycrow 1327
				if ( dofile ) adjustPointer->SetCreationTime(fit->GetCreationTime());
6 cycrow 1328
			}
1329
		}
1330
 
1331
		if ( dofile )
1332
		{
1333
			// uncompressed to file, rename and move
1334
			if ( uncomprToFile )
1335
			{
134 cycrow 1336
				_iLastError = SPKERR_WRITEFILE;
1337
				Utils::String to = fit->getDirectory(this);
1338
				if ( !fileEnabled )	to = "PluginManager/Disabled/" + to;
6 cycrow 1339
 
134 cycrow 1340
				if ( !_install_createDirectory(Dir, to, fit, errorStr) ) {
51 cycrow 1341
					bFailed = true;
1342
					continue;
6 cycrow 1343
				}
1344
 
1345
				int err = 1;
134 cycrow 1346
				_sLastError = to;
51 cycrow 1347
				if ( !fit->GetTempFile ().Empty() )	err = rename ( fit->GetTempFile().c_str(), to.c_str() );
1348
				if ( err ) {
1349
					bFailed = true;
1350
					continue;
1351
				}
6 cycrow 1352
			}
1353
			//otherwise, just extract the file
1354
			else
1355
			{
1356
				// old file is found in list, switch to using new one
50 cycrow 1357
				if ( (filelist) && (adjustPointer) ) {
6 cycrow 1358
					adjustPointer->CopyData(fit, false);
50 cycrow 1359
					CLog::log(CLog::Log_Install, 2, "Copying data into existing file");
1360
				}
6 cycrow 1361
 
134 cycrow 1362
				Utils::String fpointer = fit->filePointer();
1363
				_iLastError = SPKERR_CREATEDIRECTORY;
1364
				Utils::String dir = CFileIO(fit->filePointer()).dir();
6 cycrow 1365
 
134 cycrow 1366
				dir = dir.findRemove(destdir.ToString());
149 cycrow 1367
				if (!dir.empty() && (dir[0] == '/' || dir[0] == '\\')) 
1368
					dir.erase(0, 1);
6 cycrow 1369
 
134 cycrow 1370
				if ( !_install_createDirectory(Dir, dir, fit, errorStr) ) {
51 cycrow 1371
					bFailed = true;
1372
					continue;
6 cycrow 1373
				}
1374
 
51 cycrow 1375
				_install_writeFile(fit, destdir.ToString(), errorStr);
6 cycrow 1376
			}
1377
			ClearError ();
1378
		}
1379
 
1380
		if ( adjustPointer )
1381
		{
50 cycrow 1382
			CLog::log(CLog::Log_Install, 2, "Adjusting pointers to existing file and deleting new file pointer");
6 cycrow 1383
			node->ChangeData(adjustPointer);
1384
			delete fit;
1385
		}
50 cycrow 1386
 
1387
		CLog::log(CLog::Log_Install, 1, "File installation completed");
6 cycrow 1388
	}
1389
 
1390
	// now clear or data memory
50 cycrow 1391
	CLog::log(CLog::Log_Install, 2, "Delting temporary file data from memory");
51 cycrow 1392
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) node->Data()->DeleteData();
6 cycrow 1393
 
50 cycrow 1394
	return !bFailed;
6 cycrow 1395
}
1396
 
1397
/*######################################################################################################*/
1398
 
1399
 
1400
/*
1401
	Func:   ParseHeader
1402
	Input:  Header String - string formated directly from the file
1403
	Return: Boolean - If string is a valid header
1404
	Desc:   Splits up the main header string to get all required settings
1405
*/
1406
bool CBaseFile::ParseHeader ( CyString header )
1407
{
14 cycrow 1408
	if ( !this->CheckHeader(header.GetToken ( 1, ';' ).ToString()) )
6 cycrow 1409
		return false;
1410
 
1411
	m_SHeader.fVersion = header.GetToken ( 2, ';' ).ToFloat();
1412
	if ( m_SHeader.fVersion > FILEVERSION )
1413
		return false;
1414
 
1415
	m_SHeader.iValueCompression = header.GetToken ( 3, ';' ).ToInt();
1416
	m_SHeader.lValueCompressSize = header.GetToken ( 4, ';' ).ToLong();
1417
 
1418
	return true;
1419
}
1420
 
14 cycrow 1421
bool CBaseFile::CheckHeader(const Utils::String header) const
6 cycrow 1422
{
1423
	if ( header.Compare("BaseCycrow") )
1424
		return true;
1425
	return false;
1426
}
1427
 
1428
/*
1429
	Func:   ParseFileHeader
1430
	Input:  Header String - string formated directly from the file
1431
	Return: Boolean - If string is a valid header
1432
	Desc:   Splits up the file header string to get all required settings
1433
*/
1434
bool CBaseFile::ParseFileHeader ( CyString header )
1435
{
1436
	if ( header.GetToken ( 1, ';' ) != "FileHeader" )
1437
		return false;
1438
 
1439
	m_SHeader2.iNumFiles = header.GetToken ( 2, ';' ).ToInt();
1440
	m_SHeader2.lSize = header.GetToken ( 3, ';' ).ToInt();
1441
	m_SHeader2.lFullSize = header.GetToken ( 4, ';' ).ToInt();
1442
	m_SHeader2.iFileCompression = header.GetToken ( 5, ';' ).ToInt();
1443
	m_SHeader2.iDataCompression = header.GetToken ( 6, ';' ).ToInt();
1444
 
1445
	return true;
1446
}
1447
 
1448
 
1449
/*
1450
	Func:   ParseValueLine
1451
	Input:  String - single line from a file to set
1452
	Return: Boolean - returns true if value exists
1453
	Desc:   Reads the line and assigns the parameters for the file
1454
*/
14 cycrow 1455
bool CBaseFile::ParseValueLine(const Utils::String &sLine)
6 cycrow 1456
{
14 cycrow 1457
	Utils::String first = sLine.token(" ", 1);
1458
	Utils::String rest  = sLine.tokens(" ", 2);
6 cycrow 1459
 
50 cycrow 1460
	if ( first.Compare("Name:") )					this->setName(rest);
1461
	else if ( first.Compare("Author:") )			this->setAuthor(rest);
1462
	else if ( first.Compare("Version:") )			this->setVersion(rest);
14 cycrow 1463
	else if ( first.Compare("fGameVersion:") ) {
6 cycrow 1464
		if ( m_lGames.Back() ) {
1465
			m_lGames.Back()->Data()->sVersion = rest;
1466
		}
1467
	}
14 cycrow 1468
	else if ( first.Compare("GameVersion:") ) {
6 cycrow 1469
		if ( m_lGames.Back() ) {
14 cycrow 1470
			m_lGames.Back()->Data()->iVersion = rest;
6 cycrow 1471
		}
1472
	}
14 cycrow 1473
	else if ( first.Compare("Game:") )
46 cycrow 1474
		this->AddGameCompatability(rest, "");
14 cycrow 1475
	else if ( first.Compare("GameCompat:") )
1476
		this->AddGameCompatability(rest.token(" ", 1), rest.tokens(" ", 2));
1477
	else if ( first.Compare("GameCompatExact:") )
1478
		this->AddGameCompatability(rest.token(" ", 1), rest.tokens(" ", 2));
50 cycrow 1479
	else if ( first.Compare("Date:") )				this->setCreationDate(rest);
49 cycrow 1480
	else if ( first.Compare("WebAddress:") )		this->setWebAddress(rest);
1481
	else if ( first.Compare("WebSite:") )			this->setWebSite(rest);
1482
	else if ( first.Compare("Email:") )				this->setEmail(rest);
14 cycrow 1483
	else if ( first.Compare("WebMirror1:") || first.Compare("Mirror1:") || first.Compare("WebMirror:") )
6 cycrow 1484
		this->AddWebMirror(rest);
14 cycrow 1485
	else if ( first.Compare("WebMirror2:") || first.Compare("Mirror2:") )
6 cycrow 1486
		this->AddWebMirror(rest);
48 cycrow 1487
	else if ( first.Compare("PluginType:") )		this->setPluginType(rest);
1488
	else if ( first.Compare("Desc:") )				this->setDescription(rest);
1489
	else if ( first.Compare("UninstallAfter:") )	this->addUninstallText(ParseLanguage(rest.token("|", 1)), false, rest.tokens("|", 2));
1490
	else if ( first.Compare("UninstallBefore:") )	this->addUninstallText(ParseLanguage(rest.token("|", 1)), true, rest.tokens("|", 2));
1491
	else if ( first.Compare("InstallAfter:") )		this->addInstallText(ParseLanguage(rest.token("|", 1)), false, rest.tokens("|", 2));
1492
	else if ( first.Compare("InstallBefore:") )		this->addInstallText(ParseLanguage(rest.token("|", 1)), true, rest.tokens("|", 2));
14 cycrow 1493
	else if ( first.Compare("ScriptName:") )
1494
		AddLanguageName(ParseLanguage(rest.token(":", 1)), rest.token(":", 2));
48 cycrow 1495
	else if ( first.Compare("GameChanging:") )		this->setGameChanging(rest);
1496
	else if ( first.Compare("EaseOfUse:") )			this->setEaseOfUse(rest);
1497
	else if ( first.Compare("Recommended:") )		this->setRecommended(rest);
14 cycrow 1498
	else if ( first.Compare("NeededLibrary:") )
1499
		this->AddNeededLibrary(rest.token("||", 1), rest.token("||", 2), rest.token("||", 3));
1500
	else if ( first.Compare("FakePatchBefore:") )
1501
		this->AddFakePatchOrder(false, rest.token("||", 1), rest.token("||", 2));
1502
	else if ( first.Compare("FakePatchAfter:") )
1503
		this->AddFakePatchOrder(true, rest.token("||", 1), rest.token("||", 2));
49 cycrow 1504
	else if ( first.Compare("ForumLink:") )			this->setForumLink(rest);
6 cycrow 1505
	else
1506
		return false;
1507
 
1508
	return true;
1509
}
1510
 
48 cycrow 1511
int CBaseFile::ParseLanguage(const Utils::String &lang) const
6 cycrow 1512
{
48 cycrow 1513
	int langID = lang;
1514
	if ( !langID ) {
1515
		if ( lang.Compare("english") )		return 44;
1516
		else if ( lang.Compare("default") )	return 0;
1517
		else if ( lang.Compare("german") )	return 49;
1518
		else if ( lang.Compare("russian") )	return 7;
1519
		else if ( lang.Compare("spanish") )	return 34;
1520
		else if ( lang.Compare("french") )	return 33;
6 cycrow 1521
	}
1522
 
1523
	return langID;
1524
}
1525
 
1526
/*
1527
	Func:   ReadValues
1528
	Input:  String - values in one long line
1529
	Desc:   splits the values data into each line to read the data
1530
*/
1531
void CBaseFile::ReadValues ( CyString values )
1532
{
1533
	int num = 0;
1534
	CyString *lines = values.SplitToken ( '\n', &num );
1535
 
1536
	for ( int i = 0; i < num; i++ )
14 cycrow 1537
		ParseValueLine ( lines[i].ToString() );
6 cycrow 1538
 
1539
	CLEANSPLIT(lines, num)
1540
}
1541
 
1542
/*
1543
	Func:   ParseFilesLine
1544
	Input:  String - single line from a file to set
1545
	Return: Boolean - returns true if value exists
1546
	Desc:   Reads the line and assigns the parameters for the file
1547
*/
127 cycrow 1548
bool CBaseFile::ParseFilesLine ( CyString sLine )
6 cycrow 1549
{
127 cycrow 1550
	Utils::String line = sLine.ToString();
1551
 
1552
	if ( !line.contains(":") )
6 cycrow 1553
		return false;
1554
 
127 cycrow 1555
	Utils::String command = line.token(":", 1);
6 cycrow 1556
 
127 cycrow 1557
	long size = line.token(":", 2).toInt();
1558
	long usize = line.token(":", 3).toInt ();
1559
	long compression = line.token(":", 4).toInt ();
6 cycrow 1560
 
1561
	if ( command == "Icon" )
1562
	{
127 cycrow 1563
		m_sIconExt = line.token (":", 5);
6 cycrow 1564
		m_pIconFile = new C_File ();
1565
		m_pIconFile->SetDataSize ( size - 4 );
1566
		m_pIconFile->SetDataCompression ( compression );
1567
		m_pIconFile->SetUncompressedDataSize ( usize );
1568
 
1569
		return true;
1570
	}
1571
 
127 cycrow 1572
	time_t time = line.token(":", 5).toLong();
1573
	bool compressToFile = (line.token(":", 6).toInt() == 1) ? true : false;
1574
	Utils::String name  = line.token(":", 7);
1575
	Utils::String dir = line.token(":", 8);
6 cycrow 1576
 
127 cycrow 1577
	if ( name.empty() )
6 cycrow 1578
		return true;
1579
 
1580
	bool shared = false;
127 cycrow 1581
	if ( command.left(1) == "$" )
6 cycrow 1582
	{
1583
		shared = true;
127 cycrow 1584
		command.erase(0, 1);
6 cycrow 1585
	}
1586
 
127 cycrow 1587
	FileType type = FILETYPE_UNKNOWN;
6 cycrow 1588
	if ( command == "Script" )
1589
		type = FILETYPE_SCRIPT;
1590
	else if ( command == "Text" )
1591
		type = FILETYPE_TEXT;
1592
	else if ( command == "Readme" )
1593
		type = FILETYPE_README;
1594
	else if ( command == "Map" )
1595
		type = FILETYPE_MAP;
1596
	else if ( command == "Mod" )
1597
		type = FILETYPE_MOD;
1598
	else if ( command == "Uninstall" )
1599
		type = FILETYPE_UNINSTALL;
1600
	else if ( command == "Sound" )
1601
		type = FILETYPE_SOUND;
1602
	else if ( command == "Mission" )
1603
		type = FILETYPE_MISSION;
1604
	else if ( command == "Extra" )
1605
		type = FILETYPE_EXTRA;
1606
	else if ( command == "Screen" )
1607
		type = FILETYPE_SCREEN;
1608
	else if ( command == "Backup" )
1609
		type = FILETYPE_BACKUP;
1610
	else if ( command == "Advert" )
1611
		type = FILETYPE_ADVERT;
1612
	else if ( command == "ShipScene" )
1613
		type = FILETYPE_SHIPSCENE;
1614
	else if ( command == "CockpitScene" )
1615
		type = FILETYPE_COCKPITSCENE;
1616
	else if ( command == "ShipOther" )
1617
		type = FILETYPE_SHIPOTHER;
1618
	else if ( command == "ShipModel" )
1619
		type = FILETYPE_SHIPMODEL;
1620
 
127 cycrow 1621
	if (type == FILETYPE_UNKNOWN)
6 cycrow 1622
		return false;
1623
 
127 cycrow 1624
	C_File *file = new C_File();
6 cycrow 1625
 
127 cycrow 1626
	if (dir.left(5).Compare("GAME_")) {
130 cycrow 1627
		unsigned int iGame = dir.token("_", 2).toInt();
1628
		if (!iGame)
1629
			file->setGame(0);
1630
		else
1631
			file->setGame(1 << 31 | 1 << iGame);
127 cycrow 1632
		dir = Utils::String::Null();
6 cycrow 1633
	} 
127 cycrow 1634
	else if ( line.countToken(":") >= 9 ) 
1635
	{
1636
		Utils::String game = line.token(":", 9);
1637
		if (game.contains("_"))
130 cycrow 1638
		{
1639
			unsigned int iGame = game.token("_", 2).toInt();
1640
			if (iGame)
1641
				file->setGame(1 << 31 | 1 << iGame);
1642
			else
1643
				file->setGame(0);
1644
		}
127 cycrow 1645
		else
1646
		{
1647
			int iGame = game.toInt();
1648
			if (iGame & (1 << 31))
1649
				file->setGame(iGame);
130 cycrow 1650
			else if (!iGame)
1651
				file->setGame(0);
127 cycrow 1652
			else
1653
				file->setGame(1 << 31 | 1 << iGame);
1654
		}
6 cycrow 1655
	}
1656
 
127 cycrow 1657
	if (dir.Compare("NULL")) {
1658
		dir = Utils::String::Null();
1659
	}
1660
 
1661
	file->setFileType(type);
6 cycrow 1662
	file->SetCreationTime ( time );
1663
	file->SetName ( name );
1664
	file->SetDir ( dir );
1665
	file->SetDataSize ( size - 4 );
1666
	file->SetDataCompression ( compression );
1667
	file->SetUncompressedDataSize ( usize );
1668
	file->SetShared ( shared );
1669
	file->SetCompressedToFile ( compressToFile );
1670
 
88 cycrow 1671
	_addFile(file, true);
6 cycrow 1672
 
1673
	return true;
1674
}
1675
 
1676
 
1677
/*
1678
	Func:   ParseFiles
1679
	Input:  String - values in one long line
1680
	Desc:   splits the files data into each line to read the data
1681
*/
1682
void CBaseFile::ReadFiles ( CyString values )
1683
{
1684
	int num = 0;
1685
	CyString *lines = values.SplitToken ( '\n', &num );
1686
 
1687
	for ( int i = 0; i < num; i++ )
1688
		ParseFilesLine ( lines[i] );
1689
 
1690
	CLEANSPLIT(lines, num)
1691
}
1692
 
1693
 
1694
 
1695
/*
1696
	Func:   ReadFile
1697
	Input:  filename - the name of the file to open and read
1698
			readdata - If falses, dont read the files to memory, just read the headers and values
1699
	Return: boolean - return ture if acceptable format
1700
	Desc:   Opens and reads the spk file and loads all data into class
1701
*/
130 cycrow 1702
bool CBaseFile::ReadFile(CyString filename, int readtype, CProgressInfo *progress)
6 cycrow 1703
{
130 cycrow 1704
	return readFile(filename.ToString(), readtype, progress);
1705
}
1706
bool CBaseFile::readFile(const Utils::String &filename, int readtype, CProgressInfo *progress)
1707
{
1708
	CFileIO File(filename);
58 cycrow 1709
	if ( !File.startRead() ) return false;
6 cycrow 1710
 
58 cycrow 1711
	bool ret = this->readFile(File, readtype, progress);
130 cycrow 1712
	if ( ret ) this->setFilename(filename);
6 cycrow 1713
 
58 cycrow 1714
	File.close();
6 cycrow 1715
	return ret;
1716
}
51 cycrow 1717
 
109 cycrow 1718
int CBaseFile::_read_Header(CFileIO &File, int iReadType, int iMaxProgress, CProgressInfo *pProgress)
6 cycrow 1719
{
51 cycrow 1720
	int doneLen = 0;
6 cycrow 1721
 
51 cycrow 1722
	// read data to memory
1723
	unsigned char *readData;
1724
	try {
1725
		readData = new unsigned char[m_SHeader.lValueCompressSize];
1726
	}
1727
	catch (std::exception &e) {
1728
		CLog::logf(CLog::Log_IO, 2, "CBaseFile::_read_Header() unable to malloc [header], %d (%s)", m_SHeader.lValueCompressSize, e.what());
1729
		return -1;
1730
	}
6 cycrow 1731
 
51 cycrow 1732
	unsigned char size[4];
109 cycrow 1733
	File.read(size, 4);
1734
	File.read(readData, m_SHeader.lValueCompressSize);
6 cycrow 1735
 
51 cycrow 1736
	unsigned long uncomprLen = (size[0] << 24) + (size[1] << 16) + (size[2] << 8) + size[3];
6 cycrow 1737
 
51 cycrow 1738
	// check for zlib compression
1739
	if ( m_SHeader.iValueCompression == SPKCOMPRESS_ZLIB ) {
1740
		// uncomress the data
1741
		try {
6 cycrow 1742
			unsigned char *uncompr = new unsigned char[uncomprLen];
1743
			int err = uncompress ( uncompr, &uncomprLen, readData, m_SHeader.lValueCompressSize );
1744
			// update the progress for each section
51 cycrow 1745
			if ( iReadType != SPKREAD_ALL && pProgress ) pProgress->UpdateProgress(2, iMaxProgress);
1746
			if ( err == Z_OK ) this->ReadValues ( CyString ((char *)uncompr) );
6 cycrow 1747
			doneLen = uncomprLen;
1748
			delete uncompr;
1749
		}
51 cycrow 1750
		catch (std::exception &e) {
1751
			CLog::logf(CLog::Log_IO, 2, "CBaseFile::_read_Header() unable to malloc [uncompr], %d (%s)", uncomprLen, e.what());
53 cycrow 1752
			delete []readData;
51 cycrow 1753
			return -1;
6 cycrow 1754
		}
51 cycrow 1755
	}
1756
	else if ( m_SHeader.iValueCompression == SPKCOMPRESS_7ZIP ) {
1757
		long len = uncomprLen;
1758
		unsigned char *compr = LZMADecode_C ( readData, m_SHeader.lValueCompressSize, (size_t*)&len, NULL );
1759
		// update the progress for each section
1760
		if ( iReadType != SPKREAD_ALL && pProgress ) pProgress->UpdateProgress(2, iMaxProgress);
6 cycrow 1761
 
51 cycrow 1762
		if ( compr ) ReadValues ( CyString ((char *)compr) );
6 cycrow 1763
	}
51 cycrow 1764
	// no compression
1765
	else
1766
		ReadValues ( CyString ((char *)readData) );
6 cycrow 1767
 
53 cycrow 1768
	delete []readData;
6 cycrow 1769
 
51 cycrow 1770
	return doneLen;
1771
}
6 cycrow 1772
 
109 cycrow 1773
int CBaseFile::_read_FileHeader(CFileIO &File, int iReadType, int iMaxProgress, int iDoneLen, CProgressInfo *pProgress)
51 cycrow 1774
{
1775
	unsigned char *readData;
1776
	try {
1777
		readData = new unsigned char[m_SHeader2.lSize];
1778
	}
1779
	catch (std::exception &e) {
1780
		CLog::logf(CLog::Log_IO, 2, "CBaseFile::_read_FileHeader() unable to malloc [header], %d (%s)", m_SHeader2.lSize, e.what());
1781
		return -1;
1782
	}
6 cycrow 1783
 
51 cycrow 1784
	unsigned char size[4];
109 cycrow 1785
	File.read(size, 4);
1786
	File.read(readData, m_SHeader2.lSize);
6 cycrow 1787
 
51 cycrow 1788
	unsigned long uncomprLen = (size[0] << 24) + (size[1] << 16) + (size[2] << 8) + size[3];
6 cycrow 1789
 
51 cycrow 1790
	// check for zlib compression
1791
	if ( m_SHeader.iValueCompression == SPKCOMPRESS_ZLIB ) {
1792
		if ( uncomprLen < (unsigned long)iDoneLen ) uncomprLen = iDoneLen;
6 cycrow 1793
 
51 cycrow 1794
		try {
6 cycrow 1795
			unsigned char *uncompr = new unsigned char[uncomprLen];
1796
			int err = uncompress ( uncompr, &uncomprLen, readData, m_SHeader2.lSize );
1797
			// update the progress for each section
51 cycrow 1798
			if ( iReadType != SPKREAD_ALL && pProgress ) pProgress->UpdateProgress(5, iMaxProgress);
1799
			if ( err == Z_OK ) ReadFiles ( CyString ((char *)uncompr) );
6 cycrow 1800
			delete uncompr;
1801
		}
51 cycrow 1802
		catch (std::exception &e) {
1803
			CLog::logf(CLog::Log_IO, 2, "CBaseFile::_read_FileHeader() unable to malloc [uncompr], %d (%s)", uncomprLen, e.what());
53 cycrow 1804
			delete []readData;
51 cycrow 1805
			return -1;
6 cycrow 1806
		}
1807
 
1808
	}
51 cycrow 1809
	else if ( m_SHeader.iValueCompression == SPKCOMPRESS_7ZIP )
1810
	{
1811
		long len = uncomprLen;
1812
		unsigned char *compr = LZMADecode_C ( readData, m_SHeader2.lSize, (size_t*)&len, NULL );
1813
		// update the progress for each section
1814
		if ( iReadType != SPKREAD_ALL && pProgress ) pProgress->UpdateProgress(5, iMaxProgress);
1815
		if ( compr ) ReadFiles ( CyString ((char *)compr) );
1816
	}
1817
	else
1818
		ReadFiles ( CyString ((char *)readData) );
6 cycrow 1819
 
53 cycrow 1820
	delete []readData;
51 cycrow 1821
	return true;
1822
}
1823
 
58 cycrow 1824
bool CBaseFile::readFile(CFileIO &File, int readtype, CProgressInfo *progress)
51 cycrow 1825
{
1826
	ClearError ();
1827
 
1828
	// first read the header
58 cycrow 1829
	if ( !ParseHeader(File.readEndOfLine()) ) return false;
51 cycrow 1830
	if ( readtype == SPKREAD_HEADER ) return true;
1831
 
1832
	// update the progress for each section
1833
	int maxProgress = (readtype == SPKREAD_VALUES) ? 3 : 6;
1834
	if ( readtype != SPKREAD_ALL && progress ) progress->UpdateProgress(1, maxProgress);
1835
 
1836
	long doneLen = 0;
1837
	// next read the data values for the spk files
109 cycrow 1838
	if ( m_SHeader.lValueCompressSize ) doneLen = this->_read_Header(File, readtype, maxProgress, progress);
51 cycrow 1839
 
1840
	// update the progress for each section
1841
	if ( readtype != SPKREAD_ALL && progress ) progress->UpdateProgress(3, maxProgress);
1842
	if ( readtype == SPKREAD_VALUES ) return true;
1843
 
1844
	// next should be the next header
58 cycrow 1845
	if ( !ParseFileHeader(File.readEndOfLine()) ) return false;
51 cycrow 1846
 
1847
	// clear the current file list
1848
	m_lFiles.clear(true);
88 cycrow 1849
	if ( _pTextDB ) {
1850
		delete _pTextDB;
1851
		_pTextDB = NULL;
1852
	}
51 cycrow 1853
 
1854
	// update the progress for each section
1855
	if ( readtype != SPKREAD_ALL && progress ) progress->UpdateProgress(4, maxProgress);
1856
 
109 cycrow 1857
	if ( m_SHeader2.lSize ) this->_read_FileHeader(File, readtype, maxProgress, doneLen, progress);
51 cycrow 1858
 
6 cycrow 1859
	// file mismatch
1860
	long numfiles = m_lFiles.size();
51 cycrow 1861
	if ( m_pIconFile ) ++numfiles;
1862
	if ( m_SHeader2.iNumFiles != numfiles ) {
134 cycrow 1863
		_iLastError = SPKERR_FILEMISMATCH;
6 cycrow 1864
		return false;
1865
	}
1866
 
1867
	// update the progress for each section
51 cycrow 1868
	if ( readtype != SPKREAD_ALL && progress )	progress->UpdateProgress(6, maxProgress);
6 cycrow 1869
 
51 cycrow 1870
	if ( readtype == SPKREAD_ALL ) {
6 cycrow 1871
		int fileCount = 2;
58 cycrow 1872
		if ( m_pIconFile ) m_pIconFile->readFromFile(File, m_pIconFile->GetDataSize());
6 cycrow 1873
 
51 cycrow 1874
		// ok finally we need to read all the file
1875
		for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
58 cycrow 1876
			node->Data()->readFromFile(File, node->Data()->GetDataSize());
51 cycrow 1877
			if ( progress )	progress->UpdateProgress(fileCount++, m_lFiles.size() + 2);
6 cycrow 1878
		}
1879
 
1880
		m_bFullyLoaded = true;
1881
	}
1882
 
1883
	return true;
1884
}
1885
 
1886
bool CBaseFile::IsMod()
1887
{
1888
	// check for any mod files that are not fake patchs
1889
	for ( CListNode<C_File> *fNode = m_lFiles.Front(); fNode; fNode = fNode->next() )
1890
	{
1891
		C_File *f = fNode->Data();
1892
		if ( f->GetFileType() != FILETYPE_MOD )
1893
			continue;
1894
 
1895
		if ( !f->IsFakePatch() )
1896
			return true;
1897
	}
1898
 
1899
	return false;
1900
}
1901
 
13 cycrow 1902
bool CBaseFile::IsFakePatch() const
6 cycrow 1903
{
1904
	// check for any mod files that are not fake patchs
1905
	for ( CListNode<C_File> *fNode = m_lFiles.Front(); fNode; fNode = fNode->next() )
1906
	{
1907
		C_File *f = fNode->Data();
1908
		if ( f->GetFileType() != FILETYPE_MOD )
1909
			continue;
1910
 
1911
		if ( f->IsFakePatch() )
1912
			return true;
1913
	}
1914
 
1915
	return false;
1916
}
1917
 
14 cycrow 1918
Utils::String CBaseFile::CreateValuesLine () const
6 cycrow 1919
{
14 cycrow 1920
	Utils::String values("Name: ");
50 cycrow 1921
	values += this->name() + "\n";
1922
	values += "Author: " + this->author() + "\n";
1923
	values += "Version: " + this->version() + "\n";
1924
	if ( !this->creationDate().empty() )values += "Date: "			+ this->creationDate()	+ "\n";
49 cycrow 1925
	if ( !this->webAddress().empty() )	values += "WebAddress: "	+ this->webAddress()	+ "\n";
1926
	if ( !this->webSite().empty() )		values += "WebSite: "		+ this->webSite()		+ "\n";
1927
	if ( !this->email().empty() )		values += "Email: "			+ this->email()			+ "\n";
1928
	if ( !this->forumLink().empty() )	values += "ForumLink: "		+ this->forumLink()		+ "\n";
1929
 
6 cycrow 1930
	for ( SStringList *str = m_lMirrors.Head(); str; str = str->next )
14 cycrow 1931
		values += Utils::String("WebMirror: ") + str->str.ToString() + "\n";
48 cycrow 1932
	if ( !this->description().empty() ) {
1933
		Utils::String desc = this->description();
14 cycrow 1934
		desc = desc.findReplace("<newline>", "<br>");
1935
		desc = desc.findReplace("\n", "<br>");
1936
		desc.remove('\r');
1937
		values += "Desc: " + desc + "\n";
6 cycrow 1938
	}
1939
 
1940
	for ( CListNode<SGameCompat> *gc = m_lGames.Front(); gc; gc = gc->next() ) {
46 cycrow 1941
		if ( !gc->Data()->sVersion.empty() )
1942
			values += Utils::String("GameCompatExact: ") + (long)gc->Data()->iGame + " " + gc->Data()->sVersion + "\n";
6 cycrow 1943
		else
14 cycrow 1944
			values += Utils::String("GameCompat: ") + (long)gc->Data()->iGame + " " + (long)gc->Data()->iVersion + "\n";
6 cycrow 1945
	}
1946
 
1947
	if ( m_bSigned )
1948
		values += "Signed\n";
1949
 
46 cycrow 1950
	for ( int j = 0; j < 2; j++ ) {
1951
		const CInstallText *text;
1952
		Utils::String textStart;
1953
		switch(j) {
1954
			case 0:	textStart = "Uninstall"; text = this->uninstallText(); break;
1955
			case 1: textStart = "Install"; text = this->installText(); break;
1956
		}
1957
		for ( unsigned int i = 0; i < text->count(); i++ ) {
1958
			int iLang = text->language(i);
1959
			if ( !text->getBefore(iLang).empty() ) values += textStart + "Before: " + (long)iLang + "|" + text->getBefore(iLang) + "\n";
1960
			if ( !text->getAfter(iLang).empty() ) values += textStart + "After: " + (long)iLang + "|" + text->getAfter(iLang) + "\n";
1961
		}
6 cycrow 1962
	}
1963
 
46 cycrow 1964
	values += Utils::String("GameChanging: ") + (long)gameChanging() + "\n";
1965
	values += Utils::String("EaseOfUse: ") + (long)easeOfUse() + "\n";
1966
	values += Utils::String("Recommended: ") + (long)recommended() + "\n";
6 cycrow 1967
 
14 cycrow 1968
	for ( CListNode<SNames> *nNode = m_lNames.Front(); nNode; nNode = nNode->next() )
46 cycrow 1969
		values += Utils::String("ScriptName: ") + (long)nNode->Data()->iLanguage + ":" + nNode->Data()->sName + "\n";
6 cycrow 1970
 
14 cycrow 1971
	for ( CListNode<SNeededLibrary> *libNode = m_lNeededLibrarys.Front(); libNode; libNode = libNode->next() ) {
6 cycrow 1972
		SNeededLibrary *l = libNode->Data();
14 cycrow 1973
		values += (CyString("NeededLibrary: ") + l->sName + "||" + l->sAuthor + "||" + l->sMinVersion + "\n").ToString();
6 cycrow 1974
	}
1975
 
1976
	for ( SStringList *fpbNode = m_lFakePatchBefore.Head(); fpbNode; fpbNode = fpbNode->next )
14 cycrow 1977
		values += (CyString("FakePatchBefore: ") + fpbNode->str + "||" + fpbNode->data + "\n").ToString();
6 cycrow 1978
	for ( SStringList *fpaNode = m_lFakePatchAfter.Head(); fpaNode; fpaNode = fpaNode->next )
14 cycrow 1979
		values += (CyString("FakePatchAfter: ") + fpaNode->str + "||" + fpaNode->data + "\n").ToString();
6 cycrow 1980
 
48 cycrow 1981
	values += Utils::String("PluginType: ") + (long)this->pluginType() + "\n";
6 cycrow 1982
 
1983
	return values;
1984
}
1985
 
1986
 
1987
/*
1988
	Func:   WriteFile
1989
	Input:  filename - The filename of the spk file to write to
1990
	Desc:   Writes the data to an spk file
1991
*/
1992
bool CBaseFile::WriteFile ( CyString filename, CProgressInfo *progress )
1993
{
52 cycrow 1994
	CFileIO File(filename);
1995
	if ( File.startWrite() ) return WriteData(File, progress);
1996
	return false;
6 cycrow 1997
}
1998
 
52 cycrow 1999
bool CBaseFile::WriteHeader(CFileIO &file, int valueheader, int valueComprLen)
6 cycrow 2000
{
52 cycrow 2001
	return file.write("BaseCycrow;%.2f;%d;%d\n", FILEVERSION, valueheader, valueComprLen);
6 cycrow 2002
}
2003
 
52 cycrow 2004
bool CBaseFile::WriteData(CFileIO &file, CProgressInfo *progress )
6 cycrow 2005
{
2006
	int valueheader = m_SHeader.iValueCompression, fileheader = m_SHeader.iValueCompression;
2007
	if ( valueheader == SPKCOMPRESS_7ZIP )
2008
		valueheader = SPKCOMPRESS_ZLIB;
2009
	if ( fileheader == SPKCOMPRESS_7ZIP )
2010
		fileheader = SPKCOMPRESS_ZLIB;
2011
 
2012
	// get the script values
2013
	this->UpdateSigned(true);
2014
	CyString values = this->CreateValuesLine();
2015
 
2016
	// compress the values
2017
	int valueUncomprLen = (int)values.Length();
2018
	unsigned long valueComprLen = 0;
2019
	unsigned char *valueCompr = NULL;
2020
	bool compressed = false;
2021
	if ( valueheader == SPKCOMPRESS_ZLIB )
2022
	{
2023
		valueComprLen = valueUncomprLen;
2024
		if ( valueComprLen < 100 )
2025
			valueComprLen = 200;
2026
		else if ( valueComprLen < 1000 )
2027
			valueComprLen *= 2;
2028
 
2029
		valueCompr = (unsigned char *)calloc((unsigned int)valueComprLen, 1);
2030
		int err = compress ( (unsigned char *)valueCompr, &valueComprLen, (const unsigned char *)values.c_str(), (unsigned long)values.Length(), 0 );
2031
		if ( err == Z_OK )
2032
			compressed = true;
2033
	}
2034
 
2035
	if ( !compressed )
2036
	{
2037
		valueComprLen = valueUncomprLen;
2038
		valueCompr = (unsigned char *)calloc((unsigned int)valueComprLen, 1);
2039
		memcpy ( valueCompr, values.c_str(), valueComprLen );
2040
		valueheader = SPKCOMPRESS_NONE;
2041
	}
2042
 
2043
	// write the main header to the file
52 cycrow 2044
	if ( !this->WriteHeader(file, valueheader, valueComprLen) )	return false;
6 cycrow 2045
 
2046
	// write the compressed data to file
52 cycrow 2047
	file.put(static_cast<unsigned char>(valueUncomprLen >> 24));
2048
	file.put(static_cast<unsigned char>(valueUncomprLen >> 16));
2049
	file.put(static_cast<unsigned char>(valueUncomprLen >> 8));
2050
	file.put(static_cast<unsigned char>(valueUncomprLen));
2051
	file.write(valueCompr, valueComprLen);
6 cycrow 2052
	free ( valueCompr );
2053
 
2054
	// now compress the files header
2055
	// create the files values
2056
	CyString files = CreateFilesLine ( true, progress );
2057
 
2058
	// compress the files values
2059
	long fileUncomprLen = (long)files.Length(), fileComprLen = fileUncomprLen;
2060
	unsigned char *fileCompr = NULL;
2061
 
2062
	compressed = false;
2063
	if ( fileUncomprLen )
2064
	{
2065
		if ( fileheader == SPKCOMPRESS_ZLIB )
2066
		{
2067
			if ( fileComprLen < 100 )
2068
				fileComprLen = 200;
2069
			else if ( fileComprLen < 1000 )
2070
				fileComprLen *= 2;
2071
			fileCompr = (unsigned char *)calloc((unsigned int)fileComprLen, 1);
2072
			int err = compress ( (unsigned char *)fileCompr, (unsigned long *)&fileComprLen, (const unsigned char *)files.c_str(), (unsigned long)files.Length(), 0 );
2073
			if ( err == Z_OK )
2074
				compressed = true;
2075
		}
2076
	}
2077
 
2078
	// if unable to compress, store it as plain text
2079
	if ( !compressed )
2080
	{
2081
		fileComprLen = fileUncomprLen;
2082
		fileCompr = (unsigned char *)calloc((unsigned int)fileComprLen, 1);
2083
		memcpy ( fileCompr, files.c_str(), fileComprLen );
2084
		fileheader = SPKCOMPRESS_NONE;
2085
	}
2086
 
2087
	// now write the file header
2088
	m_SHeader2.lSize = fileComprLen;
52 cycrow 2089
	file.write("FileHeader;%d;%ld;%ld;%d;%d\n", m_SHeader2.iNumFiles, m_SHeader2.lSize, m_SHeader2.lFullSize, fileheader, m_SHeader2.iDataCompression);
6 cycrow 2090
 
52 cycrow 2091
	file.put(static_cast<unsigned char>(fileUncomprLen >> 24));
2092
	file.put(static_cast<unsigned char>(fileUncomprLen >> 16));
2093
	file.put(static_cast<unsigned char>(fileUncomprLen >> 8));
2094
	file.put(static_cast<unsigned char>(fileUncomprLen));
2095
	file.write(fileCompr, fileComprLen);
6 cycrow 2096
	free ( fileCompr );
2097
 
2098
	if ( progress )
2099
	{
2100
		progress->UpdateStatus(STATUS_WRITE);
2101
		progress->SetDone(0);
2102
		long max = 0;
88 cycrow 2103
		for ( CListNode<C_File> *file = m_lFiles.Front(); file; file = file->next() )
2104
			max += file->Data()->GetDataSize();
6 cycrow 2105
		if ( m_pIconFile )
2106
			max += m_pIconFile->GetDataSize();
2107
		progress->SetMax(max);
2108
	}
2109
 
2110
	// now finally, write all the file data
52 cycrow 2111
	if ( m_pIconFile ) {
2112
		if ( progress )	progress->UpdateFile(m_pIconFile);
2113
		file.writeSize(m_pIconFile->GetUncompressedDataSize());
2114
		file.write(m_pIconFile->GetData(), m_pIconFile->GetDataSize());
2115
		if ( progress )	progress->IncDone(m_pIconFile->GetDataSize());
6 cycrow 2116
	}
2117
 
2118
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
2119
	{
52 cycrow 2120
		C_File *f = node->Data();
2121
		if ( progress )	progress->UpdateFile(f);
2122
		file.writeSize(f->GetUncompressedDataSize());
2123
		unsigned char *data = f->GetData();
2124
		size_t remaining = f->GetDataSize();
2125
		while ( remaining )	{
6 cycrow 2126
			size_t writeSize = WRITECHUNK;
52 cycrow 2127
			if ( writeSize > remaining ) writeSize = remaining;
6 cycrow 2128
 
52 cycrow 2129
			if ( file.write(data, writeSize) ) {
2130
				data += writeSize;
2131
				remaining -= writeSize;
2132
			}
6 cycrow 2133
 
52 cycrow 2134
			if ( progress ) progress->IncDone((int)writeSize);
6 cycrow 2135
		}
2136
	}
2137
 
50 cycrow 2138
	_changed();
6 cycrow 2139
 
2140
	return true;
2141
}
2142
 
2143
 
131 cycrow 2144
bool CBaseFile::ExtractFile(C_File *file, CyString dir, bool includedir, CProgressInfo *progress)
6 cycrow 2145
{
131 cycrow 2146
	return extractFile(file, dir.ToString(), includedir, progress);
2147
}
2148
bool CBaseFile::extractFile(C_File *file, const Utils::String &dir, bool includedir, CProgressInfo *progress)
2149
{
2150
	if (ReadFileToMemory(file))
6 cycrow 2151
	{
2152
		// now finally, uncompress the file
2153
		long len = 0;
131 cycrow 2154
		unsigned char *data = file->UncompressData(&len, progress);
2155
		if (!data)
6 cycrow 2156
		{
2157
			// attempt a file decompress
131 cycrow 2158
			if (file->GetCompressionType() == SPKCOMPRESS_7ZIP)
6 cycrow 2159
			{
131 cycrow 2160
				if (file->UncompressToFile(dir, this, includedir, progress))
6 cycrow 2161
					return true;
2162
			}
2163
			return false;
2164
		}
2165
 
131 cycrow 2166
		if (!file->writeToDir(dir, this, includedir, Utils::String::Null(), data, len))
6 cycrow 2167
			return false;
2168
 
2169
		return true;
2170
 
2171
	}
2172
	else
2173
		return false;
2174
}
131 cycrow 2175
bool CBaseFile::extractFile(C_File *file, const Utils::String &dir, unsigned int game, const Utils::CStringList &gameAddons, bool includedir, CProgressInfo *progress)
2176
{
2177
	if (ReadFileToMemory(file))
2178
	{
2179
		CDirIO Dir(dir);
2180
		Utils::String addonDir;
2181
		if (file->isFileInAddon())
2182
		{
2183
			int addonGame = file->getForSingleGame();
2184
			if (!addonGame) addonGame = game;
6 cycrow 2185
 
131 cycrow 2186
			if (addonGame > 0)
2187
				addonDir = gameAddons.findString(Utils::String::Number(addonGame));
2188
		}
2189
 
2190
		if (!addonDir.empty())
2191
			Dir.cd(addonDir);
2192
 
2193
		// create directory first
2194
		Dir.create(file->getDirectory(this));
2195
 
2196
		// now finally, uncompress the file
2197
		long len = 0;
2198
		unsigned char *data = file->UncompressData(&len, progress);
2199
		if (!data)
2200
		{
2201
			// attempt a file decompress
2202
			if (file->GetCompressionType() == SPKCOMPRESS_7ZIP)
2203
			{
2204
				if (file->UncompressToFile(Dir.dir(), this, includedir, progress))
2205
					return true;
2206
			}
2207
			return false;
2208
		}
2209
 
2210
		if (!file->writeToDir(Dir.dir(), this, includedir, Utils::String::Null(), data, len))
2211
			return false;
2212
 
2213
		return true;
2214
 
2215
	}
2216
	else
2217
		return false;
2218
}
2219
 
2220
bool CBaseFile::ExtractFile(int filenum, CyString dir, bool includedir, CProgressInfo *progress)
6 cycrow 2221
{
2222
	// invalid valus
131 cycrow 2223
	if (filenum < 0)
6 cycrow 2224
		return false;
2225
	// out of range
131 cycrow 2226
	if (filenum > m_lFiles.size())
6 cycrow 2227
		return false;
2228
 
2229
	// get the file pointer
131 cycrow 2230
	C_File *file = m_lFiles.Get(filenum);
2231
	return extractFile(file, dir.ToString(), includedir, progress);
6 cycrow 2232
}
2233
 
131 cycrow 2234
bool CBaseFile::extractFile(int filenum, const Utils::String &dir, unsigned int game, const Utils::CStringList &gameAddons, bool includedir, CProgressInfo *progress)
2235
{
2236
	// invalid valus
2237
	if (filenum < 0)
2238
		return false;
2239
	// out of range
2240
	if (filenum > m_lFiles.size())
2241
		return false;
2242
 
2243
	// get the file pointer
2244
	C_File *file = m_lFiles.Get(filenum);
2245
	return extractFile(file, dir, game, gameAddons, includedir, progress);
2246
}
2247
 
2248
bool CBaseFile::extractFile(int filenum, const Utils::String &dir, bool includedir, CProgressInfo *progress)
2249
{
2250
	// invalid valus
2251
	if (filenum < 0)
2252
		return false;
2253
	// out of range
2254
	if (filenum > m_lFiles.size())
2255
		return false;
2256
 
2257
	// get the file pointer
2258
	C_File *file = m_lFiles.Get(filenum);
2259
	return ExtractFile(file, dir, includedir, progress);
2260
}
2261
 
129 cycrow 2262
bool CBaseFile::extractAll(const Utils::String &dir, int game, const Utils::CStringList &gameAddons, bool includedir, CProgressInfo *progress)
6 cycrow 2263
{
2264
	// no file to read from
129 cycrow 2265
	if (this->filename().empty())
6 cycrow 2266
		return false;
2267
 
2268
	// now open the file
58 cycrow 2269
	CFileIO *File = _startRead();
129 cycrow 2270
	if (!File) return false;
6 cycrow 2271
 
2272
	// now were in the file section
2273
	// skip past each one
129 cycrow 2274
	if (m_pIconFile) File->seek(4 + m_pIconFile->GetDataSize());
6 cycrow 2275
 
134 cycrow 2276
	for (CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next()) 
2277
	{
6 cycrow 2278
		C_File *fit = node->Data();
2279
 
134 cycrow 2280
		if ((!fit->GetDataSize()) || (!fit->GetData())) 
2281
		{
2282
			if (!fit->readFromFile(*File, fit->GetDataSize())) 
2283
				return false;
6 cycrow 2284
		}
2285
		else
58 cycrow 2286
			File->seek(fit->GetDataSize());
6 cycrow 2287
 
129 cycrow 2288
		if (game && !fit->isForGame(game))
2289
			continue;
2290
 
134 cycrow 2291
		if (progress)	
2292
			progress->UpdateFile(fit);
2293
 
129 cycrow 2294
		CDirIO Dir(dir);
2295
		Utils::String addonDir;
2296
		if (fit->isFileInAddon())
2297
		{
2298
			int addonGame = fit->getForSingleGame();
2299
			if (!addonGame) addonGame = game;
2300
 
2301
			if (addonGame > 0)
2302
				addonDir = gameAddons.findString(Utils::String::Number(addonGame));
6 cycrow 2303
		}
2304
 
129 cycrow 2305
		if (!addonDir.empty())
2306
			Dir.cd(addonDir);
2307
 
6 cycrow 2308
		// create directory first
129 cycrow 2309
		Dir.create(fit->getDirectory(this));
6 cycrow 2310
 
2311
		long size = 0;
129 cycrow 2312
		unsigned char *data = fit->UncompressData(&size, progress);
2313
		if ((!data) && (fit->GetCompressionType() == SPKCOMPRESS_7ZIP)) {
2314
			if (!fit->UncompressToFile(Dir.dir(), this, includedir, progress)) return false;
6 cycrow 2315
		}
129 cycrow 2316
		else if ((!data) || (!fit->writeToDir(Dir.dir(), this, includedir, Utils::String::Null(), data, size))) return false;
6 cycrow 2317
	}
2318
 
58 cycrow 2319
	delete File;
6 cycrow 2320
	return true;
2321
}
2322
 
2323
 
2324
 
2325
bool CBaseFile::UpdateSigned (bool updateFiles)
2326
{
2327
	m_bSigned = true;
2328
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
2329
	{
2330
		C_File *file = node->Data();
2331
		if ( updateFiles )
2332
			file->UpdateSigned();
2333
		// extra, text, soundtrack, readmes and screen files do not require a modified game directly
2334
		if ( (file->GetFileType() == FILETYPE_EXTRA) || (file->GetFileType() == FILETYPE_TEXT) || (file->GetFileType() == FILETYPE_SOUND) || (file->GetFileType() == FILETYPE_SCREEN) || (file->GetFileType() == FILETYPE_README) )
2335
			continue;
2336
		// mods and maps always need modified game
2337
		else if ( (file->GetFileType() == FILETYPE_MOD) || (file->GetFileType() == FILETYPE_MAP) )
2338
		{
2339
			m_bSigned = false;
2340
			break;
2341
		}
2342
 
2343
		// else should be a script file, script or uninstall type
2344
		// all scripts must be signed, if any are not, then no signed status
2345
		if ( !file->IsSigned () )
2346
		{
2347
			m_bSigned = false;
2348
			break;
2349
		}
2350
	}
2351
 
2352
	return m_bSigned;
2353
}
2354
 
2355
 
46 cycrow 2356
bool CBaseFile::IsPackageNeeded(const Utils::String &scriptName, const Utils::String &author)
6 cycrow 2357
{
2358
	for ( CListNode<SNeededLibrary> *node = m_lNeededLibrarys.Front(); node; node = node->next() )
2359
	{
2360
		SNeededLibrary *l = node->Data();
2361
		if ( l->sName.Compare(scriptName) && l->sAuthor.Compare(author) )
2362
			return true;
2363
	}
2364
 
2365
	return false;
2366
}
2367
 
46 cycrow 2368
SNeededLibrary *CBaseFile::FindPackageNeeded(const Utils::String &scriptName, const Utils::String &author)
6 cycrow 2369
{
2370
	for ( CListNode<SNeededLibrary> *node = m_lNeededLibrarys.Front(); node; node = node->next() )
2371
	{
2372
		SNeededLibrary *l = node->Data();
2373
		if ( l->sName.Compare(scriptName) && l->sAuthor.Compare(author) )
2374
			return l;
2375
	}
2376
 
2377
	return NULL;
2378
}
2379
 
2380
void CBaseFile::RemoveFakePatchOrder(CyString scriptName, CyString author)
2381
{
2382
	RemoveFakePatchOrder(true, scriptName, author);
2383
	RemoveFakePatchOrder(false, scriptName, author);
2384
}
2385
void CBaseFile::RemoveFakePatchOrder(bool after, CyString scriptName, CyString author)
2386
{
2387
	CyStringList *list;
2388
	if ( after )
2389
		list = &m_lFakePatchAfter;
2390
	else
2391
		list = &m_lFakePatchBefore;
2392
 
2393
	for ( SStringList *str = list->Head(); str; str = str->next )
2394
	{
2395
		// already added
2396
		if ( str->str.Compare(scriptName) && str->data.Compare(author) )
2397
			str->remove = true;
2398
	}
2399
 
2400
	list->RemoveMarked();
2401
}
2402
 
2403
void CBaseFile::AddFakePatchOrder(bool after, CyString scriptName, CyString author)
2404
{
2405
	CyStringList *list;
2406
	if ( after )
2407
		list = &m_lFakePatchAfter;
2408
	else
2409
		list = &m_lFakePatchBefore;
2410
 
2411
	// check if the package already exists
2412
	for ( SStringList *str = list->Head(); str; str = str->next )
2413
	{
2414
		// already added
2415
		if ( str->str.Compare(scriptName) && str->data.Compare(author) )
2416
			return;
2417
	}
2418
 
2419
	// cant have it on both list
2420
	RemoveFakePatchOrder(!after, scriptName, author);
2421
 
2422
	list->PushBack(scriptName, author);
2423
}
46 cycrow 2424
void CBaseFile::AddNeededLibrary(const Utils::String &scriptName, const Utils::String &author, const Utils::String &minVersion)
6 cycrow 2425
{
2426
	SNeededLibrary *l = this->FindPackageNeeded(scriptName, author);
2427
	if ( !l )
2428
	{
2429
		l = new SNeededLibrary;
2430
		l->sName = scriptName;
2431
		l->sAuthor = author;
2432
		m_lNeededLibrarys.push_back(l);
2433
	}
2434
	l->sMinVersion = minVersion;
2435
}
2436
 
46 cycrow 2437
void CBaseFile::RemovePackageNeeded(const Utils::String &scriptName, const Utils::String &author)
6 cycrow 2438
{
2439
	SNeededLibrary *l = this->FindPackageNeeded(scriptName, author);
2440
	if ( l )
2441
	{
2442
		m_lNeededLibrarys.remove(l);
2443
		delete l;
2444
	}
2445
}
2446
 
2447
void CBaseFile::ClearNeededPackages()
2448
{
2449
	SNeededLibrary *ns = this->FindPackageNeeded("<package>", "<author>");
46 cycrow 2450
	Utils::String version;
2451
	if ( ns ) version = ns->sMinVersion;
2452
 
6 cycrow 2453
	for ( CListNode<SNeededLibrary> *node = m_lNeededLibrarys.Front(); node; node = node->next() )
2454
		node->DeleteData();
2455
	m_lNeededLibrarys.clear();
2456
 
46 cycrow 2457
	if ( !version.empty() )	this->AddNeededLibrary("<package>", "<author>", version);
6 cycrow 2458
}
2459
 
2460
 
127 cycrow 2461
bool CBaseFile::GeneratePackagerScript(bool wildcard, Utils::CStringList *list, int game, const Utils::CStringList &gameAddons, bool datafile)
6 cycrow 2462
{
126 cycrow 2463
	list->pushBack("#");
2464
	list->pushBack("# Packager Script");
2465
	list->pushBack("# -- Generated by SPK Libraries V" + Utils::String::FromFloat(GetLibraryVersion(), 2) + " --");
2466
	list->pushBack("#");
2467
	list->pushBack("");
6 cycrow 2468
	if ( !datafile )
2469
	{
126 cycrow 2470
		list->pushBack("# Variable for your game directory, where to get files from");
2471
		list->pushBack("# $PATH variable is used to get the current path");
2472
		list->pushBack("Variable: $GAMEDIR $PATH");
2473
		list->pushBack("");
6 cycrow 2474
	}
126 cycrow 2475
	list->pushBack("# The name of the script");
2476
	list->pushBack("Name: " + this->name());
2477
	list->pushBack("");
2478
	list->pushBack("# The author of the script, ie, you");
2479
	list->pushBack("Author: " + this->author());
2480
	list->pushBack("");
2481
	list->pushBack("# The creation data, when it was created");
6 cycrow 2482
	if ( datafile )
126 cycrow 2483
		list->pushBack("Date: " + this->creationDate());
50 cycrow 2484
	else {
126 cycrow 2485
		list->pushBack("# $DATE variable is used to get the current date");
2486
		list->pushBack("Date: $DATE");
6 cycrow 2487
	}
126 cycrow 2488
	list->pushBack("");
2489
	list->pushBack("# The version of script");
6 cycrow 2490
	if ( datafile )
126 cycrow 2491
		list->pushBack("Version: " + this->version());
6 cycrow 2492
	else
2493
	{
126 cycrow 2494
		list->pushBack("# $ASK variable is used to get an input when creating");
2495
		list->pushBack("Version: $ASK");
6 cycrow 2496
	}
126 cycrow 2497
	list->pushBack("");
6 cycrow 2498
 
2499
	if ( !m_lGames.empty() ) {
126 cycrow 2500
		list->pushBack("# The game version the script is for <game> <version> (can have multiple games)");
6 cycrow 2501
		for ( SGameCompat *g = m_lGames.First(); g; g = m_lGames.Next() ) {
126 cycrow 2502
			if (game > 0 && g->iGame != game)
2503
				continue;
2504
 
13 cycrow 2505
			Utils::String game = CBaseFile::ConvertGameToString(g->iGame);
6 cycrow 2506
 
46 cycrow 2507
			if ( !g->sVersion.empty() )
6 cycrow 2508
			{
2509
				game += " ";
46 cycrow 2510
				game += g->sVersion;
6 cycrow 2511
			}
2512
			else
2513
			{
2514
				game += " ";
2515
				game += (long)g->iVersion;
2516
			}
2517
 
126 cycrow 2518
			list->pushBack("Game: " + game);
6 cycrow 2519
		}
2520
 
126 cycrow 2521
		list->pushBack("");
6 cycrow 2522
	}
2523
 
48 cycrow 2524
	if ( !this->description().empty() ) {
126 cycrow 2525
		list->pushBack("# The description of the script, displays when installing");
2526
		list->pushBack("Description: " + this->description());
2527
		list->pushBack("");
6 cycrow 2528
	}
2529
 
49 cycrow 2530
	if ( !this->webSite().empty() ) {
126 cycrow 2531
		list->pushBack("# A link to the website for the script, ie for an online help page");
2532
		list->pushBack("WebSite: " + this->webSite());
2533
		list->pushBack("");
6 cycrow 2534
	}
2535
 
49 cycrow 2536
	if ( !this->forumLink().empty() ) {
126 cycrow 2537
		list->pushBack("# A direct link to the thread in the egosoft forum");
2538
		list->pushBack("ForumLink: " + this->forumLink());
2539
		list->pushBack("");
6 cycrow 2540
	}
2541
 
49 cycrow 2542
	if ( !this->webAddress().empty() ) {
126 cycrow 2543
		list->pushBack("# A link to the address for the update file");
2544
		list->pushBack("WebAddress: " + this->webAddress());
2545
		list->pushBack("");
6 cycrow 2546
	}
2547
 
49 cycrow 2548
	if ( !this->email().empty() ) {
126 cycrow 2549
		list->pushBack("# The email address of the author, to allow users to contract if needed");
2550
		list->pushBack("Email: " + this->email());
2551
		list->pushBack("");
6 cycrow 2552
	}
2553
 
2554
	if ( m_lMirrors.Count() )
2555
	{
126 cycrow 2556
		list->pushBack("# A link to the mirror address for the update file, can have many of these");
6 cycrow 2557
		for ( SStringList *node = m_lMirrors.Head(); node; node = node->next )
126 cycrow 2558
			list->pushBack(Utils::String("WebMirror: ") + node->str.ToString());
2559
		list->pushBack("");
6 cycrow 2560
	}
2561
 
2562
	if ( m_bAutoGenerateUpdateFile )
2563
	{
126 cycrow 2564
		list->pushBack("# Auto generate the package update file when created");
2565
		list->pushBack("GenerateUpdateFile");
6 cycrow 2566
	}
2567
 
2568
	if ( m_lNeededLibrarys.size() )
2569
	{
126 cycrow 2570
		list->pushBack("# Needed Library dependacies, require these to be installed");
6 cycrow 2571
		for ( CListNode<SNeededLibrary> *node = m_lNeededLibrarys.Front(); node; node = node->next() )
126 cycrow 2572
			list->pushBack("Depend: " + node->Data()->sName + "|" + node->Data()->sMinVersion + "|" + node->Data()->sAuthor);
6 cycrow 2573
 
126 cycrow 2574
		list->pushBack("");
6 cycrow 2575
	}
2576
 
46 cycrow 2577
	if ( !_noRatings() )
6 cycrow 2578
	{
126 cycrow 2579
		list->pushBack("# Ratings Values, 0 to 5, <ease> <changing> <recommended>");
2580
		list->pushBack(Utils::String("Ratings: ") + (long)easeOfUse() + " " + (long)gameChanging() + " " + (long)recommended());
2581
		list->pushBack("");
6 cycrow 2582
	}
2583
 
2584
	if ( m_lNames.size() )
2585
	{
126 cycrow 2586
		list->pushBack("# Package names, uses different names for different languages");
6 cycrow 2587
		for ( CListNode<SNames> *node = m_lNames.Front(); node; node = node->next() )
126 cycrow 2588
			list->pushBack(Utils::String("ScriptName: ") + (long)node->Data()->iLanguage + " " + node->Data()->sName);
2589
		list->pushBack("");
6 cycrow 2590
	}
2591
 
46 cycrow 2592
	for ( int j = 0; j < 2; j++ ) {
2593
		Utils::String installText = (j == 0) ? "Install" : "Uninstall";
2594
		const CInstallText *pText = (j == 0) ? this->installText() : this->uninstallText();
2595
		if ( pText->any() )
6 cycrow 2596
		{
126 cycrow 2597
			list->pushBack("# " + installText + " Texts, display text before and/or after " + installText + "ing to inform the use of special conditions");
46 cycrow 2598
			for ( unsigned int i = 0; i < pText->count(); i++ ) {
2599
				long iLang = pText->language(i);
126 cycrow 2600
				if ( !pText->getBefore(iLang).empty() )	list->pushBack(installText + "Before: " + iLang + " " + pText->getBefore(iLang));
2601
				if ( !pText->getAfter(iLang).empty()  )	list->pushBack(installText + "After: " + iLang + " " + pText->getAfter(iLang));
46 cycrow 2602
			}
126 cycrow 2603
			list->pushBack("");
6 cycrow 2604
		}
2605
	}
2606
 
126 cycrow 2607
	list->pushBack("# Plugin Type, the type the plugin is, mainly used to show users the type, types include: Normal, Stable, Experimental, Cheat, Mod");
48 cycrow 2608
	switch ( this->pluginType() )
6 cycrow 2609
	{
2610
		case PLUGIN_NORMAL:
126 cycrow 2611
			list->pushBack("PluginType: Normal");
6 cycrow 2612
			break;
2613
		case PLUGIN_STABLE:
126 cycrow 2614
			list->pushBack("PluginType: Stable");
6 cycrow 2615
			break;
2616
		case PLUGIN_EXPERIMENTAL:
126 cycrow 2617
			list->pushBack("PluginType: Experimental");
6 cycrow 2618
			break;
2619
		case PLUGIN_CHEAT:
126 cycrow 2620
			list->pushBack("PluginType: Cheat");
6 cycrow 2621
			break;
2622
		case PLUGIN_MOD:
126 cycrow 2623
			list->pushBack("PluginType: Mod");
6 cycrow 2624
			break;
2625
	}
126 cycrow 2626
	list->pushBack("");
6 cycrow 2627
 
2628
	return true;
2629
}
2630
 
127 cycrow 2631
bool CBaseFile::GeneratePackagerScriptFile(bool wildcard, Utils::CStringList *list, int game, const Utils::CStringList &gameAddons)
6 cycrow 2632
{
2633
	// now do files and wildcards
126 cycrow 2634
	Utils::CStringList files;
6 cycrow 2635
	for ( CListNode<C_File> *f = m_lFiles.Front(); f; f = f->next() )
2636
	{
127 cycrow 2637
		if (game && !(f->Data()->game() & 1 << game))
126 cycrow 2638
			continue;
6 cycrow 2639
 
126 cycrow 2640
		Utils::String name = "$GAMEDIR/";
2641
 
127 cycrow 2642
		// addon directory?
2643
		unsigned int checkGame = f->Data()->game() & ~(1 << 31);
2644
		unsigned int foundGame = 0;
2645
		for (int i = 0; i < 31; ++i)
2646
		{
2647
			if (checkGame == 1 << i)
2648
			{
2649
				foundGame = i;
2650
				break;
2651
			}
2652
		}
2653
 
2654
		if (foundGame)
2655
		{
2656
			Utils::String str = gameAddons.findString(Utils::String::Number(foundGame));
2657
			if(!str.empty())
2658
				name += str + "/";
2659
		}
2660
 
6 cycrow 2661
		bool done = false;
2662
		if ( wildcard )
2663
		{
131 cycrow 2664
			Utils::String base = f->Data()->baseName();
2665
			if ( f->Data()->fileType() == FILETYPE_SCRIPT )
6 cycrow 2666
			{
126 cycrow 2667
				if ( base.token(".", 1).Compare("plugin") || base.token(".", 1).Compare("lib") )
6 cycrow 2668
				{
131 cycrow 2669
					name += f->Data()->getDirectory(this) + "/" + base.tokens(".", 1, 2) + ".*";
6 cycrow 2670
					done = true;
2671
				}
126 cycrow 2672
				else if ( base.token(".", 1).Compare("al") && !base.token(".", 2).Compare("plugin") )
6 cycrow 2673
				{
131 cycrow 2674
					name += f->Data()->getDirectory(this) + "/" + base.tokens(".", 1, 2) + ".*";
6 cycrow 2675
					done = true;
2676
				}
2677
			}
131 cycrow 2678
			else if ( f->Data()->fileType() == FILETYPE_TEXT )
6 cycrow 2679
			{
126 cycrow 2680
				if ( base.contains("-L") )
6 cycrow 2681
				{
131 cycrow 2682
					name += f->Data()->getDirectory(this) + "/" + base.token("-L", 1) + "-L*";
6 cycrow 2683
					done = true;
2684
				}
2685
				else
2686
				{
131 cycrow 2687
					name += f->Data()->getDirectory(this) + "/*" + base.right(4) + ".*";
6 cycrow 2688
					done = true;
2689
				}
2690
			}
2691
		}
2692
 
2693
		if ( !done )
131 cycrow 2694
			name += f->Data()->getNameDirectory(this);
6 cycrow 2695
 
131 cycrow 2696
		if ( !f->Data()->dir().empty() )
6 cycrow 2697
		{
2698
			name += "|";
131 cycrow 2699
			name += f->Data()->dir();
6 cycrow 2700
		}
127 cycrow 2701
		Utils::String s = "GAME ";
2702
		if (!f->Data()->game() || f->Data()->game() == GAME_ALLNEW)
2703
			s += CBaseFile::ConvertGameToString(f->Data()->game());
2704
		else
2705
		{
2706
			bool first = true;
2707
			for (int i = 0; i < 31; ++i) 
2708
			{
2709
				if (f->Data()->game() & 1 << i)
2710
				{
2711
					if (first)
2712
						first = false;
2713
					else
2714
						s += "|";
2715
					s += CBaseFile::ConvertGameToString(i);
2716
				}
2717
			}
2718
		}
2719
 
2720
		s += " " + name;
126 cycrow 2721
		if(!files.contains(s))
2722
			files.pushBack(s, f->Data()->GetFileTypeString().ToString());
6 cycrow 2723
	}
2724
 
2725
 
126 cycrow 2726
	if ( !files.empty() )
6 cycrow 2727
	{
126 cycrow 2728
		list->pushBack("# Files List, all the files to add, can include wild cards");
2729
		for(auto itr = files.begin(); itr != files.end(); itr++)
2730
			list->pushBack((*itr)->data + ": " + (*itr)->str);
2731
		list->pushBack("");
6 cycrow 2732
	}
2733
 
2734
	return true;
2735
}
2736
 
50 cycrow 2737
Utils::String CBaseFile::GetAutosaveName()
6 cycrow 2738
{
50 cycrow 2739
	return this->name() + "-V" + this->version() + "-" + this->creationDate().findReplace("/", ".");
6 cycrow 2740
}
2741
 
2742
bool CBaseFile::CheckGameCompatability(int game)
2743
{
2744
	if ( m_lGames.empty() )
2745
		return true; // no game compatability added, assume its ok for all
2746
 
2747
	for ( CListNode<SGameCompat> *node = m_lGames.Front(); node; node = node->next() ) {
2748
		if ( node->Data()->iGame == 0 || node->Data()->iGame == game )
2749
			return true;
2750
	}
2751
	return false;
2752
}
2753
 
2754
bool CBaseFile::CheckGameVersionCompatability(int game, CyString sVersion, int iVersion)
2755
{
2756
	if ( m_lGames.empty() )
2757
		return true; // no game compatability added, assume its ok for all
2758
 
2759
	bool foundAll = false;
2760
	for ( CListNode<SGameCompat> *node = m_lGames.Front(); node; node = node->next() ) {
2761
		if ( node->Data()->iGame == 0 )
2762
			foundAll = true;
2763
		else if ( node->Data()->iGame == game ) { // now check the version
46 cycrow 2764
			if ( node->Data()->sVersion.empty() ) {
2765
				if ( CyString(node->Data()->sVersion).CompareVersion(sVersion) == COMPARE_OLDER )
6 cycrow 2766
					return false;
2767
				return true;
2768
			}
2769
			else {
2770
				if ( node->Data()->iVersion > iVersion )
2771
					return false;
2772
				return true;
2773
			}
2774
		}
2775
	}
2776
	return foundAll;
2777
}
2778
 
2779
bool CBaseFile::RemoveGameCompatability(int game)
2780
{
2781
	for ( CListNode<SGameCompat> *node = m_lGames.Front(); node; node = node->next() ) {
2782
		if ( node->Data()->iGame == game ) {
2783
			m_lGames.remove(node);
50 cycrow 2784
			_changed();
6 cycrow 2785
			return true;
2786
		}
2787
	}
2788
 
2789
	return false;
2790
}
2791
 
2792
SGameCompat *CBaseFile::GetGameCompatability(int game)
2793
{
2794
	for ( CListNode<SGameCompat> *node = m_lGames.Front(); node; node = node->next() ) {
2795
		if ( node->Data()->iGame == game ) {
2796
			return node->Data();
2797
		}
2798
	}
2799
 
2800
	return NULL;
2801
}
2802
 
46 cycrow 2803
void CBaseFile::AddGameCompatability(int game, const Utils::String &version)
6 cycrow 2804
{
2805
	// first check if we already have it on the list
2806
	SGameCompat *Found = this->GetGameCompatability(game);
2807
	if ( !Found ) {
2808
		Found = new SGameCompat;
2809
		m_lGames.push_back(Found);
2810
	}
2811
 
2812
	Found->iGame = game;
2813
	Found->iVersion = -1;
46 cycrow 2814
	Found->sVersion = "";
6 cycrow 2815
 
46 cycrow 2816
	if ( version.isin(".") || !version.isNumber() )
6 cycrow 2817
		Found->sVersion = version;
2818
	else
46 cycrow 2819
		Found->iVersion = version;
50 cycrow 2820
	_changed();
6 cycrow 2821
}
2822
 
131 cycrow 2823
Utils::String CBaseFile::_replaceFilename(const Utils::String &fname)
2824
{
2825
	Utils::String filename = fname;
2826
	Utils::String cdate = this->creationDate().findReplace("/", ".").remove(' ');
2827
	if (filename.isin("$AUTOSAVE"))
2828
	{
2829
		if (this->GetType() == TYPE_XSP)
2830
			filename = filename.findReplace("$AUTOSAVE", "$NAME-V$VERSION-$CDATE.xsp");
2831
		else
2832
			filename = filename.findReplace("$AUTOSAVE", "$NAME-V$VERSION-$CDATE.spk");
2833
	}
2834
	filename = filename.findReplace("$NAME", this->name().remove(' '));
2835
	filename = filename.findReplace("$AUTHOR", this->author().remove(' '));
2836
	filename = filename.findReplace("$DATE", cdate);
2837
	filename = filename.findReplace("$CDATE", cdate);
2838
	filename = filename.findReplace("$VERSION", this->version());
2839
 
2840
	return filename;
2841
}
134 cycrow 2842
bool CBaseFile::LoadPackageData(const Utils::String &sFirst, const Utils::String &sRest, const Utils::String &sMainGame, Utils::CStringList &otherGames, Utils::CStringList &gameAddons, CProgressInfo *progress)
6 cycrow 2843
{
134 cycrow 2844
	if (sFirst.Compare("Name"))					this->setName(sRest);
2845
	else if (sFirst.Compare("Author"))			this->setAuthor(sRest);
2846
	else if (sFirst.Compare("ScriptName"))
14 cycrow 2847
		AddLanguageName(ParseLanguage(sRest.token(" ", 1)), sRest.tokens(" ", 2));
134 cycrow 2848
	else if (sFirst.Compare("UninstallBefore"))	this->addUninstallText(ParseLanguage(sRest.token(" ", 1)), true, sRest.tokens(" ", 2));
2849
	else if (sFirst.Compare("UninstallAfter"))	this->addUninstallText(ParseLanguage(sRest.token(" ", 1)), false, sRest.tokens(" ", 2));
2850
	else if (sFirst.Compare("InstallBefore"))		this->addInstallText(ParseLanguage(sRest.token(" ", 1)), true, sRest.tokens(" ", 2));
2851
	else if (sFirst.Compare("InstallAfter"))		this->addInstallText(ParseLanguage(sRest.token(" ", 1)), false, sRest.tokens(" ", 2));
2852
	else if (sFirst.Compare("Date"))				this->setCreationDate(sRest);
2853
	else if (sFirst.Compare("Version"))			this->setVersion(sRest);
2854
	else if (sFirst.Compare("GameVersion"))
14 cycrow 2855
		this->AddGameCompatability(-1, sRest);
134 cycrow 2856
	else if (sFirst.Compare("PluginType")) {
2857
		if (sRest.isNumber())						this->setPluginType(sRest);
2858
		else if (sRest.Compare("Normal"))			this->setPluginType(PLUGIN_NORMAL);
2859
		else if (sRest.Compare("Stable"))			this->setPluginType(PLUGIN_STABLE);
2860
		else if (sRest.Compare("Experimental"))	this->setPluginType(PLUGIN_EXPERIMENTAL);
2861
		else if (sRest.Compare("Cheat"))			this->setPluginType(PLUGIN_CHEAT);
2862
		else if (sRest.Compare("Mod"))			this->setPluginType(PLUGIN_MOD);
6 cycrow 2863
	}
2864
	// new version
134 cycrow 2865
	else if (sFirst.Compare("GenerateUpdateFile"))
6 cycrow 2866
		m_bAutoGenerateUpdateFile = true;
134 cycrow 2867
	else if (sFirst.Compare("Game"))
6 cycrow 2868
	{
14 cycrow 2869
		Utils::String sGame = sRest.token(" ", 1);
2870
		this->AddGameCompatability(CBaseFile::GetGameFromString(sGame), sRest.token(" ", 2));
6 cycrow 2871
	}
134 cycrow 2872
	else if (sFirst.Compare("Description"))		this->setDescription(sRest);
2873
	else if (sFirst.Compare("AutoSave") || sFirst.Compare("AutoExport") || sFirst.Compare("AutoRarExport") || sFirst.Compare("AutoZipExport"))
6 cycrow 2874
	{
131 cycrow 2875
		Utils::String filename = _replaceFilename(sRest);
6 cycrow 2876
 
134 cycrow 2877
		if (sFirst.Compare("AutoZipExport") || sFirst.Compare("AutoExport"))
131 cycrow 2878
			this->setExportFilename(CFileIO(filename).changeFileExtension("zip"));
134 cycrow 2879
		else if (sFirst.Compare("AutoRarExport"))
131 cycrow 2880
			this->setExportFilename(CFileIO(filename).changeFileExtension("rar"));
6 cycrow 2881
		else
50 cycrow 2882
			this->setFilename(filename);
6 cycrow 2883
	}
134 cycrow 2884
	else if (sFirst.Compare("WebSite"))		this->setWebSite(sRest);
2885
	else if (sFirst.Compare("ForumLink") || sFirst.Compare("Forum")) this->setForumLink(sRest);
2886
	else if (sFirst.Compare("Email"))			this->setEmail(sRest);
2887
	else if (sFirst.Compare("WebAddress"))	this->setWebAddress(sRest);
2888
	else if (sFirst.Compare("WebMirror"))
14 cycrow 2889
		this->AddWebMirror(sRest);
134 cycrow 2890
	else if (sFirst.Compare("WebMirror1"))
14 cycrow 2891
		this->AddWebMirror(sRest);
134 cycrow 2892
	else if (sFirst.Compare("WebMirror2"))
14 cycrow 2893
		this->AddWebMirror(sRest);
134 cycrow 2894
	else if (sFirst.Compare("Ftp"))
14 cycrow 2895
		m_sFtpAddr = sRest;
134 cycrow 2896
	else if (sFirst.Compare("Ratings"))		_setRatings(sRest.token(" ", 1), sRest.token(" ", 2), sRest.token(" ", 3));
2897
	else if (sFirst.Compare("EaseOfUse"))		setEaseOfUse(sRest);
2898
	else if (sFirst.Compare("GameChanging"))	setGameChanging(sRest);
2899
	else if (sFirst.Compare("Recommended"))	setRecommended(sRest);
2900
	else if (sFirst.Compare("Depend"))
6 cycrow 2901
	{
46 cycrow 2902
		Utils::String version = sRest.token("|", 2);
2903
		Utils::String name = sRest.token("|", 1);
2904
		Utils::String author = sRest.tokens("|", 3);
6 cycrow 2905
 
2906
		this->AddNeededLibrary(name, author, version);
2907
	}
134 cycrow 2908
	else if (sFirst.Compare("DependPackage"))
6 cycrow 2909
	{
2910
		CPackages p;
134 cycrow 2911
		CBaseFile *spk = p.OpenPackage(sRest, 0, 0, SPKREAD_VALUES);
2912
		if (spk)
6 cycrow 2913
		{
50 cycrow 2914
			this->AddNeededLibrary(spk->name(), spk->author(), spk->version());
6 cycrow 2915
			delete spk;
2916
		}
2917
	}
130 cycrow 2918
	else if (sFirst.Compare("Icon"))
6 cycrow 2919
	{
14 cycrow 2920
		C_File *icon = new C_File(sRest.c_str());
134 cycrow 2921
		if (icon->ReadFromFile())
14 cycrow 2922
			this->SetIcon(icon, CFileIO(sRest).GetFileExtension());
6 cycrow 2923
	}
130 cycrow 2924
	else if (sFirst.Compare("CombineGameFiles"))
2925
		_bCombineFiles = sRest.Compare("true") || sRest.Compare("yes") || sRest.toInt();
134 cycrow 2926
	else if (sFirst.Compare("UpdateFile"))
2927
		this->createUpdateFile(sRest);
131 cycrow 2928
	else if (sFirst.Compare("ExportZip"))
2929
	{
2930
		Utils::String ext = "zip";
2931
		Utils::String game = sRest.word(1);
2932
		Utils::String file = _replaceFilename(CFileIO(sRest.words(2)).fullFilename());
2933
		if (game.contains("|"))
2934
		{
2935
			int max;
2936
			Utils::String *games = game.tokenise("|", &max);
2937
			if (games)
2938
			{
2939
				for (int i = 0; i < max; ++i)
2940
				{
2941
					unsigned int g = CBaseFile::GetGameFromString(games[i]);
2942
					Utils::String filename = CFileIO(file).dir() + "/" + CFileIO(file).baseName() + "_" + CBaseFile::ConvertGameToString(g) + "." + ext;
2943
					this->addAutoExport(g, filename);
2944
				}
2945
				CLEANSPLIT(games, max);
2946
			}
2947
		}
2948
		else
2949
		{
2950
			unsigned int g = CBaseFile::GetGameFromString(game);
2951
			Utils::String filename = CFileIO(file).dir() + "/" + CFileIO(file).baseName() + "_" + CBaseFile::ConvertGameToString(g) + "." + ext;
2952
			this->addAutoExport(g, filename);
2953
		}
2954
	}
2955
	else if (sFirst.Compare("Extract"))
2956
	{
2957
		Utils::String game = sRest.word(1);
2958
		Utils::String dir = CDirIO(sRest.words(2)).dir();
2959
		if (game.contains("|"))
2960
		{
2961
			int max;
2962
			Utils::String *games = game.tokenise("|", &max);
2963
			if (games)
2964
			{
2965
				for(int i = 0; i < max; ++i)
2966
					this->addAutoExtract(CBaseFile::GetGameFromString(games[i]), dir);
2967
				CLEANSPLIT(games, max);
2968
			}
2969
		}
2970
		else
2971
			this->addAutoExtract(CBaseFile::GetGameFromString(game), dir);
2972
	}
6 cycrow 2973
	else
2974
	{
14 cycrow 2975
		Utils::String checkType = sFirst;
6 cycrow 2976
		bool shared = false;
155 cycrow 2977
		if (checkType.left(6).Compare("Shared"))
6 cycrow 2978
		{
14 cycrow 2979
			checkType = sFirst.right(-6);
6 cycrow 2980
			shared = true;
2981
		}
155 cycrow 2982
		bool packed = false;
2983
		if (checkType.right(3).Compare("PCK"))
2984
		{
2985
			checkType = sFirst.left(-3);
2986
			packed = true;
2987
		}
6 cycrow 2988
 
2989
		// now check type name
127 cycrow 2990
		FileType filetype = GetFileTypeFromString(checkType);
2991
		if (filetype != FILETYPE_UNKNOWN)
155 cycrow 2992
			this->AddFileScript(filetype, shared, packed, sRest, sMainGame, otherGames, gameAddons, progress);
6 cycrow 2993
		else if ( !checkType.Compare("changelog") )
2994
			return false;
2995
	}
2996
 
2997
	return true;
2998
}
2999
 
155 cycrow 3000
void CBaseFile::AddFileScript(FileType filetype, bool shared, bool packed, const Utils::String &sRest, const Utils::String &sMainGame, Utils::CStringList &otherGames, Utils::CStringList &gameAddons, CProgressInfo *progress)
6 cycrow 3001
{
127 cycrow 3002
	Utils::String dir;
155 cycrow 3003
	Utils::String rest = sRest;
127 cycrow 3004
 
3005
	unsigned int mainGame = CBaseFile::GetGameFromString(sMainGame);
3006
	unsigned int game = 0;
3007
	if ( rest.token(" ", 1).left(4).Compare("GAME") ) {
3008
		Utils::String gameStr = rest.token(" ", 2);
3009
		if (gameStr.contains("|"))
3010
		{
3011
			int max = 0;
3012
			Utils::String *games = gameStr.tokenise("|", &max);
3013
			for (int i = 0; i < max; ++i)
3014
			{
3015
				unsigned int g = CBaseFile::GetGameFromString(games[i]);
3016
				if (g)
3017
					game |= 1 << g;
3018
			}
3019
			CLEANSPLIT(games, max);
3020
		}
3021
		else
131 cycrow 3022
		{
3023
			unsigned int g = CBaseFile::GetGameFromString(gameStr);
3024
			if (g)
3025
				game = 1 << g;
3026
		}
127 cycrow 3027
		rest = rest.tokens(" ", 3);
6 cycrow 3028
	}
127 cycrow 3029
	if (game)
3030
		game |= 1 << 31;
6 cycrow 3031
 
127 cycrow 3032
	if (rest.contains("|"))
3033
	{
3034
		dir = rest.tokens("|", 2);
3035
		rest = rest.token("|", 1);
6 cycrow 3036
	}
3037
 
127 cycrow 3038
	rest = rest.findReplace("\\", "/");
6 cycrow 3039
 
3040
	// wild cards
127 cycrow 3041
	if ( rest.containsAny("*?") )
6 cycrow 3042
	{
102 cycrow 3043
		CDirIO Dir(CFileIO(rest).dir());
6 cycrow 3044
		CyStringList *dirList = Dir.DirList();
3045
		if ( dirList )
3046
		{
3047
			for ( SStringList *strNode = dirList->Head(); strNode; strNode = strNode->next )
3048
			{
127 cycrow 3049
				Utils::String file = Dir.file(strNode->str.ToString());
3050
				if (file.match(rest))
6 cycrow 3051
				{
98 cycrow 3052
					int addGame = game;
3053
					// check if the file exists in the subdirectory too, if it does, add for each game
3054
					if ( game == GAME_ALL && !sMainGame.empty() && !otherGames.empty() ) {
3055
						CFileIO F(file);
3056
						for(Utils::String g = otherGames.firstString(); !g.empty(); g = otherGames.nextString()) {
102 cycrow 3057
							Utils::String checkDir = F.dir() + "/" + g;
121 cycrow 3058
							if ( CDirIO(checkDir).exists(F.filename()) ) {
98 cycrow 3059
								addGame = mainGame;
155 cycrow 3060
								C_File *newfile = this->appendFile(CDirIO(checkDir).file(F.filename()), filetype, CBaseFile::GetGameFromString(g), packed, dir);
134 cycrow 3061
								if (newfile && progress)
3062
									progress->UpdateFile(newfile);
98 cycrow 3063
								if ( newfile ) newfile->SetShared(shared);
3064
							}
3065
						}
3066
					}
3067
 
155 cycrow 3068
					C_File *newfile = this->appendFile(file, filetype, addGame, dir);
134 cycrow 3069
					if (newfile && progress)
3070
						progress->UpdateFile(newfile);
6 cycrow 3071
					if ( newfile )
3072
						newfile->SetShared(shared);
3073
				}
3074
			}
3075
			delete dirList;
3076
		}
3077
	}
3078
	else
3079
	{
127 cycrow 3080
		unsigned int addGame = game;
98 cycrow 3081
		// check if the file exists in the subdirectory too, if it does, add for each game
3082
		if ( game == GAME_ALL && !sMainGame.empty() && !otherGames.empty() ) {
3083
			CFileIO F(rest);
3084
			for(Utils::String g = otherGames.firstString(); !g.empty(); g = otherGames.nextString()) {
102 cycrow 3085
				Utils::String checkDir = F.dir() + "/" + g;
121 cycrow 3086
				if ( CDirIO(checkDir).exists(F.filename()) ) {
98 cycrow 3087
					addGame = mainGame;
155 cycrow 3088
					C_File *newfile = this->appendFile(CDirIO(checkDir).file(F.filename()), filetype, CBaseFile::GetGameFromString(g), packed, dir);
134 cycrow 3089
					if (newfile && progress)
3090
						progress->UpdateFile(newfile);
98 cycrow 3091
					if ( newfile ) newfile->SetShared(shared);
3092
				}
3093
			}
3094
		}
3095
 
127 cycrow 3096
		unsigned int checkGame = addGame & ~(1 << 31);
3097
		unsigned int foundGame = 0;
3098
		for (int i = 0; i < 31; ++i)
3099
		{
3100
			if (1 << i == checkGame)
3101
			{
3102
				foundGame = i;
3103
				break;
3104
			}
3105
		}
3106
 
3107
		C_File *file = NULL;
3108
		if (foundGame)
3109
		{
3110
			Utils::String addon = gameAddons.findString(Utils::String::Number(foundGame));
3111
			if (!addon.empty())
3112
			{
3113
				Utils::String dir = C_File::GetDirectory(filetype, rest, this);
3114
				Utils::String filename = rest;
130 cycrow 3115
				if (CCatFile::IsAddonDir(dir) && !filename.contains(addon))
3116
				{
127 cycrow 3117
					filename = filename.findReplace(dir + "/", addon + "/" + dir + "/");
155 cycrow 3118
					file = this->appendFile(filename, filetype, addGame, packed, dir);
130 cycrow 3119
				}
127 cycrow 3120
			}
3121
		}
3122
 
3123
		if(!file)
155 cycrow 3124
			file = this->appendFile(rest, filetype, addGame, packed, dir);
127 cycrow 3125
 
134 cycrow 3126
		if (file && progress)
3127
			progress->UpdateFile(file);
127 cycrow 3128
		if (file)
6 cycrow 3129
			file->SetShared(shared);
3130
	}
3131
}
3132
 
3133
 
3134
CyString CBaseFile::GetFullFileSizeString() { return SPK::GetSizeString ( this->GetFullFileSize() ); }
3135
 
52 cycrow 3136
// used for a multiple spk file
6 cycrow 3137
unsigned char *CBaseFile::CreateData(size_t *size, CProgressInfo *progress)
3138
{
52 cycrow 3139
	if ( this->WriteFile("temp.dat", progress) ) {
3140
		CFileIO File("temp.dat");
3141
		File.setAutoDelete(true);
3142
		return File.readAll(size);
6 cycrow 3143
	}
3144
	return NULL;
3145
}
3146
 
3147
 
3148
void CBaseFile::ConvertNormalMod(C_File *f, CyString to)
3149
{
3150
	C_File *match = this->FindMatchingMod(f);
3151
	if ( match )
3152
	{
3153
		// file link
3154
		if ( !match->GetData() )
3155
			match->ReadFromFile();
3156
		match->ChangeBaseName(to);
3157
	}
3158
 
3159
	// file link
3160
	if ( !f->GetData() )
3161
		f->ReadFromFile();
3162
 
3163
	f->ChangeBaseName(to);
3164
}
3165
 
3166
void CBaseFile::ConvertAutoText(C_File *f)
3167
{
3168
	CyString to;
3169
	if ( f->GetBaseName().IsIn("-L") )
3170
		to = CyString("0000-L") + f->GetBaseName().GetToken("-L", 2, 2);
3171
	else if ( f->GetBaseName().IsIn("-l") )
3172
		to = CyString("0000-L") + f->GetBaseName().GetToken("-l", 2, 2);
3173
	else
3174
		to = f->GetBaseName().Left(-4) + "0000";
3175
 
3176
	// file link
3177
	if ( !f->GetData() )
3178
		f->ReadFromFile();
3179
 
3180
	f->ChangeBaseName(to);
3181
 
3182
}
3183
 
3184
void CBaseFile::ConvertFakePatch(C_File *f)
3185
{
3186
	// find next available fake patch
3187
	int num = 0;
3188
 
3189
	bool found = true;
3190
	while ( found )
3191
	{
3192
		++num;
3193
		found = false;
3194
		CyString find = CyString::Number(num).PadNumber(2);
3195
		for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
3196
		{
3197
			if ( node->Data()->GetFileType() != FILETYPE_MOD )
3198
				continue;
3199
			if ( !node->Data()->IsFakePatch() )
3200
				continue;
3201
			if ( node->Data()->GetBaseName().Compare(find) )
3202
			{
3203
				found = true;
3204
				break;
3205
			}
3206
		}
3207
	}
3208
 
3209
	CyString to = CyString::Number(num).PadNumber(2);
3210
	C_File *match = this->FindMatchingMod(f);
3211
 
3212
	// file link
3213
	if ( !f->GetData() )
3214
		f->ReadFromFile();
3215
 
3216
	f->ChangeBaseName(to);
3217
	if ( match )
3218
	{
3219
		// file link
3220
		if ( !match->GetData() )
3221
			match->ReadFromFile();
3222
		match->ChangeBaseName(to);
3223
	}
3224
}
3225
 
3226
C_File *CBaseFile::FindMatchingMod(C_File *f)
3227
{
3228
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
3229
	{
3230
		if ( node->Data()->GetFileType() != FILETYPE_MOD )
3231
			continue;
3232
 
3233
		if ( f->GetFileExt().Compare(node->Data()->GetFileExt()) )
3234
			continue;
3235
 
3236
		if ( f->GetBaseName().Compare(node->Data()->GetBaseName()) )
3237
			return node->Data();
3238
	}
3239
 
3240
	return NULL;
3241
}
3242
 
3243
void CBaseFile::RenameFile(C_File *f, CyString baseName)
3244
{
3245
	if ( f->GetFileType() == FILETYPE_MOD )
3246
	{
3247
		C_File *match = this->FindMatchingMod(f);
3248
		if ( match )
3249
			match->ChangeBaseName(baseName);
3250
	}
3251
 
3252
	// need to edit the file
134 cycrow 3253
	if (f->GetFileType() == FILETYPE_SCRIPT || f->GetFileType() == FILETYPE_UNINSTALL)
3254
		f->RenameScript(baseName);
6 cycrow 3255
 
134 cycrow 3256
	f->ChangeBaseName(baseName);
6 cycrow 3257
}
3258
 
134 cycrow 3259
Utils::String CBaseFile::createUpdateFile(const Utils::String &dir) const
6 cycrow 3260
{
134 cycrow 3261
	Utils::String file = this->getNameValidFile() + "_" + this->author() + ".dat";
3262
	file.removeChar(' ');
6 cycrow 3263
 
134 cycrow 3264
	Utils::CStringList write;
3265
	write.pushBack("Package: " + this->name());
3266
	write.pushBack("Author: " + this->author());
3267
	write.pushBack("Version: " + this->version());
3268
	write.pushBack("File: " + CFileIO(this->filename()).filename());
6 cycrow 3269
 
3270
	CFileIO File(dir + "/" + file);
134 cycrow 3271
	if (File.writeFile(&write))
102 cycrow 3272
		return File.fullFilename();
134 cycrow 3273
	return Utils::String::Null();
6 cycrow 3274
}
3275
 
134 cycrow 3276
Utils::String CBaseFile::ErrorString(int error, const Utils::String &errorStr)
6 cycrow 3277
{
134 cycrow 3278
	if (error == SPKERR_NONE) return Utils::String::Null();
6 cycrow 3279
 
134 cycrow 3280
	Utils::String err;
6 cycrow 3281
 
126 cycrow 3282
	switch (error)
6 cycrow 3283
	{
126 cycrow 3284
	case SPKERR_MALLOC:
3285
		err = "Memory Failed";
3286
		break;
3287
	case SPKERR_FILEOPEN:
3288
		err = "Failed to open file";
3289
		break;
3290
	case SPKERR_FILEREAD:
3291
		err = "Failed to read file";
3292
		break;
3293
	case SPKERR_UNCOMPRESS:
3294
		err = "Failed to Uncompress";
3295
		break;
3296
	case SPKERR_WRITEFILE:
3297
		err = "Failed to write file";
3298
		break;
3299
	case SPKERR_CREATEDIRECTORY:
3300
		err = "Failed to create directory";
3301
		break;
3302
	case SPKERR_FILEMISMATCH:
3303
		err = "File count mismatch";
3304
		break;
6 cycrow 3305
	}
3306
 
134 cycrow 3307
	if (!err.empty())
6 cycrow 3308
	{
134 cycrow 3309
		if (!errorStr.empty())
6 cycrow 3310
		{
3311
			err += " (";
3312
			err += errorStr + ")";
3313
		}
3314
		return err;
3315
	}
3316
 
134 cycrow 3317
	return Utils::String::Number((long)error);
6 cycrow 3318
}
3319
 
126 cycrow 3320
bool CBaseFile::SaveToArchive(CyString filename, int game, const CGameExe *exes, CProgressInfo *progress)
6 cycrow 3321
{
131 cycrow 3322
	return saveToArchive(filename.ToString(), game, exes, progress);
3323
}
3324
bool CBaseFile::saveToArchive(const Utils::String &filename, int game, const CGameExe *exes, CProgressInfo *progress)
3325
{
3326
	CDirIO Dir(CFileIO(filename).dir());
3327
	if (!Dir.exists())
3328
		Dir.create();
3329
 
6 cycrow 3330
	TCHAR buf[5000];
3331
	wsprintf(buf, L"%hs", filename.c_str());
3332
 
3333
	HZIP hz = CreateZip(buf, 0);
126 cycrow 3334
	if (!hz) return false;
6 cycrow 3335
 
3336
	// read files and compress
3337
	ReadAllFilesToMemory();
126 cycrow 3338
	if (!UncompressAllFiles(progress))
6 cycrow 3339
	{
3340
		CloseZip(hz);
3341
		return false;
3342
	}
3343
 
126 cycrow 3344
	for (CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next())
6 cycrow 3345
	{
126 cycrow 3346
		if (game != -1) {
127 cycrow 3347
			if (game && !(node->Data()->game() & (1 << game)))
6 cycrow 3348
				continue;
127 cycrow 3349
			// extracting for all games, so ignore files that have a game set
3350
			if (!game && node->Data()->game() && node->Data()->game() != GAME_ALLNEW)
6 cycrow 3351
				continue;
3352
		}
131 cycrow 3353
		Utils::String fname = node->Data()->getNameDirectory(this);
126 cycrow 3354
 
3355
		// use the addon directory
3356
		if (node->Data()->isFileInAddon() && exes)
3357
		{
127 cycrow 3358
			unsigned int whatGame = game;
126 cycrow 3359
			if (game == -1)
127 cycrow 3360
			{
3361
				unsigned int checkGame = node->Data()->game() & ~GAME_ALLNEW;
3362
				whatGame = 0;
3363
				for (int i = 0; i < 31; ++i)
3364
				{
3365
					if (1 << i == checkGame)
3366
					{
3367
						whatGame = i;
3368
						break;
3369
					}
3370
				}
3371
			}
126 cycrow 3372
 
127 cycrow 3373
			if (whatGame > 0)
126 cycrow 3374
			{
127 cycrow 3375
				SGameExe *e = exes->GetGame(whatGame - 1);
3376
				if (e)
3377
				{
3378
					if (e->iFlags & EXEFLAG_ADDON)
3379
						fname = e->sAddon + "/" + fname;
3380
				}
126 cycrow 3381
			}
3382
		}
3383
 
6 cycrow 3384
		// create the directory
3385
		wsprintf(buf, L"%hs", fname.c_str());
127 cycrow 3386
		if (node->Data()->isExternalFile())
3387
		{
3388
			CFileIO file(node->Data()->filePointer());
3389
			size_t size = 0;
3390
			unsigned char *data = file.readAll(&size);
3391
			ZipAdd(hz, buf, data, size);
3392
			delete data;
3393
		}
3394
		else
3395
			ZipAdd(hz, buf, node->Data()->GetData(), node->Data()->GetDataSize());
6 cycrow 3396
	}
3397
 
109 cycrow 3398
	// if its a ship, then add any generated files
3399
	this->addGeneratedFiles(hz);
3400
 
6 cycrow 3401
	// add the data file
126 cycrow 3402
	Utils::CStringList list;
127 cycrow 3403
	Utils::CStringList addons;
3404
	if ( this->GeneratePackagerScript(false, &list, game, addons, true) )
6 cycrow 3405
	{
126 cycrow 3406
		if ( CFileIO("test.tmp").writeFile(&list) )
6 cycrow 3407
		{
3408
			ZipAdd(hz, L"pluginmanager.txt", L"test.tmp");
52 cycrow 3409
			CFileIO::Remove("test.tmp");
6 cycrow 3410
		}
3411
	}
3412
 
3413
	CloseZip(hz);
3414
 
3415
	return true;
3416
}
3417
 
13 cycrow 3418
int CBaseFile::GetGameFromString(const Utils::String &sGame)
6 cycrow 3419
{
3420
	int iGame = GAME_ALL;
3421
	if ( sGame.Compare("ALL") )
3422
		iGame = GAME_ALL;
3423
	else if ( sGame.Compare("X3") )
3424
		iGame = GAME_X3;
3425
	else if ( sGame.Compare("X2") )
3426
		iGame = GAME_X2;
3427
	else if ( sGame.Compare("X3TC") )
3428
		iGame = GAME_X3TC;
126 cycrow 3429
	else if (sGame.Compare("X3AP"))
6 cycrow 3430
		iGame = GAME_X3AP;
126 cycrow 3431
	else if (sGame.Compare("X3FL"))
3432
		iGame = GAME_X3FL;
13 cycrow 3433
	else if ( sGame.isNumber() )
3434
		iGame = sGame;
6 cycrow 3435
 
3436
	return iGame;
3437
}
3438
 
13 cycrow 3439
Utils::String CBaseFile::ConvertGameToString(int iGame)
6 cycrow 3440
{
13 cycrow 3441
	Utils::String game = "ALL";
6 cycrow 3442
 
3443
	switch(iGame) {
3444
		case GAME_ALL:
127 cycrow 3445
		case GAME_ALLNEW:
6 cycrow 3446
			game = "ALL";
3447
			break;
3448
		case GAME_X2:
3449
			game = "X2";
3450
			break;
3451
		case GAME_X3:
3452
			game = "X3";
3453
			break;
3454
		case GAME_X3TC:
3455
			game = "X3TC";
3456
			break;
3457
		case GAME_X3AP:
3458
			game = "X3AP";
3459
			break;
126 cycrow 3460
		case GAME_X3FL:
3461
			game = "X3FL";
3462
			break;
6 cycrow 3463
		default:
3464
			game = (long)iGame;
3465
	}
3466
 
3467
	return game;
3468
}
3469
 
3470
bool CBaseFile::IsGameInPackage(int game)
3471
{
3472
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
3473
		if ( node->Data()->GetGame() == game )
3474
			return true;
3475
	}
3476
 
3477
	return false;
3478
}
3479
 
3480
bool CBaseFile::IsAnyGameInPackage()
3481
{
3482
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
3483
		if ( node->Data()->GetGame() )
3484
			return true;
3485
	}
3486
 
3487
	return false;
3488
}
3489
 
88 cycrow 3490
Utils::String builtInWares()
3491
{
3492
	Utils::String str;
3493
	str += "28;0;0;0;0;59;5753;0;35714;1;1;0;35714;-100000;0;0;SS_WARE_SW_NEW1;\n";
3494
	str += "28;0;0;0;0;60;5763;0;33232;1;1;0;33232;0;1043;0;SS_WARE_SW_NEW2;\n";
3495
	str += "28;0;0;0;0;61;5773;0;21428;1;1;0;21428;0;1043;0;SS_WARE_SW_NEW3;\n";
3496
	str += "28;0;0;0;0;62;5783;0;56;1;1;0;56;-100000;0;0;SS_WARE_SW_NEW4;\n";
3497
	str += "28;0;0;0;0;63;5793;0;88;1;1;0;88;-100000;0;0;SS_WARE_SW_NEW5;\n";
3498
	str += "28;0;0;0;0;64;5803;0;283;1;1;0;283;-100000;0;0;SS_WARE_SW_NEW6;\n";
3499
	str += "28;0;0;0;0;65;5813;0;383;1;1;0;383;-100000;0;0;SS_WARE_SW_NEW7;\n";
3500
	str += "28;0;0;0;0;66;5823;0;1389;1;1;0;1389;-100000;1043;0;SS_WARE_SW_NEW8;\n";
3501
	str += "28;0;0;0;0;67;5833;0;3396;1;1;0;3396;-100000;0;0;SS_WARE_SW_NEW9;\n";
3502
	str += "28;0;0;0;0;68;5843;0;4215;1;1;0;4215;-100000;0;0;SS_WARE_SW_NEW10;\n";
3503
	str += "28;0;0;0;0;69;5853;0;5635;1;1;0;5635;-100000;0;0;SS_WARE_SW_NEW11;\n";
3504
	str += "28;0;0;0;0;70;5863;0;65735;1;1;0;65735;-100000;0;0;SS_WARE_SW_NEW12;\n";
3505
	str += "28;0;0;0;0;71;5873;0;17857;1;1;0;17857;333;1043;0;SS_WARE_SW_NEW13;\n";
3506
	str += "28;0;0;0;0;72;5883;0;21428;1;1;0;21428;0;1043;0;SS_WARE_SW_NEW14;\n";
3507
	str += "28;0;0;0;0;73;5893;0;324515;1;1;0;324515;-100000;0;0;SS_WARE_SW_NEW15;\n";
3508
	str += "28;0;0;0;0;74;5903;0;638508;1;1;0;638508;-100000;0;0;SS_WARE_SW_NEW16;\n";
3509
	str += "28;0;0;0;0;75;5913;0;225755;1;1;0;225755;-100000;0;0;SS_WARE_SW_NEW17;\n";
3510
	str += "28;0;0;0;0;76;5923;0;1931535;1;1;0;1931535;1000;0;0;SS_WARE_SW_NEW18;\n";
3511
	str += "28;0;0;0;0;77;5933;0;2209150;1;1;0;2209150;-100000;0;0;SS_WARE_SW_NEW19;\n";
3512
	str += "28;0;0;0;0;78;5943;0;6727565;1;1;0;6727565;-100000;0;0;SS_WARE_SW_NEW20;\n";
3513
	str += "28;0;0;0;0;85;9999;0;105;1;5;0;105;0;1043;0;SS_WARE_SW_X3TC_1;\n";
3514
	str += "28;0;0;0;0;86;15053;0;105;1;5;0;105;0;1043;0;SS_WARE_SW_X3TC_2;\n";
3515
	str += "28;0;0;0;0;87;15063;0;105;1;5;0;105;0;1043;0;SS_WARE_SW_X3TC_3;\n";
3516
	str += "28;0;0;0;0;88;15073;0;105;1;5;0;105;0;1043;0;SS_WARE_SW_X3TC_4;\n";
3517
	str += "28;0;0;0;0;89;15083;0;105;1;5;0;105;0;1043;0;SS_WARE_SW_X3TC_5;\n";
3518
	str += "28;0;0;0;0;90;15093;0;105;1;5;0;105;0;1043;0;SS_WARE_SW_X3TC_6;\n";
3519
 
3520
	return str;
3521
}
3522
 
3523
void CBaseFile::_addWaresToList(int iLang, CLinkList<SWareEntry> &list, const Utils::String &wares, enum WareTypes eType)
3524
{
3525
	int totalWares = 0;
3526
	Utils::String *w = wares.tokenise("\n", &totalWares);
3527
 
3528
	for(int i = 0; i < totalWares; i++) {
3529
		int textId = w[i].token(";", 7).toLong();
3530
		int useLang = iLang;
3531
		if ( !_pTextDB->exists(useLang, 17, textId) )
3532
			useLang = 44;
3533
		if ( !_pTextDB->exists(useLang, 17, textId) )
3534
			useLang = 49;
3535
		if ( _pTextDB->exists(useLang, 17, textId) ) {	
3536
			SWareEntry *ware = new SWareEntry;
3537
			ware->name = _pTextDB->get(useLang, 17, textId);
3538
			ware->description = _pTextDB->get(useLang, 17, textId + 1);
3539
			ware->id = w[i].token(";", -2);
3540
			ware->relval = w[i].token(";", 9).toLong();
3541
			ware->notority = w[i].token(";", 14).toLong();
3542
			ware->type = eType;
3543
			ware->position = i;
89 cycrow 3544
			ware->package = this;
88 cycrow 3545
			list.push_back(ware);
3546
		}
3547
	}
3548
 
3549
	CLEANSPLIT(w, totalWares);
3550
}
3551
 
3552
bool CBaseFile::readWares(int iLang, CLinkList<SWareEntry> &list, const Utils::String &empWares)
3553
{
3554
	_pTextDB->setLanguage(iLang);
3555
 
3556
	// now go through all emp wares and get the ones we have text for
3557
	_addWaresToList(iLang, list, empWares, Ware_EMP);
3558
	_addWaresToList(iLang, list, builtInWares(), Ware_BuiltIn);
3559
 
89 cycrow 3560
	return true;
3561
}
88 cycrow 3562
 
89 cycrow 3563
bool CBaseFile::_readCommands(int iLang, int iStartID, CLinkList<SCommandSlot> &list)
3564
{
3565
	_pTextDB->setLanguage(iLang);
3566
 
3567
	for(int i = 2; i <= 13; i++) {
3568
		for(int j = 0; j < 64; j++) {
3569
			int id = (i * 100) + j;
3570
			if ( _pTextDB->exists(iLang, iStartID + 2, id) ) {
3571
				SCommandSlot *slot = new SCommandSlot;
3572
				list.push_back(slot);
3573
 
3574
				slot->id = _pTextDB->get(iLang, iStartID, id);
3575
				slot->name = _pTextDB->get(iLang, iStartID + 2, id);
3576
				slot->shortName = _pTextDB->get(iLang, iStartID + 3, id);
3577
				slot->info = _pTextDB->get(iLang, iStartID + 14, id);
3578
				slot->slot = id;
3579
				slot->package = this;
3580
 			}
3581
		}
3582
	}
3583
 
3584
	for(int i = 1400; i <= 2000; i++) {
3585
		if ( _pTextDB->exists(iLang, iStartID + 2, i) ) {
3586
			SCommandSlot *slot = new SCommandSlot;
3587
			list.push_back(slot);
3588
 
3589
			slot->id = _pTextDB->get(iLang, iStartID, i);
3590
			slot->name = _pTextDB->get(iLang, iStartID + 2, i);
3591
			slot->shortName = _pTextDB->get(iLang, iStartID + 3, i);
3592
			slot->info = _pTextDB->get(iLang, iStartID + 14, i);
3593
			slot->slot = i;
3594
			slot->package = this;
3595
		}
3596
	}
3597
 
3598
	for(int i = 6000; i <= 9999; i++) {
3599
		if ( _pTextDB->exists(iLang, iStartID + 2, i) ) {
3600
			SCommandSlot *slot = new SCommandSlot;
3601
			list.push_back(slot);
3602
 
3603
			slot->id = _pTextDB->get(iLang, iStartID, i);
3604
			slot->name = _pTextDB->get(iLang, iStartID + 2, i);
3605
			slot->shortName = _pTextDB->get(iLang, iStartID + 3, i);
3606
			slot->info = _pTextDB->get(iLang, iStartID + 14, i);
3607
			slot->slot = i;
3608
			slot->package = this;
3609
		}
3610
	}
3611
 
88 cycrow 3612
	return true;
3613
}
3614
 
89 cycrow 3615
bool CBaseFile::readWingCommands(int iLang, CLinkList<SCommandSlot> &list)
3616
{
3617
	return _readCommands(iLang, 2028, list);
3618
}
3619
 
3620
bool CBaseFile::readCommands(int iLang, CLinkList<SCommandSlot> &list)
3621
{
3622
	return _readCommands(iLang, 2008, list);
3623
}
3624
 
6 cycrow 3625
int CBaseFile::FindFirstGameInPackage()
3626
{
3627
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
3628
		if ( node->Data()->GetGame() )
3629
			return node->Data()->GetGame();
3630
	}
3631
 
3632
	return 0;
3633
}
3634
bool CBaseFile::IsMultipleGamesInPackage()
3635
{
3636
	int game = 0;
3637
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
3638
		if ( node->Data()->GetGame() ) {
3639
			if ( game != node->Data()->GetGame() )
3640
				return true;
3641
			game = node->Data()->GetGame();
3642
		}
3643
	}
3644
 
3645
	return false;
3646
}