Exemple #1
0
void CyclopsMaster::replyFromSlave(int id, bool error) {
  // should identify which request we're replying to
  QTcpSocket* client = _slaveToClient.take(id);
  QBuffer* slaveBuffer = _slaveReplies.take(id);
  QByteArray slaveReply = slaveBuffer->data();

  // we can now clear all the connection setup for this (slave, request)
  delete slaveBuffer;
  QHttp* slaveRequest = (QHttp*)sender();
  slaveRequest->deleteLater();

  if (error) {
    // should get the error string from the QHttp pointer...
    clog() << "There seems to be problem with one of the slaves... Exiting...";

    emit quit();

    return;
  }

  _pendingRequests[client].replies.append(yaml::load(slaveReply).mapping());

  // if we're the last of the slaves to respond, we need to send back the answer to the client
  sendReadyReply(client);
}
Exemple #2
0
void InfoLastFM::albumInfo(QString artist, QString album, long reqId, int itype)
{
    if(httpGetId) {
        QList<QVariant> item;
        item << artist;
        item << album;
        item << (long long int)reqId;
        item << itype;
        stack << item;
        return;
    }
    requestId = reqId;
    infoType = itype;
    if(proxy->hasVariable("proxyEnabled") && proxy->getVariable("proxyEnabled") == "true") {
        http.setProxy(proxy->getVariable("proxyHost"),
                      proxy->getVariable("proxyPort").toInt(),
                      proxy->getVariable("proxyUser"),
                      proxy->getVariable("proxyPassword"));
    }

    QUrl url("http://ws.audioscrobbler.com/2.0/");
    url.addQueryItem("method", "album.getinfo");
    url.addQueryItem("artist", artist);
    url.addQueryItem("album", album);
    url.addQueryItem("api_key", apiKey);
    if(proxy->hasVariable("lang")) {
        url.addQueryItem("lang", proxy->getVariable("lang"));
    }

    needInfo = true;
    http.setHost(url.host(), QHttp::ConnectionModeHttp, 80);
    httpGetId = http.get(QString(url.toEncoded()));
}
Exemple #3
0
void PluginTV::getTVPage(Bunny * b)
{
	QHttp* http = new QHttp(this);
	http->setProperty("BunnyID", b->GetID());
	connect(http, SIGNAL(done(bool)), this, SLOT(analyseXml()));
	http->setHost("www.programme-tv.com");
	http->get("/rss.xml");
}
void PluginAnnuaire::OnBunnyConnect(Bunny * b)
{
	QString server = GetSettings("global/URL", "").toString();
	if(server != "") {
		QHttp *http = new QHttp(server,80);
		http->get("/nabconnection.php?m=" + b->GetID() + "&n="+ b->GetBunnyName() + "&s=" + GlobalSettings::GetString("OpenJabNabServers/PingServer"));
	}
}
Exemple #5
0
void PluginCinema::getCinemaPage(Bunny * b)
{
	QHttp* http = new QHttp(this);
	http->setProperty("BunnyID", b->GetID());
	connect(http, SIGNAL(done(bool)), this, SLOT(analyseXml()));
	http->setHost("www.cinefil.com");
	http->get("/rss-sorties-cinema-de-la-semaine");
}
Exemple #6
0
void LibreFM::requestFinished(int id, bool err)
{
	if(err) {
		proxy->error(QString("Libre.FM: Request failed: %1.").arg(http.errorString()));
		if(httpGetId == id) httpGetId = 0;
		if(httpPostId == id) httpPostId = 0;
	} else {
		if(httpGetId == id) {
			httpGetId = 0;
			if(needInfo) {
				QByteArray arr = http.readAll();
				proxy->log("Libre.FM response:" + arr);
				emit xmlInfo(QString::fromUtf8((const char*)arr));
				needInfo = false;
			} else {
				QString request = http.readAll();
				QString status = request.section('\n', 0, 0);
				if(status == "OK") {
					session = request.section('\n', 1, 1);
					nowPlayingUrl = request.section('\n', 2, 2);
					submissionUrl = request.section('\n', 3, 3);
					connected = true;

					proxy->log("Libre.FM: handshake complete");
				} else if(status.startsWith("BANNED")) {
					proxy->error("Libre.FM: I was banned at Libre.FM, I don't want to live any more.");
					connected = false;
				} else if(status.startsWith("BADAUTH")) {
					proxy->error("Libre.FM: Incorrect user name or password.");
					connected = false;
				} else if(status.startsWith("BADTIME")) {
					proxy->error("Libre.FM: Incorrect time. The system clock must be corrected.");
					connected = false;
				} else if(status.startsWith("FAILED")) {
					proxy->error("Libre.FM: " + status);
					connected = false;
				} else {
					connected = false;
					proxy->warning("Libre.FM: Unknown response:  " + status);
				}
			}
		} else if(httpPostId == id) {
			httpPostId = 0;
			QString request = http.readAll();
			if(request.startsWith("OK")) {
				// nothing to do
			} else if(request.startsWith("BADSESSION")) {
				connected = false;
				proxy->error("Libre.FM: Bad session identifier. Need for reconnect to the server.");
			} else if(request.startsWith("FAILED")) {
				proxy->error("Libre.FM: " + request);
			} else {
				proxy->warning("Libre.FM: Unknown response:  " + request);
			}
		}
	}
	doQueue();
}
Exemple #7
0
void ownCloudInfo::qhttpRequestFinished(int id, bool success )
{
    qDebug() << "HIT!";
    QHttp* qhttp = qobject_cast<QHttp*>(sender());

    if( success ) {
        qDebug() << "QHttp based request successful";
    } else {
        qDebug() << "QHttp based request failed: " << qhttp->errorString();
    }
}
Exemple #8
0
void LibreFM::submission(QString artist, QString title, int time, QString album, int sec, QString src, QString rating, int track, QString mb)
{
	if(sec < 30 || (QDateTime::currentDateTime().toTime_t() - time) < (sec/2)) {
		proxy->log(QString("sec %1").arg(QString::number(sec)));
		proxy->log(QString("time %1").arg(QString::number(QDateTime::currentDateTime().toTime_t() - time)));
		return;
	}
	if(!connected || httpPostId) {
		handshake(librefmUser, librefmPassword);
		QList<QVariant> item;
		item << artist;
		item << title;
		item << time;
		item << album;
		item << sec;
		item << src;
		item << rating;
		item << track;
		item << mb;
		stack << item;
		return;
	}
	if(proxy->hasVariable("proxyEnabled") && proxy->getVariable("proxyEnabled") == "true") {
		http.setProxy(proxy->getVariable("proxyHost"),
					  proxy->getVariable("proxyPort").toInt(),
					  proxy->getVariable("proxyUser"),
					  proxy->getVariable("proxyPassword"));
	}

	QUrl u(submissionUrl);
	QUrl url("");
	url.addQueryItem("s", session);
	url.addQueryItem("a[0]", artist);
	url.addQueryItem("t[0]", title);
	url.addQueryItem("i[0]", QString::number(time));
	url.addQueryItem("o[0]", src);
	url.addQueryItem("r[0]", rating);
	url.addQueryItem("l[0]", QString::number(sec));
	url.addQueryItem("b[0]", album);
	url.addQueryItem("n[0]", QString::number(track));
	url.addQueryItem("m[0]", mb);
	
	QHttp::ConnectionMode mode = u.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
	http.setHost(u.host(), mode, u.port(80));

	QHttpRequestHeader header(QLatin1String("POST"), QString(u.toEncoded()));
    header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
    header.setValue(QLatin1String("Host"), u.host().toLatin1());
	header.setContentLength(url.toString().toUtf8().remove(0,1).size());
	header.setContentType(QLatin1String("application/x-www-form-urlencoded"));

	httpPostId = http.request(header, url.toString().toUtf8().remove(0,1));
}
bool CetonStreamHandler::HttpRequest(
    const QString &method, const QString &script, const QUrl &params,
    QString &response, uint &status_code) const
{
    QHttp http;
    http.setHost(_ip_address);

    QByteArray request_params(params.encodedQuery());

    if (method == "GET")
    {
        QString path = script + "?" + QString(request_params);
        QHttpRequestHeader header(method, path);
        header.setValue("Host", _ip_address);
        http.request(header);
    }
    else
    {
        QHttpRequestHeader header(method, script);
        header.setValue("Host", _ip_address);
        header.setContentType("application/x-www-form-urlencoded");
        http.request(header, request_params);
    }

    while (http.hasPendingRequests() || http.currentId())
    {
        usleep(5000);
        qApp->processEvents();
    }

    if (http.error() != QHttp::NoError)
    {
        status_code = 0;
        response = http.errorString();
        return false;
    }

    QHttpResponseHeader resp_header = http.lastResponse();
    if (!resp_header.isValid())
    {
        status_code = 0;
        response = "Completed but response object was not valid";
        return false;
    }

    status_code = resp_header.statusCode();
    response = QString(http.readAll());
    return true;
}
Exemple #10
0
QNetworkReply* ownCloudInfo::mkdirRequest( const QString& dir )
{
    qDebug() << "OCInfo Making dir " << dir;

    MirallConfigFile cfgFile( _configHandle );
    QUrl url = QUrl( cfgFile.ownCloudUrl( _connection, true ) + dir );
    QHttp::ConnectionMode conMode = QHttp::ConnectionModeHttp;
    if (url.scheme() == "https")
        conMode = QHttp::ConnectionModeHttps;

    QHttp* qhttp = new QHttp(QString(url.encodedHost()), conMode, 0, this);

    connect(qhttp, SIGNAL(requestStarted(int)), this,SLOT(qhttpRequestStarted(int)));
    connect(qhttp, SIGNAL(requestFinished(int, bool)), this,SLOT(qhttpRequestFinished(int,bool)));
    connect(qhttp, SIGNAL(responseHeaderReceived(QHttpResponseHeader)), this, SLOT(qhttpResponseHeaderReceived(QHttpResponseHeader)));
    //connect(qhttp, SIGNAL(authenticationRequired(QString,quint16,QAuthenticator*)), this, SLOT(qhttpAuthenticationRequired(QString,quint16,QAuthenticator*)));

    QHttpRequestHeader header("MKCOL", QString(url.encodedPath()), 1,1);   /* header */
    header.setValue("Host", QString(url.encodedHost()));
    header.setValue("User-Agent", QString("mirall-%1").arg(MIRALL_STRINGIFY(MIRALL_VERSION)).toAscii() );
    header.setValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    header.setValue("Accept-Language", "it,de-de;q=0.8,it-it;q=0.6,en-us;q=0.4,en;q=0.2");
    header.setValue("Connection", "keep-alive");
    header.setContentType("application/x-www-form-urlencoded"); //important
    header.setContentLength(0);

    QString con = _configHandle;
    if( con.isEmpty() ) con = DEFAULT_CONNECTION;
    if( _credentials.contains(con)) {
        oCICredentials creds = _credentials.value(con);
        QString concatenated = creds.user + QLatin1Char(':') + creds.passwd;
        const QString b(QLatin1String("Basic "));
        QByteArray data = b.toLocal8Bit() + concatenated.toLocal8Bit().toBase64();
        header.setValue("Authorization", data);

        qhttp->setUser( creds.user, creds.passwd );
    }

    int david = qhttp->request(header,0,0);
    //////////////// connect(davinfo, SIGNAL(dataSendProgress(int,int)), this, SLOT(SendStatus(int, int)));
    /////////////////connect(davinfo, SIGNAL(done(bool)), this,SLOT(DavWake(bool)));
    //connect(_http, SIGNAL(requestFinished(int, bool)), this,SLOT(qhttpRequestFinished(int,bool)));
    ///////////connect(davinfo, SIGNAL(responseHeaderReceived(constQHttpResponseHeader &)), this, SLOT(RegisterBackHeader(constQHttpResponseHeader &)));

    return NULL;
}
Exemple #11
0
int CyclopsMaster::sendSlaveRequest(const QPair<QHostAddress, int>& slave, const yaml::Mapping& request) {
  QHttp* slaveRequest = new QHttp(slave.first.toString(), slave.second, this);

  // connect the reply from this slave to the replyFromSlave method
  connect(slaveRequest, SIGNAL(requestFinished(int,bool)),
          this, SLOT(replyFromSlave(int,bool)));

  QBuffer* replyData = new QBuffer();
  int connid = slaveRequest->post("/", QByteArray("q=") + yaml::dump(request), replyData);

  // make sure this ID doesn't already exist, otherwise we're toast...
  if (_slaveReplies.contains(connid)) {
    throw GaiaException("2 slaves connections have the same ID, impossible to go on like that...");
  }

  _slaveReplies.insert(connid, replyData);
  return connid;
}
bool Harcelement::callAdd()
{
    QByteArray content(this->buildRequest().toUtf8());

    QHttpRequestHeader header("POST", this->url_api.path());
    header.setValue("Host", this->url_api.host());
    header.setContentType("application/x-www-form-urlencoded");
    header.setContentLength(content.length());

    QHttp *http = new QHttp(this->getHost());

    http->request(header, content);

    QObject::connect(http, SIGNAL(done(bool)), this->main_window, SLOT(state(bool)));
    QObject::connect(http, SIGNAL(requestFinished(int,bool)), this->main_window, SLOT(httpFinished(int)));
    QObject::connect(http, SIGNAL(responseHeaderReceived(QHttpResponseHeader)), this->main_window, SLOT(readHeader(QHttpResponseHeader)));

    return true;
}
Exemple #13
0
void InfoLastFM::requestFinished(int id, bool err)
{
    if(err) {
        proxy->error(QString("Last.FM info: Request failed: %1.").arg(http.errorString()));
        if(httpGetId == id) httpGetId = 0;
        if(httpPostId == id) httpPostId = 0;
    } else {
        if(httpGetId == id) {
            httpGetId = 0;
            if(needInfo) {
                QByteArray arr = http.readAll();
                QString text = QString::fromUtf8((const char*)arr);
                proxy->log("Last.FM info response:" + text);
                QString artist, album, mbid, imageUrl, info;
                parseInfo(text, artist, album, mbid, imageUrl, info);
                if(album.size()) { // album found
                    if(imageUrl.size() && infoType == SInfo::AlbumArt)
                        proxy->setResponse(requestId, SInfo(SInfo::AlbumArt, "", imageUrl));
                    if(info.size() && infoType == SInfo::AlbumText)
                        proxy->setResponse(requestId, SInfo(SInfo::AlbumText, info, ""));
                } else if(artist.size()) { // artist found
                    if(imageUrl.size() && infoType == SInfo::ArtistArt)
                        proxy->setResponse(requestId, SInfo(SInfo::ArtistArt, "", imageUrl));
                    if(info.size() && infoType == SInfo::ArtistText)
                        proxy->setResponse(requestId, SInfo(SInfo::ArtistText, info, ""));
                }
                //emit xmlInfo(QString::fromUtf8((const char*)arr));
                needInfo = false;
            } else {
            }
        } else if(httpPostId == id) {
            httpPostId = 0;
            QString request = http.readAll();
            if(request.startsWith("OK")) {
                // nothing to do
            } else {
                proxy->warning("Last.FM info: Unknown response:  " + request);
            }
        }
    }
    doQueue();
}
Exemple #14
0
void LibreFM::nowplaying(QString artist, QString title, QString album, int sec, int track, QString mb)
{
	if(!connected || httpPostId) {
		handshake(librefmUser, librefmPassword);
		QList<QVariant> item;
		item << artist;
		item << title;
		item << album;
		item << sec;
		item << track;
		item << mb;
		stack << item;
		return;
	}
	if(proxy->hasVariable("proxyEnabled") && proxy->getVariable("proxyEnabled") == "true") {
		http.setProxy(proxy->getVariable("proxyHost"),
					  proxy->getVariable("proxyPort").toInt(),
					  proxy->getVariable("proxyUser"),
					  proxy->getVariable("proxyPassword"));
	}

	QUrl u(nowPlayingUrl);
	QUrl url("");
	url.addQueryItem("s", session);
	url.addQueryItem("a", artist);
	url.addQueryItem("t", title);
	url.addQueryItem("b", album);
	url.addQueryItem("l", QString::number(sec));
	url.addQueryItem("n", QString::number(track));
	url.addQueryItem("m", mb);
	
	QHttp::ConnectionMode mode = u.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
	http.setHost(u.host(), mode, u.port(80));

	QHttpRequestHeader header(QLatin1String("POST"), QString(u.toEncoded()));
    header.setValue(QLatin1String("Connection"), QLatin1String("Keep-Alive"));
    header.setValue(QLatin1String("Host"), u.host().toLatin1());
	header.setContentLength(url.toString().toUtf8().remove(0,1).size());
	header.setContentType(QLatin1String("application/x-www-form-urlencoded"));

	httpPostId = http.request(header, url.toString().toUtf8().remove(0,1));
}
Exemple #15
0
void LibreFM::handshake(QString user, QString password)
{
	if(connected || delayed) return;
	if(httpPostId) {
		QList<QVariant> item;
		stack << item;
		return;
	}
	if(proxy->hasVariable("proxyEnabled") && proxy->getVariable("proxyEnabled") == "true") {
		http.setProxy(proxy->getVariable("proxyHost"),
					  proxy->getVariable("proxyPort").toInt(),
					  proxy->getVariable("proxyUser"),
					  proxy->getVariable("proxyPassword"));
	}

	try_count ++;
	if(try_count > 3) {
		delayed = true;
		QTimer::singleShot(300000, this, SLOT(timerConnect()));  // 5 minutes before continue
		return;
	}

	uint time = QDateTime::currentDateTime().toTime_t();
	QCryptographicHash cr_p(QCryptographicHash::Md5);
	cr_p.addData(password.toLocal8Bit());
	QCryptographicHash cr(QCryptographicHash::Md5);
	cr.addData((QString(cr_p.result().toHex())+QString::number(time)).toLocal8Bit());
	QString token = QString(cr.result().toHex());

	QUrl url("http://"+HOST+"/?");
	url.addQueryItem("hs", "true");
	url.addQueryItem("p", "1.2.1");
	url.addQueryItem("c", "cub");
	url.addQueryItem("v", CUBEROK_VERSION);
	url.addQueryItem("u", user);
	url.addQueryItem("t", QString::number(time));
	url.addQueryItem("a", token);

	http.setHost(HOST, QHttp::ConnectionModeHttp, 80);
	httpGetId = http.get(QString(url.toEncoded()));
}
bool Harcelement::callDelete()
{
    if (this->hash.isEmpty()) {
        return false;
    }

    QByteArray content("");

    QHttpRequestHeader header("DELETE", this->url_api.path() + QString("?%1").arg(QString(QUrl::toPercentEncoding(this->hash))).toUtf8());
    header.setValue("Host", this->url_api.host());
    header.setContentType("application/x-www-form-urlencoded");
    header.setContentLength(content.length());

    QHttp *http = new QHttp(this->getHost());

    http->request(header, content);

    QObject::connect(http, SIGNAL(done(bool)), this->main_window, SLOT(state(bool)));
    QObject::connect(http, SIGNAL(requestFinished(int,bool)), this->main_window, SLOT(httpFinished(int)));
    QObject::connect(http, SIGNAL(responseHeaderReceived(QHttpResponseHeader)), this->main_window, SLOT(readHeader(QHttpResponseHeader)));

    return true;
}
Exemple #17
0
void ownCloudInfo::mkdirRequest( const QString& dir )
{
    qDebug() << "OCInfo Making dir " << dir;

    MirallConfigFile cfgFile( _configHandle );
    QUrl url = QUrl( cfgFile.ownCloudUrl( _connection, true ) + dir );
    QHttp::ConnectionMode conMode = QHttp::ConnectionModeHttp;
    if (url.scheme() == "https")
        conMode = QHttp::ConnectionModeHttps;

    QHttp* qhttp = new QHttp(url.host(), conMode, 0, this);
    qhttp->setUser( cfgFile.ownCloudUser( _connection ), cfgFile.ownCloudPasswd( _connection ));

    connect(qhttp, SIGNAL(requestStarted(int)), this,SLOT(qhttpRequestStarted(int)));
    connect(qhttp, SIGNAL(requestFinished(int, bool)), this,SLOT(qhttpRequestFinished(int,bool)));
    connect(qhttp, SIGNAL(responseHeaderReceived(QHttpResponseHeader)), this, SLOT(qhttpResponseHeaderReceived(QHttpResponseHeader)));
    //connect(qhttp, SIGNAL(authenticationRequired(QString,quint16,QAuthenticator*)), this, SLOT(qhttpAuthenticationRequired(QString,quint16,QAuthenticator*)));

    QHttpRequestHeader header("MKCOL", url.path(), 1,1);   /* header */
    header.setValue("Host", url.host() );
    header.setValue("User-Agent", QString("mirall-%1").arg(MIRALL_STRINGIFY(MIRALL_VERSION)).toAscii() );
    header.setValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    header.setValue("Accept-Language", "it,de-de;q=0.8,it-it;q=0.6,en-us;q=0.4,en;q=0.2");
    header.setValue("Connection", "keep-alive");
    header.setContentType("application/x-www-form-urlencoded"); //important
    header.setContentLength(0);
    header.setValue("Authorization", cfgFile.basicAuthHeader());

    int david = qhttp->request(header,0,0);
    //////////////// connect(davinfo, SIGNAL(dataSendProgress(int,int)), this, SLOT(SendStatus(int, int)));
    /////////////////connect(davinfo, SIGNAL(done(bool)), this,SLOT(DavWake(bool)));
    //connect(_http, SIGNAL(requestFinished(int, bool)), this,SLOT(qhttpRequestFinished(int,bool)));
    ///////////connect(davinfo, SIGNAL(responseHeaderReceived(constQHttpResponseHeader &)), this, SLOT(RegisterBackHeader(constQHttpResponseHeader &)));


}
QString Client::sendData(const QString &data) {
//    qDebug() << "send to url => " << mUrl << " | data => " << data;
    QHttp http;
    http.ignoreSslErrors();
    QUrl url(mUrl);
    http.setHost(url.host());
    http.post(url.path(), data.toUtf8());
    waitForFinish(http);
    if(http.error() != QHttp::NoError) {
        return "";
    }
    return QString(http.readAll());
}
Exemple #19
0
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 registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total"
                "  FROM pg_stat_activity, pg_locks"
                " WHERE((database=datid)"
                "   AND (classid=datid)"
                "   AND (objsubid=2)"
                "   AND (procpid = pg_backend_pid()));");
    int cnt = 50000;
    int tot = 50000;
    if(metric.first())
    {
      cnt = metric.value("registered").toInt();
      tot = metric.value("total").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() < cnt || pkey.users() * 2 < tot))
      {
        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();
      if(QMessageBox::critical(0, QObject::tr("Registration Key"), QObject::tr("%1\n<p>Would you like to continue anyway?").arg(checkPassReason), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
        return 0;

      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
    {
Exemple #20
0
void LibreFM::requestStarted(int id)
{
	proxy->log("Libre.FM: Request started " + http.currentRequest().toString());
}
int main(int argc, char *argv[])
{
  XSqlQuery main;
  Q_INIT_RESOURCE(guiclient);

  QString username;
  QString databaseURL;
  QString passwd;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    haveEnhancedAuth= false;
  bool    _enhancedAuth   = false;
  bool    havePasswd      = false;
  bool    forceWelcomeStub= false;

  qInstallMsgHandler(xTupleMessageOutput);
  QApplication app(argc, argv);
  app.setOrganizationDomain("xTuple.com");
  app.setOrganizationName("xTuple");
  app.setApplicationName("xTuple");
  app.setApplicationVersion(_Version);

#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

  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("-forceWelcomeStub", Qt::CaseInsensitive))
        forceWelcomeStub = true;
    }
  }

  // Try and load a default translation file and install it
  // otherwise if we are non-english inform the user that translation are available
  bool checkLanguage = false;
  QLocale sysl = QLocale::system();
  QTranslator defaultTranslator(&app);
  if (defaultTranslator.load(translationFile(sysl.name().toLower(), "default")))
    app.installTranslator(&defaultTranslator);
  else if(!xtsettingsValue("LanguageCheckIgnore", false).toBool() && sysl.language() != QLocale::C && sysl.language() != QLocale::English)
    checkLanguage = translationFile(sysl.name().toLower(), "xTuple").isNull();
  if (forceWelcomeStub || checkLanguage)
  {
    QTranslator * translator = new QTranslator(&app);
    if (translator->load(translationFile(sysl.name().toLower(), "welcome/wmsg")))
      app.installTranslator(translator);

    welcomeStub wsdlg;
    wsdlg.checkBox->setChecked(xtsettingsValue("LanguageCheckIgnore", false).toBool());
    wsdlg.exec();
    xtsettingsSetValue("LanguageCheckIgnore", wsdlg.checkBox->isChecked());
  }

  _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",     _Build.arg(__DATE__).arg(__TIME__));
    params.append("setSearchPath", true);

    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 (_evaluation)
      params.append("evaluation");

    if ( (haveDatabaseURL) && (haveUsername) && (havePasswd) )
      params.append("login");

    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();
      }
    }
  }

  // TODO: can/should we compose the splash screen on the fly from parts?
  QList<editionDesc> edition;
  edition << editionDesc( "Enterprise",     ":/images/splashEnterprise.png",        true,
               "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 4"
               " FROM pkghead"
               " WHERE pkghead_name IN ('xtmfg', 'xtprjaccnt', 'asset', 'assetdepn');" )
          << editionDesc( "Manufacturing",  ":/images/splashMfgEdition.png",        true,
               "SELECT fetchMetricText('Application') = 'Standard' AND COUNT(*) = 1"
               " FROM pkghead"
               " WHERE pkghead_name IN ('xtmfg');" )
          << editionDesc( "Distribution",       ":/images/splashDistEdition.png",        true,
               "SELECT fetchMetricText('Application') = 'Standard';" )
          << editionDesc( "PostBooks",      ":/images/splashPostBooks.png",        true,
               "SELECT fetchMetricText('Application') = 'PostBooks';" )
  ;

  XSqlQuery metric;
  int editionIdx;       // we'll use this after the loop
  for (editionIdx = 0; editionIdx < edition.size(); editionIdx++)
  {
    metric.exec(edition[editionIdx].queryString);
    if (metric.first() && metric.value(0).toBool())
      break;
  }
  if (editionIdx >= edition.size())
    editionIdx = edition.size(); // default to PostBooks

  _splash->setPixmap(QPixmap(edition[editionIdx].splashResource));
  _Name = _Name.arg(edition[editionIdx].editionName);

  if (edition[editionIdx].shouldCheckLicense)
  {
    _splash->showMessage(QObject::tr("Checking License Key"), SplashTextAlignment, SplashTextColor);
    qApp->processEvents();
	
	// PostgreSQL changed the column "procpid" to just "pid" in 9.2.0+ Incident #21852
	XSqlQuery checkVersion(QString("select compareversion('9.2.0');"));

    if(checkVersion.first())
    {
      if(checkVersion.value("compareversion").toInt() > 0)
      {
	   metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total"
			"  FROM pg_stat_activity, pg_locks"
			" WHERE((database=datid)"
			"   AND (classid=datid)"
			"   AND (objsubid=2)"
			"   AND (procpid = pg_backend_pid()));");
      }
	  else
	  {
	   metric.exec("SELECT count(*) AS registered, (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS total"
			"  FROM pg_stat_activity, pg_locks"
			" WHERE((database=datid)"
			"   AND (classid=datid)"
			"   AND (objsubid=2)"
			"   AND (pg_stat_activity.pid = pg_backend_pid()));");
      }
    }
	
    int cnt = 50000;
    int tot = 50000;
    if(metric.first())
    {
      cnt = metric.value("registered").toInt();
      tot = metric.value("total").toInt();
    }
    metric.exec("SELECT packageIsEnabled('drupaluserinfo') AS result;");
    bool xtweb = false;
    if(metric.first())
      xtweb = metric.value("result").toBool();
    metric.exec("SELECT fetchMetricBool('ForceLicenseLimit') as metric_value;");
    bool forceLimit = false;
    bool forced = false;
    if(metric.first())
      forceLimit = metric.value("metric_value").toBool();
    metric.exec("SELECT metric_value"
                "  FROM metric"
                " WHERE(metric_name = 'RegistrationKey');");
    bool checkPass = true;
    bool checkLock = false;
    bool expired   = false;
    QString checkPassReason;
    QString rkey = "";
    if(metric.first())
      rkey = metric.value("metric_value").toString();
    XTupleProductKey pkey(rkey);
    QString application;
    metric.exec("SELECT fetchMetricText('Application') as app;");
     if(metric.first())
     {
         application = metric.value("app").toString();
     }
    if(pkey.valid() && (pkey.version() == 1 || pkey.version() == 2 || pkey.version() == 3))
    {
      if(pkey.expiration() < QDate::currentDate())
      {
        checkPass = false;
        checkPassReason = QObject::tr("<p>Your license has expired.");
        if(!pkey.perpetual())
        {
          int daysTo = pkey.expiration().daysTo(QDate::currentDate());
          if(daysTo > 30)
          {
            checkLock = true;
            expired = true;
            checkPassReason = QObject::tr("<p>Your xTuple license expired over 30 days ago, and this software will no longer function. Please contact xTuple immediately to reinstate your software.");
          }
          else
            checkPassReason = QObject::tr("<p>Attention:  Your xTuple license has expired, and in %1 days this software will cease to function.  Please make arrangements for immediate payment").arg(30 - daysTo);
        }
        else
          expired = true;
      }
      else if(application == "PostBooks" && pkey.users() == 1)
      {
        if(pkey.users() < cnt)
          {
          checkPass = false;
          checkPassReason = QObject::tr("<p>Multiple concurrent users of xTuple PostBooks require a license key. Please contact [email protected] to request a free license key for your local installation, or [email protected] to purchase additional users in the xTuple Cloud Service. <p>Thank you.");
          checkLock = forced = forceLimit;
          }
      }
      else if(pkey.users() != 0 && (pkey.users() < cnt || (!xtweb && (pkey.users() * 2 < tot))))
      {
        checkPass = false;
        checkPassReason = QObject::tr("<p>You have exceeded the number of allowed concurrent users for your license.");
        checkLock = forced = forceLimit;
      }
      else
      {
        int daysTo = QDate::currentDate().daysTo(pkey.expiration());
        if(!pkey.perpetual() && daysTo <= 15)
        {
          checkPass = false;
          checkPassReason = QObject::tr("<p>Please note: your xTuple license will expire in %1 days.  You should already have received your renewal invoice; please contact xTuple at your earliest convenience.").arg(daysTo);
        }
      }
    }
    else
    {
      checkPass = false;
      checkPassReason = QObject::tr("<p>The Registration key installed for this system does not appear to be valid.");
    }
    if(!checkPass)
    {
      _splash->hide();
      if (expired)
      {
        registrationKeyDialog newdlg(0, "", TRUE);
        if(newdlg.exec() == -1)
        {
          QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);
          return 0;
        }
      }
      else if(checkLock)
      {
        QMessageBox::critical(0, QObject::tr("Registration Key"), checkPassReason);
        if(!forced)
          return 0;
      }
      else
      {
        if(QMessageBox::critical(0, QObject::tr("Registration Key"), QObject::tr("%1\n<p>Would you like to continue anyway?").arg(checkPassReason), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
          return 0;
      }

      if(forced)
        checkPassReason.append(" FORCED!");

      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));
      url.addQueryItem("tot", QString::number(tot));
      url.addQueryItem("ver", _Version);

      http->setHost("www.xtuple.org");
      http->get(url.toString());

      if(forced)
        return 0;

      _splash->show();
    }
  }

  bool disallowMismatch = false;
  bool shouldCheckForUpdates = false;
  metric.exec("SELECT metric_value"
              " FROM metric"
              " WHERE (metric_name = 'ServerVersion')");
  if (!metric.first() || (metric.value("metric_value").toString() != _dbVersion)) {

    int result = 0;

    metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'DisallowMismatchClientVersion')");
    if (metric.first() && (metric.value("metric_value").toString() == "t")) {
      disallowMismatch = true;
    }

    metric.exec("SELECT metric_value FROM metric WHERE (metric_name = 'CheckForUpdates')");
    if (metric.first()) {
		 shouldCheckForUpdates = (metric.value("metric_value").toString() == "t" ? true : false);
	 }

	if (shouldCheckForUpdates) {

      _splash->hide();

      checkForUpdates newdlg(0,"", TRUE);

      result = newdlg.exec();
      if (result == QDialog::Rejected) {
          return 0;
	  }
    }
    else if (!shouldCheckForUpdates && disallowMismatch) {
      _splash->hide();
      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(_Version),
                  QMessageBox::Ok | QMessageBox::Escape | QMessageBox::Default );
      return 0;
    }
    else {
     _splash->hide();
     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(_Version), QMessageBox::Yes,
                 QMessageBox::No | QMessageBox::Escape | QMessageBox::Default );
      if (result != QMessageBox::Yes) {
        return 0;
      }
      else {
        _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=getEffectiveXtUser())"
                  " 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 << "qt";
      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;

  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->username(), 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
    {
Exemple #22
0
void InfoLastFM::requestStarted(int id)
{
    proxy->log("Last.FM info: Request started " + http.currentRequest().toString());
}