summaryrefslogtreecommitdiffstats
path: root/kfilereplace/kfilereplacelib.cpp
blob: e57a3a84e8c288158cc4d0ce1ef0f496be9d9410 (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
/***************************************************************************
                           kfilereplacelib.cpp  -  File library
                                      -------------------
    begin                : lun mai  3 20:19:52 CEST 1999

    copyright            : (C) 1999 by Fran�ois Dupoux
                           (C) 2003 Andras Mantia <[email protected]>
                           (C) 2004 Emiliano Gulmini <[email protected]>
    email                : [email protected]

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

//QT
#include <qstringlist.h>
#include <qwidget.h>
#include <qlistview.h>
#include <qfileinfo.h>

//KDE
#include <kdebug.h>
#include <kmessagebox.h>
#include <klistview.h>
#include <kiconloader.h>

//needed for malloc/free
#include <stdlib.h>

// local
#include "kfilereplacelib.h"

const double kilo = 1024.0;
const double mega = 1048576.0;//1024^2
const double giga = 1073741824.0;//1024^3
const double tera = 1099511627776.0;//1024^4

/**
 Format a path, from a path and a filename, or another sub-path (avoid double '/' risks)
 Parameters::.....* basePath: fist path (can be "/" if root, or "/usr/bin/" or "/usr/bin" for example)
 .................* fileName: second path (can be "/doc/html/", or "doc/html/" or "doc/html/index.html" for example)
 Return values:...* Full valid path (without double "/")
*/
QString KFileReplaceLib::formatFullPath(const QString& basePath, const QString &fileName)
{
  QString fullPath = basePath;
  QString fname = fileName;

  if (fname.startsWith("/")) // skip beginning '/'
    fname = fname.remove(0,1);

  if (fullPath.endsWith("/"))
    fullPath.append(fname);
  else
    fullPath.append("/"+fname);

  return fullPath;
}

/**
 Add an extension to a filename, or a filepath
 Parameters::.....* fileName: filename or filepath (it can have already the extension)
 .................* extension: extension to add without "." (ex: "html", "kfr")
 Return values:...* Filename / Filepath with the extension
*/
QString KFileReplaceLib::addExtension(const QString& fileName, const QString& extension)
{
  QString fullExtension = ".";
  QString fname = fileName;

  fullExtension.append(extension);

  // filename cannot contain ".ext" ==> Add it
  if(fname.length() <= fullExtension.length())
   fname.append(fullExtension);
  else // filename can contain ".ext"
  {
   if (fname.right(fullExtension.length()) != fullExtension)
    fname.append(fullExtension);
  }

  return fname;
}

QString KFileReplaceLib::formatFileSize(double size)
{
  QString stringSize;

  if(size < kilo)
    {
      const int asInt = (int) size;
      stringSize = i18n("1 byte", "%n bytes", asInt);
    }
  else
  if(size >= kilo && size < mega)
    {
      double d = size / kilo;
      stringSize = i18n("%1 KB").arg(QString::number(d,'f',2));
    }
  else
  if(size >= mega && size < giga)
    {
      double d = size / mega;
      stringSize = i18n("%1 MB").arg(QString::number(d,'f',2));
    }
  else
  if(size >= giga)
    {
      double d = size / giga;
      stringSize =  i18n("%1 GB").arg(QString::number(d,'f',2));
    }
  return stringSize;
}

void KFileReplaceLib::convertOldToNewKFRFormat(const QString& fileName, KListView* stringView)
{
 //this method convert old format in new XML-based format
 typedef struct
 {
   char pgm[13]; // Must be "KFileReplace" : like MZ for EXE files
   int stringNumber; // Number of strings in file
   char reserved[64]; // Reserved for future use
 } KFRHeader;

 KFRHeader head;

 FILE* f = fopen(fileName.ascii(),"rb");
 int err = fread(&head, sizeof(KFRHeader), 1, f);
 QString pgm(head.pgm);

 if(!f || (err != 1) || (pgm != "KFileReplace"))
 {
   KMessageBox::error(0, i18n("<qt>Cannot open the file <b>%1</b> and load the string list. This file seems not to be a valid old kfr file or it is broken.</qt>").arg(fileName));
   return ;
 }

  stringView->clear();

  int oldTextSize,
      newTextSize,
      errors = 0,
      stringSize;
  QStringList l;

  int i ;
  for (i=0; i < head.stringNumber; i++)
    {
      errors += (fread(&oldTextSize, sizeof(int), 1, f)) != 1;
      errors += (fread(&newTextSize, sizeof(int), 1, f)) != 1;
      if(errors > 0)
        KMessageBox::error(0, i18n("Cannot read data."));
      else
        {
          stringSize = ((oldTextSize > newTextSize) ? oldTextSize : newTextSize) + 2;
          char* oldString = (char*) malloc(stringSize+10),
              * newString = (char*) malloc(stringSize+10);
          memset(oldString, 0, stringSize);
          memset(newString,0, stringSize);
          if (oldString == 0 || newString == 0)
            KMessageBox::error(0, i18n("Out of memory."));
          else
            {
              if (fread(oldString, oldTextSize, 1, f) != 1)
                KMessageBox::error(0, i18n("Cannot read data."));
              else
                {
                  if (newTextSize > 0) // If there is a Replace text
                    {
                      if (fread(newString, newTextSize, 1, f) != 1)
                        KMessageBox::error(0, i18n("Cannot read data."));
                      else
                        {
                          QListViewItem* lvi = new QListViewItem(stringView);
                          lvi->setText(0,oldString);
                          lvi->setText(1,newString);

                          if(newString)
                            free(newString);
                          if(oldString)
                            free(oldString);
                        }
                    }
                }
            }
        }
    }
    fclose(f);
    return ;
 }

bool KFileReplaceLib::isAnAccessibleFile(const QString& filePath, const QString& fileName, RCOptions* info)
{
  QString bkExt = info->m_backupExtension;
  if(fileName == ".." || fileName == "." || (!bkExt.isEmpty() && fileName.right(bkExt.length()) == bkExt))
    return false;

  QFileInfo fi;
  if(filePath.isEmpty())
    fi.setFile(fileName);
  else
    fi.setFile(filePath+"/"+fileName);

  if(fi.isDir())
    return true;

   int minSize = info->m_minSize,
       maxSize = info->m_maxSize;
   QString minDate = info->m_minDate,
           maxDate = info->m_maxDate,
           dateAccess = info->m_dateAccess;

  // Avoid files that not match access date requirements
  QString last = "unknown";
  if(dateAccess == "Last Writing Access")
    last = fi.lastModified().toString(Qt::ISODate);
  if(dateAccess == "Last Reading Access")
    last = fi.lastRead().toString(Qt::ISODate);

  if(last != "unknown")
    {
      if(minDate != "unknown" && maxDate != "unknown")
        { //If out of range then exit
          if((minDate > last) || (maxDate < last))
            return false;
        }
      else
        {
          if(minDate != "unknown")
            { //If out of range then exit
              if(minDate > last)
                return false;
            }
          else
            {
              if(maxDate != "unknown")
              //If out of range then exit
              if(maxDate < last)
                return false;
            }
        }
    }
  // Avoid files that not match size requirements
  int size = fi.size();
  if(maxSize != FileSizeOption && minSize != FileSizeOption)
    if(size > (maxSize*1024) || size < (minSize*1024))
      return false;

  // Avoid files that not match ownership requirements
  if(info->m_ownerUserIsChecked)
    {
      QString fileOwnerUser;
      if(info->m_ownerUserType == "Name")
        fileOwnerUser = fi.owner();
      else
        fileOwnerUser = QString::number(fi.ownerId(),10);

      if(info->m_ownerUserBool == "Equals To")
        {
          if(info->m_ownerUserValue != fileOwnerUser)
            return false;
        }
      else
        {
          if(info->m_ownerUserValue == fileOwnerUser)
            return false;
        }
    }

  if(info->m_ownerGroupIsChecked)
    {
      QString fileOwnerGroup;
      if(info->m_ownerGroupType == "Name")
        fileOwnerGroup = fi.group();
      else
        fileOwnerGroup = QString::number(fi.groupId(),10);
      if(info->m_ownerGroupBool == "Equals To")
        {
          if(info->m_ownerGroupValue != fileOwnerGroup)
            return false;
        }
      else
        {
          if(info->m_ownerGroupValue == fileOwnerGroup)
            return false;
        }
    }

  //If we are here then all requirements have been verified
  return true;
}

void KFileReplaceLib::setIconForFileEntry(QListViewItem* item, QString path)
{
  QFileInfo fi(path);
  QString extension = fi.extension(),
          baseName = fi.baseName();

  KeyValueMap extensionMap;

  extensionMap["a"] = "binary";
  extensionMap["am"] = "shellscript";
  extensionMap["bz"] = "zip";
  extensionMap["bz2"] = "zip";
  extensionMap["c"] = "source_c";
  extensionMap["cc"] = "source_cpp";
  extensionMap["cpp"] = "source_cpp";
  extensionMap["eml"] = "message";
  extensionMap["exe"] = "exec_wine";
  extensionMap["gz"] = "zip";
  extensionMap["h"] = "source_h";
  extensionMap["htm"] = "html";
  extensionMap["html"] = "html";
  extensionMap["in"] = "shellscript";
  extensionMap["java"] = "source_java";
  extensionMap["jpg"] = "image";
  extensionMap["kfr"] = "html";
  extensionMap["kmdr"] = "widget_doc";
  extensionMap["kwd"] = "kword_kwd";
  extensionMap["log"] = "log";
  extensionMap["moc"] = "source_moc";
  extensionMap["mp3"] = "sound";
  extensionMap["o"] = "source_o";
  extensionMap["pdf"] = "pdf";
  extensionMap["php"] = "source_php";
  extensionMap["py"] = "source_py";
  extensionMap["pl"] = "source_pl";
  extensionMap["p"] = "source_p";
  extensionMap["ps"] = "postscript";
  extensionMap["png"] = "image";
  extensionMap["sa"] = "binary";
  extensionMap["sh"] = "shellscript";
  extensionMap["so"] = "binary";
  extensionMap["tar"] = "tar";
  extensionMap["tex"] = "tex";
  extensionMap["tgz"] = "tgz";
  extensionMap["txt"] = "txt";
  extensionMap["ui"] = "widget_doc";
  extensionMap["uml"] = "umbrellofile";
  extensionMap["wav"] = "sound";
  extensionMap["xml"] = "html";
  extensionMap["xpm"] = "image";

  KeyValueMap::Iterator itExtensionMap;

  for(itExtensionMap = extensionMap.begin(); itExtensionMap != extensionMap.end(); ++itExtensionMap)
    {
      if(extension == itExtensionMap.key())
        {
          item->setPixmap(0,SmallIcon(itExtensionMap.data()));
          return;
        }
    }

  KeyValueMap baseNameMap;

  baseNameMap["configure"] = "shellscript";
  baseNameMap["core"] = "core";
  baseNameMap["makefile"] = "make";
  baseNameMap["readme"] = "readme";
  baseNameMap["README"] = "readme";
  baseNameMap["Readme"] = "readme";
  baseNameMap["TODO"] = "txt";

  KeyValueMap::Iterator itBaseNameMap;

  for(itBaseNameMap = baseNameMap.begin(); itBaseNameMap != baseNameMap.end(); ++itBaseNameMap)
    {
      if(baseName == itBaseNameMap.key())
        {
          item->setPixmap(0,SmallIcon(itBaseNameMap.data()));
          return;
        }
    }
}