summaryrefslogtreecommitdiffstats
path: root/src/schedule.cpp
blob: 56c03d2f87af5d89d090ad71cce812093168aa99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/*
 * Copyright (C) 2004 Robert Hogan <robert at roberthogan dot net>
 */

#include "schedule.h"
#include "klamav.h"
#include "datepicker.h"


#include "ktview.h"


#include <tqlabel.h>
#include <kurlrequester.h>
#include <tqlayout.h>
#include <tqlistview.h>
//#include <qlistviewitem.h>
#include <kglobalsettings.h>
#include <kdialog.h>
#include <dcopclient.h>
#include <kstdguiitem.h>
#include <sys/stat.h>


Schedule::Schedule( TQWidget* parent, TQStringList filepattern, const char* name, bool modal, WFlags fl )
    : TQDialog( parent, name, modal, fl )
{

	setCaption( i18n( "Schedule Scan" ) );

 	cthost = new CTHost();
// 	const CTHost& cth(*cthost);

	// for each user
//  	CTCronIterator i = const_cast<CTHost&>(cth).cron.begin();
// 	CTCron* ctcron((CTCron*)*i);	


	_filepattern = filepattern;
	//bool isRTL = TQApplication::reverseLayout();
	TQVBoxLayout *vbox = new TQVBoxLayout(this, KDialog::marginHint(),
			KDialog::spacingHint(), "vbox");
 
	TQGroupBox *group = new TQGroupBox("Schedule Scan of Selected Folders", this);
	vbox->addWidget(group);
	


	TQGridLayout *layout = new TQGridLayout( group, 6, 6, KDialog::spacingHint(),
			KDialog::spacingHint(), "layout");
	layout->addRowSpacing(0, group->fontMetrics().height());
	layout->setColStretch(0, 1);
	layout->setColStretch(1, 1);

	

	check_combo = new TQComboBox(false, group);
   check_combo->insertItem( i18n("When I log in to KDE"));
   check_combo->insertItem( i18n("Every day at "));
   check_combo->insertItem( i18n("Every day at the current time"));
   check_combo->insertItem( i18n("Every week from now on at the current time"));
   check_combo->insertItem( i18n("Every week from now on at"));
   check_combo->insertItem( i18n("Every week from a specific date at"));
   check_combo->insertItem( i18n("Every month from now on at the current time"));
   check_combo->insertItem( i18n("Every month from now on at"));
   check_combo->insertItem( i18n("Every month from a specific date at"));
   check_combo->insertItem( i18n("Once only on a specific date at the current time"));
   check_combo->insertItem( i18n("Once only on a specific date at"));

 	layout->addWidget(check_combo,1,0);
 	connect( check_combo, SIGNAL(activated(int)),this,
 		SLOT(slotQueryDatePicker(int)) );


	hour = new HMSTimeWidget( group );
	hour->setWrapping(true);
	hour->setMaxValue(23);
	hour->setValidator(new KStrictIntValidator(0, 23, hour));
	layout->addWidget(hour, 1, 1);
	
	TQLabel *dots1 = new TQLabel(":", group);
	dots1->setMinimumWidth( 7 );
	dots1->setAlignment( TQLabel::AlignCenter );
	layout->addWidget(dots1, 1, 2);
	
	minute = new HMSTimeWidget( group );
	minute->setWrapping(true);
	minute->setMinValue(0);
	minute->setMaxValue(59);
	minute->setValidator(new KStrictIntValidator(0, 59, minute));
	layout->addWidget(minute, 1, 3);




	TQPushButton* add = new TQPushButton ("Add", group);
	layout->addWidget(add,1,5);
	//add->setFixedSize(add->sizeHint());

 	connect( add, SIGNAL(clicked()),
 		SLOT(slotScheduleScan()) );

	TQPushButton* del = new TQPushButton ("Delete", group);
	layout->addWidget(del,1,6);
	//del->setFixedSize(del->sizeHint());

 	connect( del, SIGNAL(clicked()),
 		SLOT(slotDelete()) );


	//schedulebox = new TQListView(group);
	schedulebox = new KTView(group);
	TQFontMetrics rb_fm(schedulebox->fontMetrics());
	schedulebox->setMinimumSize(rb_fm.width("0")*55,
				rb_fm.lineSpacing()*15);
/*	//kdDebug() << ((schedulebox->width())/2) << endl;
	schedulebox->addColumn( "Paths to Scan",(group->width()));
        schedulebox->addColumn( "When to Scan",(group->width()));
	schedulebox->setResizeMode(TQListView::AllColumns);
	schedulebox->setSelectionMode( TQListView::Extended );
	schedulebox->setAllColumnsShowFocus(true);*/
	
	layout->addMultiCellWidget(schedulebox, 2, 4,0,6);

	TQHBoxLayout *h5 = new TQHBoxLayout( vbox, KDialog::spacingHint() );
	h5->addStretch( 1 );

	// OK
	KPushButton *pbOk = new KPushButton(KStdGuiItem::ok(), this, "pbOk");
	pbOk->setDefault(true);
	h5->addWidget( pbOk);
	
	// Cancel
// 	KPushButton *pbCancel = new KPushButton(KStdGuiItem::cancel(), this, "pbCancel");
// 	h5->addWidget( pbCancel);

	connect(pbOk, SIGNAL(clicked()), SLOT(slotOK()));
/*	connect(pbCancel, SIGNAL(clicked()), SLOT(slotCancel()));*/
	
	schedulebox->hideCommand();
}

Schedule::~Schedule()
{
	delete cthost;
}


void Schedule::slotQueryDatePicker(int)
{

	if (check_combo->currentText().contains(i18n("specific date")) ){
		DatePicker *_calendar;	
		_calendar = new DatePicker(this, TQDateTime::currentDateTime().date());
		int x = this->width() - (this->width()/2);
		int y = this->height() - (this->height()/2);
		_calendar->move(TQPoint(x,y));
		_calendar->show();
		_calendar->setFocus();
		connect( _calendar, SIGNAL(signalSelectedDate(TQDate)),this,
			SLOT(slotAddDateToCombo(TQDate)) );

	}
}

void Schedule::slotAddDateToCombo(TQDate newdate)
{

	//check_combo->insertItem
	_date = newdate;
	//kdDebug() << newdate.toString() << endl;
	TQString newstring = check_combo->currentText().replace("a specific date",newdate.toString());
	check_combo->insertItem(newstring);
	check_combo->setCurrentItem(check_combo->count()-1);

	DCOPClient* client = KApplication::dcopClient();
	client->attach();
	client->registerAs(kapp->name());


	
}


void Schedule::slotScheduleScan()
{


/* 	cthost = new CTHost();*/
/* 	const CTHost& cth(*cthost);
// 
// 	// for each user
 	CTCronIterator i = const_cast<CTHost&>(cth).cron.begin();
 	CTCron* ctcron((CTCron*)*i);	*/
 
	//delete cttask;
	TQString command = check_combo->currentText();

	
	
 	cttask = new CTTask ("", "", TRUE);

	cttask->user = "";

	if (command.contains(i18n("When I log in to KDE")) ){
		TQString startupcommand = createStartupScript();
		cttask->comment = (const char *)i18n("KlamAV Scheduled Scan at KDE Login of %1").arg(_filepattern.join(" ")).local8Bit();
		cttask->command = (const char *)TQString("%1").arg(startupcommand).local8Bit();
		cttask->enabled = FALSE;

	}else{
	
		cttask->comment = (const char *)i18n("KlamAV Scheduled Scan of %1").arg(_filepattern.join(" ")).local8Bit();
		cttask->command = (const char *)TQString("%1 '%2'").arg(createScanScript()).arg(_filepattern.join("' '")).local8Bit();
		cttask->enabled = TRUE;
	}
	cttask->silent = FALSE;
	

	int curhour = (TQTime::currentTime()).hour();
	unsigned int curmin = (TQTime::currentTime()).minute();
	
	int shour = TQString(hour->text()).toInt();
	unsigned int smin = TQString(minute->text()).toInt();

	int sdatedayofweek = _date.dayOfWeek();
	int todaydayofweek = TQDate::currentDate().dayOfWeek();


	if (command.contains(i18n("at the current time")) ){
		cttask->hour.set(curhour, TRUE);
		cttask->minute.set(curmin, TRUE);
	}else{
		cttask->hour.set(shour, TRUE);
		cttask->minute.set(smin, TRUE);
	}

	if (command.contains(i18n("Every week")) ){
		if (command.contains(i18n("from now on") ))
			cttask->dayOfWeek.set(todaydayofweek, TRUE);
		else
			cttask->dayOfWeek.set(sdatedayofweek, TRUE);
		for (int dm = 1; dm <= 31; dm++)
		{
			cttask->dayOfMonth.set(dm, true);
		}
		for (int mo = 1; mo <= 12; mo++)
		{
			cttask->month.set(mo, true);
		}

	}else if (command.contains(i18n("Every month")) ){
		if (command.contains(i18n("from now on") ))
			cttask->dayOfMonth.set(TQDate::currentDate().day(), TRUE);
		else
			cttask->dayOfMonth.set(_date.day(), TRUE);
		for (int dw = 1; dw <= 7; dw++)
		{
		cttask->dayOfWeek.set(dw, true);
		}
		for (int mo = 1; mo <= 12; mo++)
		{
			cttask->month.set(mo, true);
		}
	}else if (command.contains(i18n("Every day")) ){
		for (int dw = 1; dw <= 7; dw++)
		{
		cttask->dayOfWeek.set(dw, true);
		}

		for (int dm = 1; dm <= 31; dm++)
		{
			cttask->dayOfMonth.set(dm, true);
		}
		for (int mo = 1; mo <= 12; mo++)
		{
			cttask->month.set(mo, true);
		}
	}else if (command.contains(i18n("Once only")) ){
		cttask->month.set(_date.month(), TRUE);
		cttask->dayOfMonth.set(_date.day(), TRUE);
	}else{
		cttask->month.set(1, TRUE);
		cttask->dayOfMonth.set(1, TRUE);
		cttask->dayOfWeek.set(1, true);
		cttask->hour.set(0, TRUE);
		cttask->minute.set(0, TRUE);

	}




	TQString description = TQString::fromLocal8Bit(cttask->describe().c_str()); 
	CTCron* ctcron(schedulebox->getCTCron());
	if (cttask->dirty())
		ctcron->task.push_back(cttask);
		//new KTListTask(this, ctcron, cttask); // TQt will clean up
	else
		delete cttask;


	schedulebox->refresh();
	cthost->apply();
	
	//TQListViewItem* tm = new TQListViewItem( schedulebox, _filepattern, description);

/*	if (cthost->isError())
	{
		KMessageBox::error(this, cthost->errorMessage());
	}
	//kdDebug() << "finished crontab" << endl;


	delete cthost;*/
}


void Schedule::slotDelete()
{

	//kdDebug() << schedulebox->currentItem()->text(1) << endl;
	TQFile file(schedulebox->currentItem()->text(1).section(" ",0,0).stripWhiteSpace());
	file.remove();
	schedulebox->remove();
	cthost->apply();
}

void Schedule::slotOK()
{
	cthost->apply();
	close();
}

void Schedule::slotCancel()
{
	close();
}

TQString Schedule::createScanScript()
{

	TQString path = getenv("HOME");
	path += "/.klamav";
	TQDir klamavdir(path);
	if (!klamavdir.exists() && !klamavdir.mkdir(path))
		return TQString("Error");

	TQTime now = TQTime::currentTime();
	TQDate today = TQDate::currentDate();
	TQString timestring = TQString("%1%2")
		.arg(today.toString("ddMMyy"))
		.arg(now.toString("hhmmss"));

	TQFile file( TQString("%1/ScanWithKlamav_%2.sh").arg(path).arg(timestring ));

	if ( file.open( IO_WriteOnly ) ) {
		TQTextStream ts( &file );
	
		TQString kdedir = getenv("KDEDIR");
	
	
		ts << "#!/bin/bash" << "\n";
		ts << "HOSTNAME=`hostname`" << "\n";
		ts << "export HOSTNAME" << "\n";
		ts << TQString("PATH=%1").arg(TQString(getenv("PATH"))) << "\n";
		ts << "export PATH" << "\n";
		ts << "DCOPSERVER=`cat /home/${USER}/.DCOPserver_${HOSTNAME}_:0 | grep local`" << "\n";
		ts << "export DCOPSERVER" << "\n";
		ts << "DISPLAY=:0" << "\n";
		ts << "export DISPLAY" << "\n";
		ts << "# Execution starts here" << "\n";
		ts << "if [ \"$1\" = \"\" ]; then" << "\n";
		ts << "        exit 1" << "\n";
		ts << "fi" << "\n";
		ts << "until [ -z \"$1\" ]  # Until all parameters used up..." << "\n";
		ts << "do" << "\n";
		ts << "  if [ \"${URL}\" = \"\" ]; then" << "\n";
		ts << "        URL=$1" << "\n";
		ts << "        SCANTHIS=$1" << "\n";
		ts << "  else" << "\n";
		ts << "        URL=${URL}'*'$1" << "\n";
		ts << "        SCANTHIS=${SCANTHIS}' '$1" << "\n";
		ts << "  fi" << "\n";
		ts << "  shift" << "\n";
		ts << "done" << "\n";
        ts << "DCOPEXEC=`which dcop`" << "\n";
        ts << "KLAMAVEXEC=`which klamav`" << "\n";
        ts << "if ${DCOPEXEC} `${DCOPEXEC}|grep klamav|head -1` DCOPKlamscan scanURLs \"${URL}\"; then" << "\n";
		ts << "        exit 0" << "\n";
		ts << "else" << "\n";
		ts << "         ${KLAMAVEXEC} --scanthis ${SCANTHIS}" << "\n";
		ts << "fi" << "\n";
	
		file.close();
		chmod((const char *)file.name(), S_IWUSR | S_IRUSR | S_IEXEC );
		return file.name();
	}else
		return TQString("Error");

}

TQString Schedule::createStartupScript()
{

	TQString path = KGlobalSettings::autostartPath();
	TQDir startupdir(path);
	if (!startupdir.exists())
		return TQString("Error");

	TQTime now = TQTime::currentTime();
	TQDate today = TQDate::currentDate();
	TQString timestring = TQString("%1%2")
		.arg(today.toString("ddMMyy"))
		.arg(now.toString("hhmmss"));

	TQFile file( TQString("%1klamav_%2.desktop").arg(path).arg(timestring ));

	if ( file.open( IO_WriteOnly ) ) {
		TQTextStream ts( &file );
	
		ts << "[Desktop Entry]" << "\n";
		ts << "Encoding=UTF-8" << "\n";
		ts << "Name=Klamav" << "\n";
		ts << TQString("Exec=klamav %i %m -caption \"%c\" --scanthis '%1'").arg(_filepattern.join("' '")) << "\n";
		ts << "Icon=klamav" << "\n";
		ts << "Type=Application" << "\n";
		ts << "DocPath=klamav/klamav.html" << "\n";
		ts << "Comment=An Anti-Virus Manager" << "\n";
		ts << "Comment[cs]=Aplikace typu KPart" << "\n";
		ts << "Comment[da]=Et KDE KPart program" << "\n";
		ts << "Comment[de]=Ein KDE-Programm" << "\n";
		ts << "Comment[el]=Μια εφαρμογή KDE KPart" << "\n";
		ts << "Comment[eo]=KDEa Parto-aplikaĵo" << "\n";
		ts << "Comment[es]=Una aplicación KPart para KDE" << "\n";
		ts << "Comment[et]=KDE KPart rakendus" << "\n";
		ts << "Comment[fi]=KDE KPart sovellus" << "\n";
		ts << "Comment[fr]=Une Application KPart pour KDE" << "\n";
		ts << "Comment[he]=KDE לש KPart םושיי" << "\n";
		ts << "Comment[hu]=Egy KDE KPart tesztalkalmazás" << "\n";
		ts << "Comment[is]=KDE KPart forrit" << "\n";
		ts << "Comment[it]=Un'applicazione \"part\" di KDE" << "\n";
		ts << "Comment[ja]=KDE KPart アプリケーション" << "\n";
		ts << "Comment[ko]=KDE용 KPart 응용 프로그램" << "\n";
		ts << "Comment[lv]=KDE KPart Aplikācija" << "\n";
		ts << "Comment[nl]=een KDE KPart-applicatie" << "\n";
		ts << "Comment[no_NY]=Eit KDE KPart-program" << "\n";
		ts << "Comment[pt]=Uma aplicação KPart" << "\n";
		ts << "Comment[pt_BR]=Uma aplicação KPart do KDE" << "\n";
		ts << "Comment[ro]=O aplicaţie KPart pentru KDE" << "\n";
		ts << "Comment[ru]=Приложение KPart KDE" << "\n";
		ts << "Comment[sk]=KDE KPart aplikácia" << "\n";
		ts << "Comment[sl]=Program za KDE KPart" << "\n";
		ts << "Comment[sr]=KDE KPart aplikacija" << "\n";
		ts << "Comment[sv]=Ett KDE KPart-program" << "\n";
		ts << "Comment[tr]=KDE Kpart Uygulaması" << "\n";
		ts << "Comment[uk]=Програма KPart для KDE" << "\n";
		ts << "Comment[zh_CN.GB2312]=KDE KPart程序" << "\n";
		ts << "Terminal=0" << "\n";
	
		file.close();
		chmod((const char *)file.name(), S_IWUSR | S_IRUSR | S_IEXEC );
		return file.name();
	}else
		return TQString("Error");

}



HMSTimeWidget::HMSTimeWidget(TQWidget *parent, const char *name) :
	KIntSpinBox(parent, name)
{
}


TQString HMSTimeWidget::mapValueToText(int value)
{
  TQString s = TQString::number(value);
  if( value < 10 ) {
    s = "0" + s;
  }
  return s;
}

TQValidator::State KStrictIntValidator::validate( TQString & input, int & d ) const
{
  if( input.isEmpty() )
    return Valid;

  State st = TQIntValidator::validate( input, d );

  if( st == Intermediate )
    return Invalid;

  return st;
}

const CTHost& Schedule::getCTHost() const
{
  return *cthost;
}


#include "schedule.moc"