void encode(ArgumentEncoder& encoder, GtkPageSetup* pageSetup) { GOwnPtr<GKeyFile> keyFile(g_key_file_new()); gtk_page_setup_to_key_file(pageSetup, keyFile.get(), "Page Setup"); encodeGKeyFile(encoder, keyFile.get()); }
bool Servatrice::initServer() { serverName = settingsCache->value("server/name", "My Cockatrice server").toString(); serverId = settingsCache->value("server/id", 0).toInt(); clientIdRequired = settingsCache->value("server/requireclientid",0).toBool(); regServerOnly = settingsCache->value("authentication/regonly", 0).toBool(); const QString authenticationMethodStr = settingsCache->value("authentication/method").toString(); if (authenticationMethodStr == "sql") { qDebug() << "Authenticating method: sql"; authenticationMethod = AuthenticationSql; } else if(authenticationMethodStr == "password") { qDebug() << "Authenticating method: password"; authenticationMethod = AuthenticationPassword; } else { if (regServerOnly) { qDebug() << "Registration only server enabled but no authentication method defined: Error."; return false; } qDebug() << "Authenticating method: none"; authenticationMethod = AuthenticationNone; } qDebug() << "Store Replays: " << settingsCache->value("game/store_replays", true).toBool(); qDebug() << "Client ID Required: " << clientIdRequired; bool maxUserLimitEnabled = settingsCache->value("security/enable_max_user_limit", false).toBool(); qDebug() << "Maximum user limit enabled: " << maxUserLimitEnabled; if (maxUserLimitEnabled){ int maxUserLimit = settingsCache->value("security/max_users_total", 500).toInt(); qDebug() << "Maximum total user limit: " << maxUserLimit; int maxTcpUserLimit = settingsCache->value("security/max_users_tcp", 500).toInt(); qDebug() << "Maximum tcp user limit: " << maxTcpUserLimit; int maxWebsocketUserLimit = settingsCache->value("security/max_users_websocket", 500).toInt(); qDebug() << "Maximum websocket user limit: " << maxWebsocketUserLimit; } bool registrationEnabled = settingsCache->value("registration/enabled", false).toBool(); bool requireEmailForRegistration = settingsCache->value("registration/requireemail", true).toBool(); bool requireEmailActivation = settingsCache->value("registration/requireemailactivation", true).toBool(); qDebug() << "Accept registered users only: " << regServerOnly; qDebug() << "Registration enabled: " << registrationEnabled; if (registrationEnabled) { qDebug() << "Require email address to register: " << requireEmailForRegistration; qDebug() << "Require email activation via token: " << requireEmailActivation; } FeatureSet features; features.initalizeFeatureList(serverRequiredFeatureList); requiredFeatures = settingsCache->value("server/requiredfeatures","").toString(); QStringList listReqFeatures = requiredFeatures.split(",", QString::SkipEmptyParts); if (!listReqFeatures.isEmpty()) foreach(QString reqFeature, listReqFeatures) features.enableRequiredFeature(serverRequiredFeatureList,reqFeature); qDebug() << "Required client features: " << serverRequiredFeatureList; QString dbTypeStr = settingsCache->value("database/type").toString(); if (dbTypeStr == "mysql") databaseType = DatabaseMySql; else databaseType = DatabaseNone; servatriceDatabaseInterface = new Servatrice_DatabaseInterface(-1, this); setDatabaseInterface(servatriceDatabaseInterface); if (databaseType != DatabaseNone) { settingsCache->beginGroup("database"); dbPrefix = settingsCache->value("prefix").toString(); bool dbOpened = servatriceDatabaseInterface->initDatabase("QMYSQL", settingsCache->value("hostname").toString(), settingsCache->value("database").toString(), settingsCache->value("user").toString(), settingsCache->value("password").toString()); settingsCache->endGroup(); if (!dbOpened) { qDebug() << "Failed to open database"; return false; } updateServerList(); qDebug() << "Clearing previous sessions..."; servatriceDatabaseInterface->clearSessionTables(); } const QString roomMethod = settingsCache->value("rooms/method").toString(); if (roomMethod == "sql") { QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, name, descr, permissionlevel, auto_join, join_message, chat_history_size from {prefix}_rooms where id_server = :id_server order by id asc"); query->bindValue(":id_server", serverId); servatriceDatabaseInterface->execSqlQuery(query); while (query->next()) { QSqlQuery *query2 = servatriceDatabaseInterface->prepareQuery("select name from {prefix}_rooms_gametypes where id_room = :id_room AND id_server = :id_server"); query2->bindValue(":id_server", serverId); query2->bindValue(":id_room", query->value(0).toInt()); servatriceDatabaseInterface->execSqlQuery(query2); QStringList gameTypes; while (query2->next()) gameTypes.append(query2->value(0).toString()); addRoom(new Server_Room(query->value(0).toInt(), query->value(6).toInt(), query->value(1).toString(), query->value(2).toString(), query->value(3).toString().toLower(), query->value(4).toInt(), query->value(5).toString(), gameTypes, this )); } } else { int size = settingsCache->beginReadArray("rooms/roomlist"); for (int i = 0; i < size; ++i) { settingsCache->setArrayIndex(i); QStringList gameTypes; int size2 = settingsCache->beginReadArray("game_types"); for (int j = 0; j < size2; ++j) { settingsCache->setArrayIndex(j); gameTypes.append(settingsCache->value("name").toString()); } settingsCache->endArray(); Server_Room *newRoom = new Server_Room( i, settingsCache->value("chathistorysize").toInt(), settingsCache->value("name").toString(), settingsCache->value("description").toString(), settingsCache->value("permissionlevel").toString().toLower(), settingsCache->value("autojoin").toBool(), settingsCache->value("joinmessage").toString(), gameTypes, this ); addRoom(newRoom); } if(size==0) { // no room defined in config, add a dummy one Server_Room *newRoom = new Server_Room( 0, 100, "General room", "Play anything here.", "none", true, "", QStringList("Standard"), this ); addRoom(newRoom); } settingsCache->endArray(); } updateLoginMessage(); maxGameInactivityTime = settingsCache->value("game/max_game_inactivity_time", 120).toInt(); maxPlayerInactivityTime = settingsCache->value("server/max_player_inactivity_time", 15).toInt(); pingClockInterval = settingsCache->value("server/clientkeepalive", 1).toInt(); maxUsersPerAddress = settingsCache->value("security/max_users_per_address", 4).toInt(); messageCountingInterval = settingsCache->value("security/message_counting_interval", 10).toInt(); maxMessageCountPerInterval = settingsCache->value("security/max_message_count_per_interval", 15).toInt(); maxMessageSizePerInterval = settingsCache->value("security/max_message_size_per_interval", 1000).toInt(); maxGamesPerUser = settingsCache->value("security/max_games_per_user", 5).toInt(); commandCountingInterval = settingsCache->value("game/command_counting_interval", 10).toInt(); maxCommandCountPerInterval = settingsCache->value("game/max_command_count_per_interval", 20).toInt(); try { if (settingsCache->value("servernetwork/active", 0).toInt()) { qDebug() << "Connecting to ISL network."; const QString certFileName = settingsCache->value("servernetwork/ssl_cert").toString(); const QString keyFileName = settingsCache->value("servernetwork/ssl_key").toString(); qDebug() << "Loading certificate..."; QFile certFile(certFileName); if (!certFile.open(QIODevice::ReadOnly)) throw QString("Error opening certificate file: %1").arg(certFileName); QSslCertificate cert(&certFile); const QDateTime currentTime = QDateTime::currentDateTime(); if(currentTime < cert.effectiveDate() || currentTime > cert.expiryDate() || cert.isBlacklisted()) throw(QString("Invalid certificate.")); qDebug() << "Loading private key..."; QFile keyFile(keyFileName); if (!keyFile.open(QIODevice::ReadOnly)) throw QString("Error opening private key file: %1").arg(keyFileName); QSslKey key(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey); if (key.isNull()) throw QString("Invalid private key."); QMutableListIterator<ServerProperties> serverIterator(serverList); while (serverIterator.hasNext()) { const ServerProperties &prop = serverIterator.next(); if (prop.cert == cert) { serverIterator.remove(); continue; } QThread *thread = new QThread; thread->setObjectName("isl_" + QString::number(prop.id)); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); IslInterface *interface = new IslInterface(prop.id, prop.hostname, prop.address.toString(), prop.controlPort, prop.cert, cert, key, this); interface->moveToThread(thread); connect(interface, SIGNAL(destroyed()), thread, SLOT(quit())); thread->start(); QMetaObject::invokeMethod(interface, "initClient", Qt::BlockingQueuedConnection); } const int networkPort = settingsCache->value("servernetwork/port", 14747).toInt(); qDebug() << "Starting ISL server on port" << networkPort; islServer = new Servatrice_IslServer(this, cert, key, this); if (islServer->listen(QHostAddress::Any, networkPort)) qDebug() << "ISL server listening."; else throw QString("islServer->listen()"); } } catch (QString error) { qDebug() << "ERROR --" << error; return false; } pingClock = new QTimer(this); connect(pingClock, SIGNAL(timeout()), this, SIGNAL(pingClockTimeout())); pingClock->start(pingClockInterval * 1000); int statusUpdateTime = settingsCache->value("server/statusupdate", 15000).toInt(); statusUpdateClock = new QTimer(this); connect(statusUpdateClock, SIGNAL(timeout()), this, SLOT(statusUpdate())); if (statusUpdateTime != 0) { qDebug() << "Starting status update clock, interval " << statusUpdateTime << " ms"; statusUpdateClock->start(statusUpdateTime); } // SOCKET SERVER const int numberPools = settingsCache->value("server/number_pools", 1).toInt(); if(numberPools > 0) { gameServer = new Servatrice_GameServer(this, numberPools, servatriceDatabaseInterface->getDatabase(), this); gameServer->setMaxPendingConnections(1000); const int gamePort = settingsCache->value("server/port", 4747).toInt(); qDebug() << "Starting server on port" << gamePort; if (gameServer->listen(QHostAddress::Any, gamePort)) qDebug() << "Server listening."; else { qDebug() << "gameServer->listen(): Error:" << gameServer->errorString(); return false; } } #if QT_VERSION > 0x050300 // WEBSOCKET SERVER const int wesocketNumberPools = settingsCache->value("server/websocket_number_pools", 1).toInt(); if(wesocketNumberPools > 0) { websocketGameServer = new Servatrice_WebsocketGameServer(this, wesocketNumberPools, servatriceDatabaseInterface->getDatabase(), this); websocketGameServer->setMaxPendingConnections(1000); const int websocketGamePort = settingsCache->value("server/websocket_port", 4748).toInt(); qDebug() << "Starting websocket server on port" << websocketGamePort; if (websocketGameServer->listen(QHostAddress::Any, websocketGamePort)) qDebug() << "Websocket server listening."; else { qDebug() << "websocketGameServer->listen(): Error:" << websocketGameServer->errorString(); return false; } } #endif return true; }
// Testing the I/O of the important classes of the library // (context, keys, ciphertexts). int main(int argc, char *argv[]) { ArgMapping amap; long r=1; long p=2; long c = 2; long w = 64; long L = 5; amap.arg("p", p, "plaintext base"); amap.arg("r", r, "lifting"); amap.arg("c", c, "number of columns in the key-switching matrices"); amap.parse(argc, argv); long ptxtSpace = power_long(p,r); FHEcontext* contexts[N_TESTS]; FHESecKey* sKeys[N_TESTS]; Ctxt* ctxts[N_TESTS]; EncryptedArray* eas[N_TESTS]; vector<ZZX> ptxts[N_TESTS]; // first loop: generate stuff and write it to cout // open file for writing {fstream keyFile("iotest.txt", fstream::out|fstream::trunc); assert(keyFile.is_open()); for (long i=0; i<N_TESTS; i++) { long m = ms[i][1]; cout << "Testing IO: m="<<m<<", p^r="<<p<<"^"<<r<<endl; if (i==N_TESTS-1) { // test bootstrapping data I/O Vec<long> mvec(INIT_SIZE,2); mvec[0] = ms[i][4]; mvec[1] = ms[i][5]; vector<long> gens(2); gens[0] = ms[i][6]; gens[1] = ms[i][7]; vector<long> ords(2); ords[0] = ms[i][8]; ords[1] = ms[i][9]; contexts[i] = new FHEcontext(m, p, r, gens, ords); buildModChain(*contexts[i], L, c); // Set the modulus chain contexts[i]->makeBootstrappable(mvec); } else { contexts[i] = new FHEcontext(m, p, r); buildModChain(*contexts[i], L, c); // Set the modulus chain } // Output the FHEcontext to file writeContextBase(keyFile, *contexts[i]); keyFile << *contexts[i] << endl; sKeys[i] = new FHESecKey(*contexts[i]); const FHEPubKey& publicKey = *sKeys[i]; sKeys[i]->GenSecKey(w,ptxtSpace); // A Hamming-weight-w secret key addSome1DMatrices(*sKeys[i]);// compute key-switching matrices that we need eas[i] = new EncryptedArray(*contexts[i]); long nslots = eas[i]->size(); // Output the secret key to file, twice. Below we will have two copies // of most things. keyFile << *sKeys[i] << endl;; keyFile << *sKeys[i] << endl;; vector<ZZX> b; long p2r = eas[i]->getContext().alMod.getPPowR(); ZZX poly = RandPoly(0,to_ZZ(p2r)); // choose a random constant polynomial eas[i]->decode(ptxts[i], poly); ctxts[i] = new Ctxt(publicKey); eas[i]->encrypt(*ctxts[i], publicKey, ptxts[i]); eas[i]->decrypt(*ctxts[i], *sKeys[i], b); assert(ptxts[i].size() == b.size()); for (long j = 0; j < nslots; j++) assert (ptxts[i][j] == b[j]); // output the plaintext keyFile << "[ "; for (long j = 0; j < nslots; j++) keyFile << ptxts[i][j] << " "; keyFile << "]\n"; eas[i]->encode(poly,ptxts[i]); keyFile << poly << endl; // Output the ciphertext to file keyFile << *ctxts[i] << endl; keyFile << *ctxts[i] << endl; cerr << "okay " << i << endl; } keyFile.close();} cerr << "so far, so good\n"; // second loop: read from input and repeat the computation // open file for read {fstream keyFile("iotest.txt", fstream::in); for (long i=0; i<N_TESTS; i++) { // Read context from file unsigned long m1, p1, r1; vector<long> gens, ords; readContextBase(keyFile, m1, p1, r1, gens, ords); FHEcontext tmpContext(m1, p1, r1, gens, ords); keyFile >> tmpContext; assert (*contexts[i] == tmpContext); cerr << i << ": context matches input\n"; // We define some things below wrt *contexts[i], not tmpContext. // This is because the various operator== methods check equality of // references, not equality of the referenced FHEcontext objects. FHEcontext& context = *contexts[i]; FHESecKey secretKey(context); FHESecKey secretKey2(tmpContext); const FHEPubKey& publicKey = secretKey; const FHEPubKey& publicKey2 = secretKey2; keyFile >> secretKey; keyFile >> secretKey2; assert(secretKey == *sKeys[i]); cerr << " secret key matches input\n"; EncryptedArray ea(context); EncryptedArray ea2(tmpContext); long nslots = ea.size(); // Read the plaintext from file vector<ZZX> a; a.resize(nslots); assert(nslots == (long)ptxts[i].size()); seekPastChar(keyFile, '['); // defined in NumbTh.cpp for (long j = 0; j < nslots; j++) { keyFile >> a[j]; assert(a[j] == ptxts[i][j]); } seekPastChar(keyFile, ']'); cerr << " ptxt matches input\n"; // Read the encoded plaintext from file ZZX poly1, poly2; keyFile >> poly1; eas[i]->encode(poly2,a); assert(poly1 == poly2); cerr << " eas[i].encode(a)==poly1 okay\n"; ea.encode(poly2,a); assert(poly1 == poly2); cerr << " ea.encode(a)==poly1 okay\n"; ea2.encode(poly2,a); assert(poly1 == poly2); cerr << " ea2.encode(a)==poly1 okay\n"; eas[i]->decode(a,poly1); assert(nslots == (long)a.size()); for (long j = 0; j < nslots; j++) assert(a[j] == ptxts[i][j]); cerr << " eas[i].decode(poly1)==ptxts[i] okay\n"; ea.decode(a,poly1); assert(nslots == (long)a.size()); for (long j = 0; j < nslots; j++) assert(a[j] == ptxts[i][j]); cerr << " ea.decode(poly1)==ptxts[i] okay\n"; ea2.decode(a,poly1); assert(nslots == (long)a.size()); for (long j = 0; j < nslots; j++) assert(a[j] == ptxts[i][j]); cerr << " ea2.decode(poly1)==ptxts[i] okay\n"; // Read ciperhtext from file Ctxt ctxt(publicKey); Ctxt ctxt2(publicKey2); keyFile >> ctxt; keyFile >> ctxt2; assert(ctxts[i]->equalsTo(ctxt,/*comparePkeys=*/false)); cerr << " ctxt matches input\n"; sKeys[i]->Decrypt(poly2,*ctxts[i]); assert(poly1 == poly2); cerr << " sKeys[i]->decrypt(*ctxts[i]) == poly1 okay\n"; secretKey.Decrypt(poly2,*ctxts[i]); assert(poly1 == poly2); cerr << " secretKey.decrypt(*ctxts[i]) == poly1 okay\n"; secretKey.Decrypt(poly2,ctxt); assert(poly1 == poly2); cerr << " secretKey.decrypt(ctxt) == poly1 okay\n"; secretKey2.Decrypt(poly2,ctxt2); assert(poly1 == poly2); cerr << " secretKey2.decrypt(ctxt2) == poly1 okay\n"; eas[i]->decrypt(ctxt, *sKeys[i], a); assert(nslots == (long)a.size()); for (long j = 0; j < nslots; j++) assert(a[j] == ptxts[i][j]); cerr << " eas[i].decrypt(ctxt, *sKeys[i])==ptxts[i] okay\n"; ea.decrypt(ctxt, secretKey, a); assert(nslots == (long)a.size()); for (long j = 0; j < nslots; j++) assert(a[j] == ptxts[i][j]); cerr << " ea.decrypt(ctxt, secretKey)==ptxts[i] okay\n"; ea2.decrypt(ctxt2, secretKey2, a); assert(nslots == (long)a.size()); for (long j = 0; j < nslots; j++) assert(a[j] == ptxts[i][j]); cerr << " ea2.decrypt(ctxt2, secretKey2)==ptxts[i] okay\n"; cerr << "test "<<i<<" okay\n\n"; }} unlink("iotest.txt"); // clean up before exiting }
void encode(ArgumentEncoder& encoder, GtkPrintSettings* printSettings) { GOwnPtr<GKeyFile> keyFile(g_key_file_new()); gtk_print_settings_to_key_file(printSettings, keyFile.get(), "Print Settings"); encodeGKeyFile(encoder, keyFile.get()); }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(guiclient); QString username; QString databaseURL; QString passwd; QString company; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; bool haveEnhancedAuth= false; bool _enhancedAuth = false; bool haveRequireSSL = false; bool _requireSSL = false; bool havePasswd = false; bool cloudOption = false; bool haveCloud = false; qInstallMsgHandler(xTupleMessageOutput); QApplication app(argc, argv); #if QT_VERSION >= 0x040400 // This is the correct place for this call but on versions less // than 4.4 it causes a crash for an unknown reason so it is // called later on earlier versions. QCoreApplication::addLibraryPath(QString(".")); #endif #ifndef Q_WS_MACX QApplication::setWindowIcon(QIcon(":/images/icon32x32.png")); #endif // Try and load a default translation file and install it QTranslator defaultTranslator(&app); if (defaultTranslator.load("default.qm", app.applicationDirPath())) app.installTranslator(&defaultTranslator); app.processEvents(); if (argc > 1) { for (int intCounter = 1; intCounter < argc; intCounter++) { QString argument(argv[intCounter]); if (argument.contains("-databaseURL=", Qt::CaseInsensitive)) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.contains("-username="******"-passwd=", Qt::CaseInsensitive)) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.contains("-noAuth", Qt::CaseInsensitive)) { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.contains("-enhancedAuth", Qt::CaseInsensitive)) { haveEnhancedAuth = true; _enhancedAuth = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _enhancedAuth = false; } else if (argument.contains("-requireSSL", Qt::CaseInsensitive)) { haveRequireSSL = true; _requireSSL = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) _requireSSL = false; } else if (argument.contains("-cloud", Qt::CaseInsensitive)) { haveCloud = true; cloudOption = true; if(argument.contains("=no", Qt::CaseInsensitive) || argument.contains("=false", Qt::CaseInsensitive)) cloudOption = false; } else if (argument.contains("-company=", Qt::CaseInsensitive)) { company = argument.right(argument.length() - 9); } } } _splash = new QSplashScreen(); _splash->setPixmap(QPixmap(":/images/splashEmpty.png")); _evaluation = FALSE; if (!loggedIn) { ParameterList params; params.append("copyright", _Copyright); params.append("version", _Version); params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__)); if (haveUsername) params.append("username", username); if (havePasswd) params.append("password", passwd); if (haveDatabaseURL) params.append("databaseURL", databaseURL); if (haveEnhancedAuth) params.append("enhancedAuth", _enhancedAuth); if (haveRequireSSL) params.append("requireSSL", _requireSSL); if (_evaluation) params.append("evaluation"); if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) params.append("login"); if (haveCloud) params.append("cloud", cloudOption); if (!company.isEmpty()) params.append("company", company); login2 newdlg(0, "", TRUE); newdlg.set(params, _splash); if(newdlg.result() != QDialog::Accepted) { if (newdlg.exec() == QDialog::Rejected) return -1; else { databaseURL = newdlg._databaseURL; username = newdlg.username(); __password = newdlg.password(); company = newdlg.company(); cloudOption = newdlg.useCloud(); } } } XSqlQuery metric; metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'Application')" ); if(!metric.first() || (metric.value("metric_value").toString() == "Standard")) { // check if the xtmfg package is installed metric.exec("SELECT pkghead_name FROM pkghead WHERE pkghead_name='xtmfg'"); if(metric.first()) { _splash->setPixmap(QPixmap(":/images/splashMfgEdition.png")); _Name = _Name.arg("Manufacturing"); } else { _splash->setPixmap(QPixmap(":/images/splashStdEdition.png")); _Name = _Name.arg("Standard"); } _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); metric.exec("SELECT COUNT(*) as _count" " FROM pg_stat_activity" " WHERE(datid IN (SELECT datid" " FROM pg_stat_activity" " WHERE(procpid=pg_backend_pid())));"); int cnt = 50000; if(metric.first()) cnt = metric.value("_count").toInt(); metric.exec("SELECT metric_value" " FROM metric" " WHERE(metric_name = 'RegistrationKey');"); bool checkPass = true; QString checkPassReason; QString rkey = ""; if(metric.first()) rkey = metric.value("metric_value").toString(); XTupleProductKey pkey(rkey); if(pkey.valid() && pkey.version() == 1) { if(pkey.expiration() < QDate::currentDate()) { checkPass = false; checkPassReason = QObject::tr("Your license has expired."); } else if(pkey.users() != 0 && (pkey.users()+1) < cnt) { checkPass = false; checkPassReason = QObject::tr("You have exceeded the number of allowed concurrent users for your license."); } } else { checkPass = false; checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid."); } if(!checkPass) { _splash->hide(); QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason); metric.exec("SELECT current_database() AS db," " fetchMetricText('DatabaseName') AS dbname," " fetchMetricText('remitto_name') AS name;"); QString db = ""; QString dbname = ""; QString name = ""; if(metric.first()) { db = metric.value("db").toString(); dbname = metric.value("dbname").toString(); name = metric.value("name").toString(); } QHttp *http = new QHttp(); QUrl url; url.setPath("/api/regviolation.php"); url.addQueryItem("key", QUrl::toPercentEncoding(rkey)); url.addQueryItem("error", QUrl::toPercentEncoding(checkPassReason)); url.addQueryItem("name", QUrl::toPercentEncoding(name)); url.addQueryItem("dbname", QUrl::toPercentEncoding(dbname)); url.addQueryItem("db", QUrl::toPercentEncoding(db)); url.addQueryItem("cnt", QString::number(cnt)); http->setHost("www.xtuple.org"); http->get(url.toString()); _splash->show(); } } else { _splash->setPixmap(QPixmap(":/images/splashPostBooks.png")); _Name = _Name.arg("PostBooks"); } metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'ServerVersion')" ); if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) { bool disallowMismatch = false; metric.exec("SELECT metric_value FROM metric WHERE(metric_name='DisallowMismatchClientVersion')"); if(metric.first() && (metric.value("metric_value").toString() == "t")) disallowMismatch = true; _splash->hide(); int result; if(disallowMismatch) result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. The system has been configured to disallow " "access in this case.<p>Please contact your systems " "administrator.").arg(_dbVersion), QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default ); else result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("<p>The version of the database you are connecting to is " "not the version this client was designed to work against. " "This client was designed to work against the database " "version %1. If you continue some or all functionality may " "not work properly or at all. You may also cause other " "problems on the database.<p>Do you want to continue " "anyway?").arg(_dbVersion), QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ); if(result != QMessageBox::Yes) return 0; _splash->show(); } _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metrics = new Metrics(); _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _preferences = new Preferences(username); _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _privileges = new Privileges(); // Load the translator and set the locale from the User's preferences _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=CURRENT_USER)" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); QString langext; if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { langext = langq.value("lang_abbr2").toString(); } if(!langext.isEmpty()) { files << "xTuple"; files << "openrpt"; files << "reports"; XSqlQuery pkglist("SELECT pkghead_name" " FROM pkghead" " WHERE packageIsEnabled(pkghead_name);"); while(pkglist.next()) files << pkglist.value("pkghead_name").toString(); } if (files.size() > 0) { QStringList notfound; QTranslator *translator = new QTranslator(&app); for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { if (DEBUG) qDebug("looking for %s", (*fit).toAscii().data()); if (translator->load(translationFile(langext, *fit))) { app.installTranslator(translator); qDebug("installed %s", (*fit).toAscii().data()); translator = new QTranslator(&app); } else notfound << *fit; } if (! notfound.isEmpty() && !_preferences->boolean("IngoreMissingTranslationFiles")) QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"), QObject::tr("<p>The Translation Dictionaries %1 " "cannot be loaded. Reverting " "to the default dictionary." ) .arg(notfound.join(QObject::tr(", ")))); } /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or lang#, depending on what information is available */ QString langAbbr = langq.value("lang_abbr2").toString(); QString cntryAbbr = langq.value("country_abbr").toString().toUpper(); if(cntryAbbr == "UK") cntryAbbr = "GB"; if (! langAbbr.isEmpty() && ! cntryAbbr.isEmpty()) QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr)); else if (! langAbbr.isEmpty()) QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString())); else if (langq.value("lang_qt_number").toInt() && langq.value("country_qt_number").toInt()) QLocale::setDefault( QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()), QLocale::Country(langq.value("country_qt_number").toInt()))); else QLocale::setDefault(QLocale::system()); qDebug("Locale set to language %s and country %s", QLocale().languageToString(QLocale().language()).toAscii().data(), QLocale().countryToString(QLocale().country()).toAscii().data()); } else if (langq.lastError().type() != QSqlError::NoError) { systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__); } qApp->processEvents(); QString key; // TODO: Add code to check a few locations - Hopefully done QString keypath; QString keyname; QString keytogether; #ifdef Q_WS_WIN keypath = _metrics->value("CCWinEncKey"); #elif defined Q_WS_MACX keypath = _metrics->value("CCMacEncKey"); #elif defined Q_WS_X11 keypath = _metrics->value("CCLinEncKey"); #endif if (keypath.isEmpty()) keypath = app.applicationDirPath(); if (! keypath.endsWith(QDir::separator())) keypath += QDir::separator(); keyname = _metrics->value("CCEncKeyName"); if (keyname.isEmpty()) { keyname = "xTuple.key"; keytogether = keypath + keyname; QFile kn(keytogether); if(!kn.exists()) keyname = "OpenMFG.key"; } keytogether = keypath + keyname; // qDebug("keytogether: %s", keytogether.toAscii().data()); QFile keyFile(keytogether); if(keyFile.exists()) { if(keyFile.open(QIODevice::ReadOnly)) { key = keyFile.readLine(1024); // strip off any newline characters key = key.trimmed(); } } omfgThis = 0; omfgThis = new GUIClient(databaseURL, username); omfgThis->_key = key; omfgThis->_company = company; omfgThis->_useCloud = cloudOption; // qDebug("Encryption Key: %s", key.toAscii().data() ); if (key.length() > 0) { _splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metricsenc = new Metricsenc(key); } initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace()); // START code for updating the locale settings if they haven't been already XSqlQuery lc; lc.exec("SELECT count(*) FROM metric WHERE metric_name='AutoUpdateLocaleHasRun';"); lc.first(); if(lc.value(0).toInt() == 0) { lc.exec("INSERT INTO metric (metric_name, metric_value) values('AutoUpdateLocaleHasRun', 't');"); lc.exec("SELECT locale_id from locale;"); while(lc.next()) { ParameterList params; params.append("mode","edit"); params.append("locale_id", lc.value(0)); sysLocale lcdlg; lcdlg.set(params); lcdlg.sSave(); } } // END code for updating locale settings QObject::connect(&app, SIGNAL(aboutToQuit()), &app, SLOT(closeAllWindows())); if (omfgThis->_singleWindow.isEmpty()) { omfgThis->setAttribute(Qt::WA_DeleteOnClose); omfgThis->show(); } // keep this synchronized with GUIClient and user.ui.h else if (omfgThis->_singleWindow == "woTimeClock") { ScriptToolbox sb(0); QWidget* newdlg = sb.openWindow("woTimeClock"); if(newdlg) { XMainWindow *mw = qobject_cast<XMainWindow*>(newdlg); if(mw) { ParameterList params; params.append("captive"); mw->set(params); } newdlg->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(omfgThis, SIGNAL(destroyed(QObject*)), &app, SLOT(quit())); newdlg->show(); } else {
void scissorScene() { pScene sc; pMesh mesh; pPersp p; pTransform view; int width,height; /* default */ if ( ddebug ) printf("enable scissoring\n"); sc = cv.scene[currentScene()]; mesh = cv.mesh[sc->idmesh]; view = sc->view; p = sc->persp; /* subdivide main window */ glViewport(0,0,sc->par.xs,sc->par.ys); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,sc->par.xs,0,sc->par.ys); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(sc->par.back[0],sc->par.back[1],sc->par.back[2],sc->par.back[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* split window */ glDisable(GL_LIGHTING); glColor4fv(sc->par.line); glBegin(GL_LINES); glVertex2i(sc->par.xs/2,0); glVertex2i(sc->par.xs/2,sc->par.ys); glVertex2i(0,sc->par.ys/2); glVertex2i(sc->par.xs,sc->par.ys/2); glEnd(); glEnable(GL_LIGHTING); width = (sc->par.xs + 1)/2; height = (sc->par.ys + 1)/2; glDisable(GL_LIGHTING); glColor4fv(sc->par.line); output2(5,sc->par.ys/2+5,"Top"); output2(5,5,"Front"); output2(sc->par.xs/2+5,5,"Right"); glEnable(GL_SCISSOR_TEST); /* draw top right : normal */ glViewport(width,height,width,height); glScissor(width,height,width,height); farclip(1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.,0.,-p->depth, 0.,0.,0., 0.0,1.0,0.0); setupView(sc); glMultMatrixf(view->matrix); glTranslatef(sc->cx,sc->cy,sc->cz); drawModel(sc); if ( sc->type & S_DECO ) redrawStatusBar(sc); /* draw top left : top view */ glViewport(0,height,width,height); glScissor(0,height,width,height); farclip(1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.,0.,-p->depth, 0.,0.,0., 0.0,1.0,0.0); setupView(sc); glTranslatef(sc->cx,sc->cy,sc->cz); glRotatef(-90,0.0,0.0,1.0); glTranslatef(view->opanx,0.,0.); drawModel(sc); /* draw bottom left : front */ glViewport(0,0,width,height); glScissor(0,0,width,height); farclip(1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.,0.,-p->depth, 0.,0.,0., 0.0,1.0,0.0); setupView(sc); glTranslatef(sc->cx,sc->cy,sc->cz); glRotatef(-90.0,1.0,0.0,0.0); glTranslatef(view->opanx,0.,0.); drawModel(sc); /* draw bottom right : right */ glViewport(width,0,width,height); glScissor(width,0,width,height); farclip(1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.,0.,-p->depth, 0.,0.,0., 0.0,1.0,0.0); setupView(sc); glRotatef(-90.0,1.0,0.0,0.0); glRotatef(-90.0,0.0,0.0,1.0); glTranslatef(0.,view->opany,0.); drawModel(sc); glutSwapBuffers(); glDisable(GL_SCISSOR_TEST); glViewport(0,0,sc->par.xs,sc->par.ys); if ( saveimg ) keyFile('H',0,0); }
int main(int argc, char *argv[]) { Q_INIT_RESOURCE(guiclient); QString username; QString databaseURL; bool haveUsername = FALSE; bool haveDatabaseURL = FALSE; bool loggedIn = FALSE; #ifdef XQ_WS_WIN WSADATA wsaData; if (WSAStartup(MAKEWORD(1, 1), &wsaData)) { qDebug("Error starting up Windows Socket system... Database services are not avalable."); exit(-1); } #endif QApplication app(argc, argv); app.addLibraryPath("."); #ifdef Q_WS_WIN if (app.winVersion() == QSysInfo::WV_XP) app.setStyle(QStyleFactory::create("windowsxpstyle")); #if QT_VERSION >= 0x040300 else if (app.winVersion() == QSysInfo::WV_VISTA) app.setStyle(QStyleFactory::create("windowsvistastyle")); #endif else app.setStyle(new QWindowsStyle); #elif defined Q_WS_MACX app.setStyle(new QMacStyle); #elif defined Q_WS_X11 app.setStyle(new QWindowsStyle); #endif // Try and load a default translation file and install it QTranslator defaultTranslator(0); if (defaultTranslator.load("default.qm", app.applicationDirPath())) app.installTranslator(&defaultTranslator); app.processEvents(); if (argc > 1) { bool havePasswd = FALSE; bool interactive = TRUE; bool createCountTags = FALSE; QString passwd; for (int intCounter = 1; intCounter < argc; intCounter++) { QString argument(argv[intCounter]); if (argument.contains("-databaseURL=")) { haveDatabaseURL = TRUE; databaseURL = argument.right(argument.length() - 13); } else if (argument.contains("-username="******"-passwd=")) { havePasswd = TRUE; passwd = argument.right(argument.length() - 8); } else if (argument.contains("-noAuth")) { haveUsername = TRUE; havePasswd = TRUE; } else if (argument.contains("-createCountTags")) { interactive = FALSE; createCountTags = TRUE; } } if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) ) { QSqlDatabase db; QString hostName; QString dbName; QString port; db = QSqlDatabase::addDatabase("QPSQL7"); if (!db.isValid()) { qDebug("Cannot load Database Driver. Contact your Systems Administrator."); exit(-1); } QString protocol; parseDatabaseURL(databaseURL, protocol, hostName, dbName, port); db.setDatabaseName(dbName); db.setUserName(username); db.setPassword(passwd); db.setHostName(hostName); bool valport = false; int iport = port.toInt(&valport); if(!valport) iport = 5432; db.setPort(iport); if (!db.open()) { qDebug( QObject::tr( "Cannot log onto the database with the supplied username/password!\n" "Host = %1\n" "Database = %2\n" "Username = %3\n" ) .arg(hostName) .arg(dbName) .arg(username) ); exit(-1); } else loggedIn = TRUE; } if (!interactive) return 0; } _splash = new QSplashScreen(); _splash->setPixmap(QPixmap(":/images/splashEmpty.png")); _evaluation = FALSE; if (!loggedIn) { ParameterList params; // params.append("name", _Name); -- We can't tell now until were logged in what the app is. params.append("copyright", _Copyright); params.append("version", _Version); params.append("build", QString("%1 %2").arg(__DATE__).arg(__TIME__)); if (haveUsername) params.append("username", username); if (haveDatabaseURL) params.append("databaseURL", databaseURL); if (_evaluation) params.append("evaluation"); login2 newdlg(0, "", TRUE); newdlg.set(params, _splash); if (newdlg.exec() == QDialog::Rejected) return -1; else { databaseURL = newdlg._databaseURL; username = newdlg.username(); } } XSqlQuery metric; metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'Application')" ); if(!metric.first() || (metric.value("metric_value").toString() == "OpenMFG")) { _splash->setPixmap(QPixmap(":/images/splashOpenMFG.png")); _Name = _Name.arg("OpenMFG"); } else if(!metric.first() || (metric.value("metric_value").toString() == "xTupleERP")) { _splash->setPixmap(QPixmap(":/images/splashxTupleERP.png")); _Name = _Name.arg("Standard"); } else { _splash->setPixmap(QPixmap(":/images/splashPostBooks.png")); _Name = _Name.arg("PostBooks"); } metric.exec("SELECT metric_value" " FROM metric" " WHERE (metric_name = 'OpenMFGServerVersion')" ); if(!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) { _splash->hide(); int result; result = QMessageBox::warning( 0, QObject::tr("Version Mismatch"), QObject::tr("The version of the database you are connecting to is not the version\n" "this client was designed to work against.\n\n" "This client was designed to work against the database version %1.\n" "If you continue some or all functionality may not work properly\n" "or at all. You may also cause other problems on the database.\n\n" "Do you want to continue anyway?").arg(_dbVersion), QMessageBox::Yes, QMessageBox::No | QMessageBox::Escape | QMessageBox::Default ); if(result != QMessageBox::Yes) return 0; _splash->show(); } _splash->showMessage(QObject::tr("Loading Database Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metrics = new Metrics(); _splash->showMessage(QObject::tr("Loading User Preferences"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _preferences = new Preferences(username); _splash->showMessage(QObject::tr("Loading User Privileges"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _privileges = new Privileges(); // Load the translator and set the locale from the User's preferences QTranslator translator(0); _splash->showMessage(QObject::tr("Loading Translation Dictionary"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); XSqlQuery langq("SELECT * " "FROM usr, locale LEFT OUTER JOIN" " lang ON (locale_lang_id=lang_id) LEFT OUTER JOIN" " country ON (locale_country_id=country_id) " "WHERE ( (usr_username=CURRENT_USER)" " AND (usr_locale_id=locale_id) );" ); if (langq.first()) { QStringList paths; paths << "dict"; paths << ""; paths << "../dict"; paths << app.applicationDirPath() + "/dict"; paths << app.applicationDirPath(); paths << app.applicationDirPath() + "/../dict"; #if defined Q_WS_MACX paths << app.applicationDirPath() + "/../../../dict"; paths << app.applicationDirPath() + "/../../.."; #endif QStringList files; if (!langq.value("locale_lang_file").toString().isEmpty()) files << langq.value("locale_lang_file").toString(); if (!langq.value("lang_abbr2").toString().isEmpty() && !langq.value("country_abbr").toString().isEmpty()) { files << "xTuple." + langq.value("lang_abbr2").toString() + "_" + langq.value("country_abbr").toString().toLower(); } else if (!langq.value("lang_abbr2").toString().isEmpty()) { files << "xTuple." + langq.value("lang_abbr2").toString(); } if (files.size() > 0) { bool langFound = false; for (QStringList::Iterator fit = files.begin(); fit != files.end(); ++fit) { for(QStringList::Iterator pit = paths.begin(); pit != paths.end(); ++pit) { qDebug("looking for %s in %s", (*fit).toAscii().data(), (*pit).toAscii().data()); if (translator.load(*fit, *pit)) { app.installTranslator(&translator); langFound = true; break; } } } if (!langFound && !_preferences->boolean("IngoreMissingTranslationFiles")) QMessageBox::warning( 0, QObject::tr("Cannot Load Dictionary"), QObject::tr("<p>The Translation Dictionaries %1 " "cannot be loaded. Reverting " "to the default dictionary." ) .arg(files.join(QObject::tr(", ")))); } /* set the locale to langabbr_countryabbr, langabbr, {lang# country#}, or lang#, depending on what information is available */ QString langAbbr = langq.value("lang_abbr2").toString(); QString cntryAbbr = langq.value("country_abbr").toString().toUpper(); if(cntryAbbr == "UK") cntryAbbr = "GB"; if (! langAbbr.isEmpty() && ! cntryAbbr.isEmpty()) QLocale::setDefault(QLocale(langAbbr + "_" + cntryAbbr)); else if (! langAbbr.isEmpty()) QLocale::setDefault(QLocale(langq.value("lang_abbr2").toString())); else if (langq.value("lang_qt_number").toInt() && langq.value("country_qt_number").toInt()) QLocale::setDefault( QLocale(QLocale::Language(langq.value("lang_qt_number").toInt()), QLocale::Country(langq.value("country_qt_number").toInt()))); else QLocale::setDefault(QLocale::system()); qDebug("Locale set to language %s and country %s", QLocale().languageToString(QLocale().language()).toAscii().data(), QLocale().countryToString(QLocale().country()).toAscii().data()); } else if (langq.lastError().type() != QSqlError::None) { systemError(0, langq.lastError().databaseText(), __FILE__, __LINE__); } qApp->processEvents(); QString key; // TODO: Add code to check a few locations - Hopefully done QString keypath; QString keyname; QString keytogether; keytogether = app.applicationDirPath() + "/OpenMFG.key"; #ifdef Q_WS_WIN keypath = _metrics->value("CCWinEncKey"); #elif defined Q_WS_MACX keypath = _metrics->value("CCMacEncKey"); #elif defined Q_WS_X11 keypath = _metrics->value("CCLinEncKey"); #endif if (keypath.isEmpty()) keypath = app.applicationDirPath(); if (! keypath.endsWith(QDir::separator())) keypath += QDir::separator(); keyname = _metrics->value("CCEncKeyName"); if (keyname.isEmpty()) keyname = "OpenMFG.key"; keytogether = keypath + keyname; // qDebug("keytogether: %s", keytogether.toAscii().data()); QFile keyFile(keytogether); if(keyFile.exists()) { if(keyFile.open(QIODevice::ReadOnly)) { key = keyFile.readLine(1024); // strip off any newline characters key = key.stripWhiteSpace(); } } omfgThis = new GUIClient(databaseURL, username); omfgThis->_key = key; // qDebug("Encryption Key: %s", key.toAscii().data() ); if (key.length() > 0) { _splash->showMessage(QObject::tr("Loading Database Encryption Metrics"), SplashTextAlignment, SplashTextColor); qApp->processEvents(); _metricsenc = new Metricsenc(key); } initializePlugin(_preferences, _metrics, _privileges, omfgThis->workspace()); if (omfgThis->_singleWindow.isEmpty()) { omfgThis->show(); app.setMainWidget(omfgThis); } // keep this synchronized with GUIClient and user.ui.h else if (omfgThis->_singleWindow == "woTimeClock") { woTimeClock* newdlg = new woTimeClock(); ParameterList params; params.append("captive"); newdlg->set(params); newdlg->show(); app.setMainWidget(newdlg); } if(!omfgThis->singleCurrency()) { // Check for the gain/loss and discrep accounts q.prepare("SELECT COALESCE((SELECT TRUE" " FROM accnt, metric" " WHERE ((CAST(accnt_id AS text)=metric_value)" " AND (metric_name='CurrencyGainLossAccount'))), FALSE)" " AND COALESCE((SELECT TRUE" " FROM accnt, metric" " WHERE ((CAST(accnt_id AS text)=metric_value)" " AND (metric_name='GLSeriesDiscrepancyAccount'))), FALSE) AS result; "); q.exec(); if(q.first() && q.value("result").toBool() != true) QMessageBox::warning( omfgThis, QObject::tr("Additional Configuration Required"), QObject::tr("Your system is configured to use multiple Currencies, but the\n" "Currency Gain/Loss Account and/or the G/L Series Discrepancy Account\n" "does not appear to be configured correctly. You should define these\n" "Accounts in 'System | Configure Modules | Configure G/L...' before\n" "posting any transactions in the system.") ); } app.exec(); // Clean up delete _metrics; delete _preferences; delete _privileges; if (0 != _metricsenc) delete _metricsenc; #ifdef XQ_WS_WIN WSACleanup(); #endif return 0; }
void Database::indexCreate(IndexDefinition &indexDef) { if(indexDef.getColumnCount() < 1 || indexDef.getColumnCount() >= MAXKEYFIELDCOUNT) { /* must be < MAXKEYFIELDCOUNT because there has to be DbAddr at the end */ throwSqlError(SQL_KEY_TOO_BIG,_T("Invalid columncount (=%d)"),indexDef.getColumnCount()); } if(indexDef.getIndexType() != INDEXTYPE_PRIMARY && indexDef.getIndexType() != INDEXTYPE_UNIQUE && indexDef.getIndexType() != INDEXTYPE_NON_UNIQUE) { throwSqlError(SQL_INVALID_INDEXTYPE,_T("Invalid indextype (=%d)"),indexDef.getIndexType()); } if(indexDef.m_fileName.length() == 0) { indexDef.m_fileName = getNewFileName(_T("KEY")); } if(indexDef.m_indexName.length() == 0) { if(indexDef.getIndexType() == INDEXTYPE_PRIMARY) { indexDef.m_indexName = indexDef.m_tableName; } else { throwSqlError(SQL_INVALID_INDEXNAME,_T("Invalid indexname:<%s>"),indexDef.m_indexName.cstr()); } } if(DbFile::exist(indexDef.m_fileName)) { throwSqlError(SQL_FILE_ALREADY_EXIST,_T("File <%s> already exist"),indexDef.m_fileName.cstr()); } indexDef.m_tableName = toUpperCase(indexDef.m_tableName); indexDef.m_indexName = toUpperCase(indexDef.m_indexName); indexDef.m_fileName = toUpperCase(indexDef.m_fileName); const TableDefinition &tableDef = getTableDefinition(indexDef.m_tableName); if(tableDef.getTableType() != TABLETYPE_USER) { throwSqlError(SQL_INVALID_TABLETYPE,_T("Invalid tabletype (=%c)"),tableDef.getTableType()); } /* check that the indexname is not already used */ KeyFile indexfile2(*this,SYSTEM_INDEXKEY2_FNAME, DBFMODE_READWRITE); KeyFileDefinition keydef2(indexfile2); KeyType key2; keydef2.put(key2,0,indexDef.m_indexName ); if(indexfile2.searchMin(RELOP_EQ, key2, 1)) { throwSqlError(SQL_INDEX_ALREADY_EXIST,_T("Index <%s> already exist"),indexDef.m_indexName.cstr()); } if(!inTMF()) { throwSqlError(SQL_NO_TRANSACTION,_T("indexCreate:No active tmf")); } KeyFileDefinition keydef = tableDef.getKeyFileDefinition(indexDef); KeyFile::create(indexDef.m_fileName, keydef); try { KeyFile keyFile( indexDef.m_fileName, DBFMODE_READWRITE, false); DataFile datafile(tableDef.getFileName(), DBFMODE_READONLY , false); const TableInfo &tableInfo = getTableInfo(tableDef.getTableName()); /* TODO Lock datafile to avoid new records to be inserted */ if(indexDef.getIndexType() != INDEXTYPE_PRIMARY) { dataFileScan(indexDef.m_tableName, KeyGenerator(*this, keyFile, indexDef, tableInfo, keydef)); } sysTabIndexInsert(indexDef); /* TODO Invalidate all binded program-packages; Unlock datafile */ } catch(sqlca) { DbFile::destroy(indexDef.m_fileName); throw; } removeFromCache(indexDef.m_tableName); }
void EncryptDecryptFile::encryptDecrypt(const QString &inputFileName, const QString &outputFileName, const QString &keyFileName) { QFile inputFile(inputFileName); QFile outputFile(outputFileName); QFile keyFile(keyFileName); QString errorString; bool anErrorOccurred = false; register int i = 0; if(!inputFile.open(QIODevice::ReadOnly)) { errorString.append(tr("Could not open \"%1\" for reading.\n").arg(inputFileName)); anErrorOccurred = true; } else errorString.append(tr("Could successfully open \"%1\" for reading.\n").arg(inputFileName)); if(!outputFile.open(QIODevice::WriteOnly)) { errorString.append(tr("Could not open \"%1\" for writing.\n").arg(outputFileName)); anErrorOccurred = true; } else errorString.append(tr("Could successfully open \"%1\" for writing.\n").arg(outputFileName)); if(!keyFile.open((QIODevice::ReadOnly))) { errorString.append(tr("Could not open \"%1\" for reading.\n").arg(keyFileName)); anErrorOccurred = true; } else errorString.append(tr("Could successfully open \"%1\" for reading.\n").arg(keyFileName)); if(anErrorOccurred) { emit errorsOccurred(0, tr("Could not open someFiles!"), errorString); return; } char ioChar; char keyChar; emit fileSize(inputFile.size()); emit madeProgress(0); while(!inputFile.atEnd()) { if(!stopped) { inputFile.getChar(&ioChar); keyFile.getChar(&keyChar); encryptDecryptChar(ioChar, keyChar); outputFile.putChar(ioChar); if(keyFile.atEnd()) keyFile.reset(); if(i >= updateInterval) { emit madeProgress(inputFile.pos()); i = 0; } i++; } else { emit canceled(); break; } } inputFile.close(); outputFile.close(); keyFile.close(); if(!stopped) { emit madeProgress(inputFile.size()); emit successfullyFinished(); } stopped = false; }