Ejemplo n.º 1
0
Wt::Dbo::ptr<User> Session::user(const Wt::Auth::User& authUser)
{
  Wt::Dbo::ptr<AuthInfo> authInfo = users_->find(authUser);
  Wt::Dbo::ptr<User> user = authInfo->user();

  if (!user) {
    user = addNew<User>();
    authInfo.modify()->setUser(user);
  }
  return user;
}
Ejemplo n.º 2
0
 /// Returns a dbo::ptr to the currently logged in user *
 dbo::ptr<User> user() {
     if (_userCache) {
         if (time(NULL) - _cacheTime > _userSessionStore.getTimeout())
             _userCache.reset();
         else
             return _userCache;
     }
     // Check the session thing live .. this will possibly slow things down by locking if another thread is writing
     // but on the plus side it means if one thread los out .. all threads log out
     string cookie = getCookie();
     if (!cookie.empty()) {
         unsigned int userId;
         try {
             userId = _userSessionStore.userId(cookie);
         } catch (invalid_argument e) {
             // If they have an old session cookie, but they're not logged in now .. delete the old cookie
             WApplication::instance()->setCookie(_cookieName, cookie, 0, "", "/", true);
             cookieCache = "";
             return dbo::ptr<User>(); // Empty pointer
         }
         touchSession();
         // Cache and return the result
         dbo::Transaction t(_dbSession);
         _userCache = _dbSession.find<User>().where("id = ?").bind((int)userId);
         _cacheTime = time(NULL); // (now)
         t.commit();
         return _userCache;
     } else {
         return dbo::ptr<User>(); // Empty pointer
     }
 }
Ejemplo n.º 3
0
void User::rate(Wt::Dbo::ptr< User > userPtr, const Media& media, int rating, Wt::Dbo::Transaction& transaction) {
  MediaRatingPtr previousRating = transaction.session().find<MediaRating>()
    .where("user_id = ?").bind(userPtr.id())
    .where("media_id = ?").bind(media.uid());
  if(!previousRating) {
    transaction.session().add(new MediaRating{userPtr, media.uid(), rating});
    return;
  }
  previousRating.modify()->setRating(rating);
}
Ejemplo n.º 4
0
ChamadaForm::ChamadaForm(Wt::Dbo::Session& dbSession, Wt::Dbo::ptr<SiconfModel::Disciplina> disciplina, Wt::Dbo::ptr<SiconfModel::Aula> aula) :
																_dbSession(dbSession),
																_disciplina(disciplina),
																_aula(aula){
	try{
		_initialize();
		Wt::Dbo::Transaction transaction(_dbSession	);
		for(auto i : sortList){
			Wt::Dbo::ptr<SiconfModel::Frequencia> frequencia = _dbSession.find<SiconfModel::Frequencia>("where frequencias_aula_id = ? and frequencias_aluno_id = ?").bind(_aula.id()).bind(i.second.id());
			if(frequencia){
				i.first->setChecked(frequencia->presenca());
			}else{
				std::cout << "ChamadaForm::ChamadaForm() ................ Frequencia nao encontrada!" << std::endl;
			}
		}
	}catch(std::exception& e){
		new SiconfUtils::Popup("ChamadaForm::ChamadaForm()", e.what());
	}
}
Ejemplo n.º 5
0
  virtual void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) {
    int n;
    if (const std::string *queries = request.getParameter("queries")) {
      n = atoi(queries->c_str());
      if (n < 1)
        n = 1;
      else if (n > 500)
        n = 500;
    } else {
      n = 1;
    }

    response.setMimeType("application/json");
    response.addHeader("Server", "Wt");

    DbStruct* db = dbStruct_.get();
    if (!db) {
      db = new DbStruct();
      dbStruct_.reset(db);
    }

    std::vector<Wt::Dbo::ptr<World> > results;

    for (int i = 0; i < n; ++i) {
      bool success = false;
      while (!success) {
        try {
          Wt::Dbo::Transaction transaction(db->session);
          Wt::Dbo::ptr<World> world = db->session.load<World>(db->rand());
          world.modify()->randomNumber = db->rand();
          transaction.commit();
          results.push_back(world);
          success = true;
        } catch (Wt::Dbo::Exception& e) {
          // Retry
        }
      }
    }

    Wt::Dbo::JsonSerializer writer(response.out());
    writer.serialize(results);
  }
Ejemplo n.º 6
0
void ChamadaForm::_save(){
	Wt::Dbo::Transaction transaction(_dbSession);

	if(_aula){
		std::cout << "Aula set: updating..." << std::endl;
		for(auto i : sortList){
			Wt::Dbo::ptr<SiconfModel::Frequencia> frequencia = _dbSession.find<SiconfModel::Frequencia>("where frequencias_aula_id = ? and frequencias_aluno_id = ?").bind(_aula.id()).bind(i.second.id());
			if(frequencia){
				frequencia.modify()->definirPresenca(i.first->isChecked());
			}else{
				std::cout << "ChamadaForm::Save() ........... Frequencia not found" << std::endl;
			}
		}

	}else{
		std::cout << "Aula not set: creating..." << std::endl;
		_aula = _dbSession.add(new SiconfModel::Aula(_disciplina));
		for(auto i : sortList){
			_dbSession.add(new SiconfModel::Frequencia(_aula, i.second, i.first->isChecked()));
		}
	}

	transaction.commit();
}
Ejemplo n.º 7
0
 SessionHandle(WObject* parent, dbo::Session& dbSession, const string& cookieName) :
     BaseSessionHandle(parent, cookieName), _userSessionStore(SessionStore::getInstance()), _dbSession(dbSession), _cacheTime(time(NULL))
 {
     // Check if we're already logged in
     const string& cookie = getCookie();
     if (!cookie.empty()) {
         int userId;
         try {
             userId = _userSessionStore.userId(getCookie(), true); // Touch the session as new app/view is openning for it
         } catch (invalid_argument e) {
             // Nobody's logged in right now
             _userCache.reset();
             return;
         }
         // Remember our user object
         dbo::Transaction transaction(_dbSession);
         _userCache = _dbSession.find<User>().where("id = ?").bind((int)userId);
         transaction.commit();
     }
 }
Ejemplo n.º 8
0
void LoginPage::_setPage(Wt::Dbo::ptr<SiconfModel::Usuario> usuario){
	Wt::Dbo::Transaction transaction(_dbSession);

	typedef SiconfModel::Usuario SU;
	SU::TipoUsuario tipo = usuario->tipoUsuario();

	if(tipo == SU::_Professor){

		Wt::Dbo::ptr<SiconfModel::Professor> professor = _login->getProfessor(usuario);
		if(professor){
			_navigator->addPage(new HomeProfessor(_dbSession, professor));
			_navigator->setInternalPath("/home_professor/");
		}else{
			new SiconfUtils::Popup("Erro ao recuperar dados do banco", "Atencao");
		}


	}else if(tipo == SU::_Aluno){

		Wt::Dbo::ptr<SiconfModel::Aluno> aluno = _login->getAluno(usuario);
		if(aluno){
				_navigator->addPage(new HomeAluno(_dbSession, aluno));
				_navigator->setInternalPath("/home_aluno/");

		}else{
			new SiconfUtils::Popup("Erro ao recuperar dados do banco, aluno nao encontrado", "Atencao");
		}

	}else if(tipo == SU::_Administrador){

		new SiconfUtils::Popup("Bem vindo, administrador", "Atencao");

	}else{
		new SiconfUtils::Popup("Erro ao recuperar dados do banco, tipo usuario = " + tipo, "Atencao");
	}
}
Ejemplo n.º 9
0
/* ****************************************************************************
 * handleRequest
 */
void BlogRSSFeed::handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response)
{
    std::string myURL = request.headerValue("Host").c_str();
    //QString domainName = myURL.c_str();
    std::string domainName = myURL.c_str();
    //unsigned pos = domainName.indexOf(":");
    unsigned pos = domainName.find(":");
    if (pos > 0)
    {
        domainName = domainName.substr(0, pos);
    }
    if (!SetSqlConnectionPool(domainName))
    {
        Wt::log("error") << "(BlogRSSFeed::handleRequest: SetSqlConnectionPool failed for domain: " << domainName << ")";
        return;
    }
    Wt::log("notice") << "(BlogRSSFeed::handleRequest: domainName " << domainName << ")";
    //if(myConnectionPool.find(domainName.toStdString()) == myConnectionPool.end())
    if(myConnectionPool.find(domainName) == myConnectionPool.end())
    {
        // element not found;
        //Wt::log("notice") << "(BlogRSSFeed::handleRequest: myConnectionPool element not found " << domainName.toStdString() << ")";
        Wt::log("notice") << "(BlogRSSFeed::handleRequest: myConnectionPool element not found " << domainName << ")";
        //request.serverName().c_str() returned saber
        return;
    }
    Wt::Dbo::SqlConnectionPool *thePool;
    try
    {
        //thePool = boost::any_cast<Wt::Dbo::SqlConnectionPool *>(myConnectionPool[domainName.toStdString()]);
        thePool = boost::any_cast<Wt::Dbo::SqlConnectionPool *>(myConnectionPool[domainName]);
    }
    catch (...)
    {
        //Wt::log("notice") << "(BlogRSSFeed::handleRequest: failed connection cast " << domainName.toStdString() << ")";
        Wt::log("notice") << "(BlogRSSFeed::handleRequest: failed connection cast " << domainName << ")";
        //request.serverName().c_str() returned saber
        return;
    }
    BlogSession session(*thePool);

    response.setMimeType("application/rss+xml");
    //

    /*
Just to be clear about these instructions:

Take application lock (Wt::WApplication::UpdateLock) from handleRequest()
if you change WApplication (by changing message resource bundle)

void BlogRSSFeed::handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response)
{
    // I see no useful variables to pull
}

/mnt/storage/jflesher/FileShare/Code/0-WittyWizard/WittyWizard/BlogRSSFeed.cpp:135: error: 'WApplication' has not been declared
     WApplication::UpdateLock lock(app);
     ^

Hello!

Use WApplication::instance() to get a pointer to current WApplication.
No need to construct application object in handleRequest().
The only place where application is created is application creating function (ApplicationCreator),
which is passed to WRun() or to WServer::addEntryPoint().
So, only Wt internals should create new instances of application, not your code!

WApplication::instance() can be used from event handling functions (e.g., slots connected to Wt signals) and handleRequest()
if WResource is bind to an application.
You can use assert(wApp) to make sure it is not 0.
It can be 0 no application instance is active currently (for example, in server-global WResource or in main() function).

Macro wApp is equal to WApplication::instance().

Derive from WApplication, it works.
For example, you derived MyApplication from WApplication.
To convert pointer to WApplication to pointer to MyApplication,
use boost polymorphic cast:

#include "boost/cast.cpp"

WApplication* app = WApplication::instance(); // to just wApp
MyApplication* myapp = boost::polymorphic_downcast(app);

boost::polymorphic_downcast uses C++ built-in operators static_cast or dynamic_cast.
Which one of them is used, depends on build configuration. Release build uses static_cast,
Debug build uses dynamic_cast and checks result is not 0.

If you use boost::polymorphic_downcast many times, it makes sense for you to create a macro for it:
#define DOWNCAST boost::polymorphic_downcast

Summary: to get WApplication*, use wApp, to get WEnvironment, use wApp->environment(),
to get pointer to your derived application class, use boost::polymorphic_downcast.

wApp is 0 in static WResource.


You seem to use global WResource (added with WServer::addResource()).
In this case, wApp is 0, so you can not use WApplication.
To translate with WString::tr,
you can use WServer::setLocalizedStrings().
For this, you need Wt::WMessageResourceBundle instance.

In main(), create new WMessageResourceBundle, call use() to add your translated XML files,
then pass it to WServer::setLocalizedStrings().

BTW, this solution does not respect user's locale, all strings are translated to server's locale.
I created feature request for this http://redmine.webtoolkit.eu/issues/3381

You can workaround this by creation several global WMessageResourceBundle instances (one per language) and
selection one of them depending on client's language manually.
Then you can use WMessageResourceBundle::resolveKey to translate.
To get clients locale, get HTTP header "Accept-Language" using Request::headerValue().
(Request instance is passed to handleRequest().) Parsing it is a complicated task.
For example, "en-US,en;q=0.8,ru;q=0.6" means Russian.

*/
    /*
    //Wt::WApplication *app = Wt::WApplication::instance();

    */
    /*
     * WMessageResourceBundle& WApplication::builtinLocalizedStrings()
     */
    //Wt::WApplication* app = Wt::WApplication::instance();
    //const Wt::WEnvironment& env = new Wt::WEnvironment(); // is protected error
/*
    const Wt::WEnvironment& env = Wt::WApplication::instance()->environment(); // segment fault WEnvironment& WApplication::env()
    Wt::WApplication *app = new Wt::WApplication(env);


    Wt::WApplication::UpdateLock lock(app);  // Wt::WApplication::instance() ~ segment fault in UpdateLock: impl_ = new UpdateLockImpl(app);
    if (lock)    {
        // exclusive access to app state
        app->messageResourceBundle().use(myDomainPath[domainName] + "app_root/ww-home", false);
    }
*/

    //
    std::string url          = Wt::WString::tr("rss-url").toUTF8();
    std::string title_       = Wt::WString::tr("rss-title").toUTF8();
    std::string description_ = Wt::WString::tr("rss-description").toUTF8();
    //
    Wt::log("notice") << "(BlogRSSFeed::handleRequest:  url, title_, description_ = " << url << ", " <<  title_ << ", " <<  description_ << ")";
    //
    if (url.empty())
    {
        //url = request.urlScheme() + "://" + domainName.toStdString();
        url = request.urlScheme() + "://" + domainName;
        if (!request.serverPort().empty() && request.serverPort() != "80")
        {
            url += ":" + request.serverPort();
        }
        url += request.path();

        // remove '/feed/'
        url.erase(url.length() - 6);
    }

    response.out() << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                      "<rss version=\"2.0\">\n"
                      "  <channel>\n"
                      "    <title>" << Wt::Utils::htmlEncode(title_) << "</title>\n"
                      "    <link>" << Wt::Utils::htmlEncode(url) << "</link>\n"
                      "    <description>" << Wt::Utils::htmlEncode(description_) << "</description>\n";
    Wt::Dbo::Transaction t(session);

    Posts posts = session.find<Post>("where state = ? order by date desc limit 10").bind(Post::Published);

    for (Posts::const_iterator i = posts.begin(); i != posts.end(); ++i)
    {
        Wt::Dbo::ptr<Post> post = *i;

        std::string permaLink = url + "/" + post->permaLink();

        response.out() << "    <item>\n"
                          "      <title>" << Wt::Utils::htmlEncode(post->title.toUTF8()) << "</title>\n"
                          "      <pubDate>" << post->date.toString("ddd, d MMM yyyy hh:mm:ss UTC")
                       << "</pubDate>\n"
                          "      <guid isPermaLink=\"true\">" << Wt::Utils::htmlEncode(permaLink)
                       << "</guid>\n";

        std::string description = post->briefHtml.toUTF8();
        if (!post->bodySrc.empty())
        {
            description += "<p><a href=\"" + permaLink + "\">Read the rest...</a></p>"; // Fix Language
        }

        response.out() << "      <description><![CDATA[" << description << "]]></description>\n    </item>\n";
    }

    response.out() << "  </channel>\n</rss>\n";

    t.commit();
} // end void BlogRSSFeed::handleRequest
Ejemplo n.º 10
0
void AlunoList::setTable(){

	Wt::Dbo::Transaction transaction(_dbSession);
	_table->clear();
	_table->setHeaderCount(1);
	_table->setStyleClass("table table-striped table-hover");
	_table->setWidth(500);

		Wt::Dbo::ptr<SiconfModel::Turma> turma = _disciplina->turma();

		Wt::Dbo::collection<Wt::Dbo::ptr<SiconfModel::Aluno>> alunos = turma->alunos();

		new Wt::WText("Nome", _table->elementAt(0,0));
		new Wt::WText("Frequencia", _table->elementAt(0,1));

		Wt::Dbo::collection<Wt::Dbo::ptr<SiconfModel::Avaliacao>> avaliacoes = _disciplina->avaliacoes();

		for(unsigned i = 1; i < (avaliacoes.size() + 1) ; i++){
			new Wt::WText("Av. " + std::to_string(i), _table->elementAt(0, _table->columnCount()));
		}

		new Wt::WText("Media", _table->elementAt(0, _table->columnCount()));

		for(auto aluno : alunos){
			int row = _table->rowCount();
			new Wt::WText(aluno->usuario()->nome(), _table->elementAt(row, 0));
			float presencas = 0.0;
			float total = 0.0;

			try{

				std::vector<Wt::Dbo::ptr<SiconfModel::Frequencia>> frequencias;

				total = _disciplina->aulas().size();

				Wt::Dbo::collection<Wt::Dbo::ptr<SiconfModel::Frequencia>> collFrequ = _dbSession.find<SiconfModel::Frequencia>("where frequencias_aluno_id = ?").bind(aluno.id());

				for(auto i : collFrequ){

					if(i->aula()->disciplina().id() == _disciplina.id()){
						if(i->presenca()){
							presencas +=1;
						}
					}
				}

				if(total > 0){
					for(auto i : frequencias){
						if(i->presenca()) presencas +=1;
					}
					presencas = ((presencas/total)* 100);
				}

			}catch(Wt::Dbo::Exception& e){
				std::cout << "AlunoList::setTable: " << e.what() << std::endl;
			}

			std::stringstream strPresencas;
			strPresencas << std::fixed << std::setprecision(1) << presencas;

			new Wt::WText(strPresencas.str() + " %", _table->elementAt(row, 1));
			unsigned col = 2;

			int qtdAvaliacoes = avaliacoes.size();
			float media = 0;

			for(auto avaliacao : avaliacoes){
				Wt::Dbo::ptr<SiconfModel::Nota> nota = _dbSession.find<SiconfModel::Nota>("where notas_avaliacao_id = ? and notas_aluno_id = ?").bind(avaliacao.id()).bind(aluno.id());
				if(nota){
					media+=nota->nota();
					std::stringstream strNotas;
					strNotas << std::fixed << std::setprecision(1) << nota->nota();
					Wt::WText* text = new Wt::WText(strNotas.str(), _table->elementAt(row, col));
					if(nota->nota() < 5){
						text->addStyleClass("text-red");
					}
				}
				col++;
			}


			if(qtdAvaliacoes == 0){
				media = 0;
			}else{
				media /= qtdAvaliacoes;
			}


			std::stringstream strMedia;
			strMedia << std::fixed << std::setprecision(1) << media;
			Wt::WText* text = new Wt::WText(strMedia.str(), _table->elementAt(row, _table->columnCount() -1));
			if(media < 5){
				text->addStyleClass("text-red");
			}
		}
}
Ejemplo n.º 11
0
//TODO fazer isso
float AlunoList::getFrequencia(Wt::Dbo::ptr<SiconfModel::Disciplina> disciplina, Wt::Dbo::ptr<SiconfModel::Aluno>  aluno){

	Wt::Dbo::Transaction transaction(_dbSession);

	Wt::Dbo::collection<Wt::Dbo::ptr<SiconfModel::Aula>> aulas = _dbSession.find<SiconfModel::Aula>().where("aulas_disciplina_id = ?").bind(disciplina.id());

	return 0.0;
}
Ejemplo n.º 12
0
Archivo: BlogView.C Proyecto: DTidd/wt
 void showPosts(dbo::ptr<User> user) {
   showPosts(user->latestPosts(), items_);
 }
Ejemplo n.º 13
0
/* ****************************************************************************
 * Menu Man Session
 * Check Database for existing records and delete them
 * Read in XML file and populate Database
 * <menuman name="" path="" type="" parent="" grandparent="" language="" content="" description="" keywords="" title="" copyright="" rating=""></menuman>
 */
bool MenuManSession::ImportXML()
{
    Wt::log("start") << " *** MenuManSession::ImportXML()  *** ";
    std::string fullFilePath = appPath_ + "db/menuman-db-import.xml";
    // FIXME: Multilanguage support, _cn.xml for chinese, make a loop
    /*
    */
    std::vector<std::string> myDir;
    CrystalBall::GetFilesInDirectory(myDir, appPath_ + "db");
    for (std::vector<std::string>::iterator it = myDir.begin() ; it != myDir.end(); ++it)
    {
       Wt::log("notice") <<  "File = " << *it;
       fullFilePath = *it;
       if (CrystalBall::IsFile(fullFilePath))
       {
           Wt::log("info") << "MenuManSession::ImportXML: " << fullFilePath;
       }
       else
       {
           Wt::log("error") << "-> Missing XML Configuration File MenuManSession::ImportXML: " << fullFilePath;
           return false;
       }
       try
       {
           // Open XML File
           const char *filePath = fullFilePath.c_str();
           rapidxml::file<> xmlFile(filePath);
           rapidxml::xml_document<> xmlDoc;
           xmlDoc.parse<0>(xmlFile.data());
           // Find our root node
           /*
            *
               <?xml version="1.0" encoding="UTF-8" ?>
               <menuman name="Test" path="test" content="This is a test"></menuman>
           */
           rapidxml::xml_node<> * root_node = xmlDoc.first_node("menusman");
           rapidxml::xml_attribute<> *nodeAttrib;
           for (rapidxml::xml_node<> * domain_node = root_node->first_node("menuman"); domain_node; domain_node = domain_node->next_sibling("menuman"))
           {
               Wt::log("progress") << "MenuManSession::ImportXML: Start Loop = " << domain_node->name();
               // Start a Transaction
               Wt::Dbo::Transaction t(*this);
               // Create a new Video Instance
               Wt::Dbo::ptr<MenuMan> thisMenu = add(new MenuMan());
               // Set object to Modify
               MenuMan *menuDb = thisMenu.modify();
               // name of Menu Item that will be shown in Menu
               nodeAttrib = domain_node->first_attribute("name");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: name = " << domain_node->name();
                   return false;
               }
               menuDb->name = Wt::WString::fromUTF8(nodeAttrib->value());
               Wt::log("progress") << "MenuManSession::ImportXML: name = " << nodeAttrib->value();
               // path of Menu Item that will be shown in address bar
               nodeAttrib = domain_node->first_attribute("path");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: path = " << domain_node->name();
                   return false;
               }
               menuDb->path = nodeAttrib->value();
               std::string myPath = nodeAttrib->value();
               Wt::log("progress") << "MenuManSession::ImportXML: path = " << nodeAttrib->value();
               // type
               nodeAttrib = domain_node->first_attribute("type");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: type = " << domain_node->name();
                   return false;
               }
               std::string menuType = nodeAttrib->value();
               menuDb->type = nodeAttrib->value();
               Wt::log("progress") << "MenuManSession::ImportXML: type = " << nodeAttrib->value();
               // parent
               nodeAttrib = domain_node->first_attribute("parent");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: parent = " << domain_node->name();
                   return false;
               }
               menuDb->parent = nodeAttrib->value();
               Wt::log("progress") << "MenuManSession::ImportXML: parent = " << nodeAttrib->value();
               // grandparent
               nodeAttrib = domain_node->first_attribute("grandparent");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: grandparent = " << domain_node->name();
                   return false;
               }
               menuDb->grandparent = nodeAttrib->value();
               Wt::log("progress") << "MenuManSession::ImportXML: grandparent = " << nodeAttrib->value();
               // language of Menu Item that will be shown in address bar: en, cn, ru...
               nodeAttrib = domain_node->first_attribute("language");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: language = " << domain_node->name();
                   return false;
               }
               menuDb->language = nodeAttrib->value();
               std::string myLanguage = nodeAttrib->value();
               Wt::log("progress") << "MenuManSession::ImportXML: language = " << nodeAttrib->value();
               // content of page for menu item, XHTML for WidgetFunction
               // Read from file
               if (menuType == "" || menuType == "submenu")
               {
                   /*
                   if (myPath == "/")
                       { myPath = "/home"; } // FIXME: home is hard corded
                   std::string fileSufix = "";
                   if (myLanguage != "en") // FIXME: Is en the default language?
                       { fileSufix = "_" + myLanguage; }


                   if (CrystalBall::IsFile(appPath_ + "xml" + myPath + fileSufix + ".xml"))
                   {
                       Wt::log("info") << "MenuManSession::ImportXML: " << fullFilePath;
                       std::string templateName = myPath;
                       size_t found = templateName.find_last_of("/\\");
                       if (found != std::string::npos)
                           { templateName = templateName.substr(found + 1); }
                       Wt::WApplication::instance()->setLocale(myLanguage);

                       Wt::WApplication::instance()->messageResourceBundle().use(appPath_ + "xml" + myPath, false);
                       Wt::WString myContent = Wt::WString::tr(templateName + "-template");
                       menuDb->content = Wt::WString::fromUTF8(myContent.toUTF8());
                   }
                    */
                   menuDb->content = CrystalBall::GetTemplate(appPath_, myPath, myLanguage); //
                   Wt::log("progress") << "MenuManSession::ImportXML: content";
               } // end if (menuType == "" || menuType == "submenu")
               // description
               nodeAttrib = domain_node->first_attribute("description");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: description = " << domain_node->name();
                   return false;
               }
               menuDb->description = Wt::WString::fromUTF8(nodeAttrib->value());
               Wt::log("progress") << "MenuManSession::ImportXML: description";
               // keywords
               nodeAttrib = domain_node->first_attribute("keywords");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: keywords = " << domain_node->name();
                   return false;
               }
               menuDb->keywords = Wt::WString::fromUTF8(nodeAttrib->value());
               Wt::log("progress") << "MenuManSession::ImportXML: keywords";
               // title
               nodeAttrib = domain_node->first_attribute("title");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: title = " << domain_node->name();
                   return false;
               }
               menuDb->title = Wt::WString::fromUTF8(nodeAttrib->value());
               Wt::log("progress") << "MenuManSession::ImportXML: title";
               // copyright
               nodeAttrib = domain_node->first_attribute("copyright");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: copyright = " << domain_node->name();
                   return false;
               }
               menuDb->copyright = Wt::WString::fromUTF8(nodeAttrib->value());
               Wt::log("progress") << "MenuManSession::ImportXML: copyright";
               // rating
               nodeAttrib = domain_node->first_attribute("rating");
               if (!nodeAttrib)
               {
                   Wt::log("error") << "MenuManSession::ImportXML: Missing XML Element: rating = " << domain_node->name();
                   return false;
               }
               menuDb->rating = nodeAttrib->value();
               Wt::log("progress") << "MenuManSession::ImportXML: rating = " << nodeAttrib->value();
               // Commit Transaction
               t.commit();
           } // end for
       }
       catch (std::exception& e)
       {
           std::cerr << e.what() << std::endl;
           std::cerr << "MenuManSession::ImportXML(): Failed writting to menuman database";
           Wt::log("error") << "-> MenuManSession::ImportXML()  Failed writting to menuman database: " << e.what();
           return false;
       }
    }
    Wt::WApplication::instance()->setLocale(lang_);
    Wt::log("end") << "MenuManSession::ImportXML()";
    return true;
} // end void MenuManSession::MenuManSession::ImportXML
Ejemplo n.º 14
0
 /// Logs the user out of all _userSessionStore eventually; this session immediately. 
 void logout() {
     _userCache.reset();
     _userSessionStore.logout(getCookie());
 }
Ejemplo n.º 15
0
void DboInstaller::InsertRows()
{
	Wt::Dbo::Transaction transaction(DboSession);

	//Authors and Modules
	InsertAuthorModules();

	//Configurations
	InsertConfigurations();

	//Localization
	InsertLanguages();

	//Pages
	O.LandingHomePage = DboSession.add(new Page(1, O.NavigationModule));
	O.LandingHomePage.modify()->Title = "Home";
	O.LandingHomePage.modify()->DefaultInternalPath = "home";

	O.SitemapPage = DboSession.add(new Page(2, O.NavigationModule));
	O.SitemapPage.modify()->Title = "Site map";
	O.SitemapPage.modify()->DefaultInternalPath = "sitemap";

	//Access Paths
	//English language
	O.DefaultLanguageAccessPath = DboSession.add(new AccessPath());
	O.DefaultLanguageAccessPath.modify()->HostName = "";
	O.DefaultLanguageAccessPath.modify()->InternalPath = "en";
	O.DefaultLanguageAccessPath.modify()->LanguagePtr = O.EnglishLanguagePtr;

	//Mobile version
	O.MobileVersionAccessPath = DboSession.add(new AccessPath());
	O.MobileVersionAccessPath.modify()->HostName = "";
	O.MobileVersionAccessPath.modify()->InternalPath = "mobile";

	//Home page
	O.HomePageAccessPath = DboSession.add(new AccessPath());
	O.HomePageAccessPath.modify()->HostName = "";
	O.HomePageAccessPath.modify()->InternalPath = "home";
	O.HomePageAccessPath.modify()->PagePtr = O.LandingHomePage;

	//Sitemap page
	Wt::Dbo::ptr<AccessPath> SitemapPageAccessPath = DboSession.add(new AccessPath());
	SitemapPageAccessPath.modify()->HostName = "";
	SitemapPageAccessPath.modify()->InternalPath = "sitemap";
	SitemapPageAccessPath.modify()->PagePtr = O.SitemapPage;

	//Default style
	O.DefaultStyle = DboSession.add(new Style("Default", O.SaifAuthor));
	O.DefaultStyle.modify()->Description = "Default style";
	O.DefaultStyle.modify()->CompatibilityVersionSeries = 1;
	O.DefaultStyle.modify()->CompatibilityVersionMajor = 0;

	transaction.commit();

	//Set IDs after they have been assigned in the database
	Wt::Dbo::Transaction transaction2(DboSession);

	O.DefaultAccessPathVal.modify()->Value = O.DefaultLanguageAccessPath.id();
	O.HomePageAccessPathIdVal.modify()->Value = O.HomePageAccessPath.id();
	O.MobileAccessPathIdVal.modify()->Value = O.MobileVersionAccessPath.id();

	O.DefaultStyleNameVal.modify()->Value = O.DefaultStyle.id().Name;
	O.DefaultStyleNameVal.modify()->DefaultValue = O.DefaultStyle.id().Name;
	O.DefaultStyleAuthorVal.modify()->Value = O.DefaultStyle.id().AuthorPtr.id();
	O.DefaultStyleAuthorVal.modify()->DefaultValue = O.DefaultStyle.id().AuthorPtr.id();

	transaction2.commit();
}
Ejemplo n.º 16
0
void UserDetailsModel::save(const Wt::Auth::User& authUser)
{
  Wt::Dbo::ptr<User> user = session_.user(authUser);
  user.modify()->favouritePet = valueText(FavouritePetField).toUTF8();
}