Subversion Repositories spk

Rev

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