Exemple #1
0
bool IApplication::queryPrimaryProcessID(uint32 currentProcessID, uint32 &primaryProcessID) const
{
	primaryProcessID = 0;
	uint32 lastProcessID = 0;
	bool fileOpened = false;

	try
	{
		String syncFilePath = ProcessData::getSyncFilePath();
		boost::interprocess::file_mapping shared_file(syncFilePath.to_ascii().c_str(), boost::interprocess::read_write);

		fileOpened = true;
		boost::interprocess::mapped_region shared_region(shared_file, boost::interprocess::read_write);
		if(shared_region.get_size() != sizeof(ProcessData))
		{
			OS_LOG_ERROR("Process exception: corrupted file '" + syncFilePath + "'");
			return false;
		}

		ProcessData *processData = static_cast<ProcessData *>(shared_region.get_address());			

		boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(processData->mutex, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::millisec(OS_PROCESS_SHARED_MEMORY_LOCK_TIMEOUT));
		if(!lock)
		{
			OS_LOG_ERROR(_S("Process exception: lock timeout"));
			return false;
		}

		lastProcessID = processData->processID;
	}
	catch(std::exception &e)
	{
		if(fileOpened)
			OS_LOG_DEBUG(_S("Process exception: ") + e.what());

		return false;
	}

	shared_ptr<PlatformManager::ProcessDetails> lastProcessDetails = PlatformManager::instance()->getProcessDetails(lastProcessID);
	if(lastProcessDetails == nullptr)
		return false;

	// N.B.: non è sufficiente verificare se il processo è ancora attivo in quanto potrebbe essere terminato e il sistema operativo
	// abbia assegnato ad un nuovo processo l'ID appena letto, pertanto, se disponibile, bisogna verificare che i path degli eseguibili coincidano

	shared_ptr<PlatformManager::ProcessDetails> currentProcessDetails = PlatformManager::instance()->getProcessDetails(currentProcessID);
	OS_ASSERT(currentProcessDetails != nullptr);	// I dettagli sul processo corrente dovrebbero essere sempre disponibili
	if(currentProcessDetails != nullptr)
	{
		// Verifica che sia stato possibile determinare il path degli eseguibili di entrambe i processi
		if((currentProcessDetails->executablePath.empty() == false) && (lastProcessDetails->executablePath.empty() == false))
		{
			if(FileSystem::instance()->comparePaths(FileSystem::instance()->getFilePath(currentProcessDetails->executablePath), FileSystem::instance()->getFilePath(lastProcessDetails->executablePath)) == false)
				return false;			
		}
	}

	primaryProcessID = lastProcessID;
	return true;
}
Exemple #2
0
bool PortalsSystem::deletePortal(shared_ptr<PortalOptions> options, const String &path)
{
	if(options == nullptr || options->getDeleted() == false)
		return false;

	NotificationsManager::instance()->notify(_S("Removing portal '") + options->getName() + _S("'"));

	String driverName = options->getDatabaseDriver();
	shared_ptr<IDbDriver> driver = DatabasesSystem::instance()->getDriver(driverName.to_ascii());
	if(driver == nullptr)
	{
		OS_LOG_ERROR(_S("Invalid database driver '") + driverName + _S("'"));
		return false;
	}

	String databaseName = options->getDatabaseName();
	if(driver->removeDatabase(databaseName.to_ascii(), options->getDatabaseOptions()) == false)
	{
		OS_LOG_ERROR(_S("Cannot remove database '") + databaseName + _S("'"));
		return false;
	}

	if(FileSystem::instance()->removeDirectory(path) == false)
	{
		OS_LOG_ERROR(_S("Cannot remove directory '") + path + _S("'"));
		return false;
	}

	return true;
}
Exemple #3
0
shared_ptr<Portal> PortalsSystem::_loadPortal(const String &path, bool recovery, bool start)
{
	try
	{
		shared_ptr<Portal> portal(OS_NEW Portal(getPeersCacheSize(), getDatabasesCacheSize()));
		if(_initPortal(portal, path, recovery, start) == false)
			return nullptr;

		/*
		if(getPortal(portal->getPortalID()) != nullptr)
			return false;
		*/
		if(getPortalByFullPov(portal->getFullPovID()) != nullptr)
			return nullptr;

		m_portals.push_back(portal);
		return portal;
	}
	catch(std::exception &e)
	{
		OS_LOG_ERROR(e.what());
	}
	catch(...)
	{
		OS_LOG_ERROR(_S("Unknown error loading portal '") + path + _S("'"));
	}

	return nullptr;
}
Exemple #4
0
bool exportToString(const OS_NAMESPACE_NAME::XMLDocument &document, OS_NAMESPACE_NAME::String &str)
{
    try
    {
        AutoPtr<DOMDocument> doc = getImplementation()->createDocument();
        if(convertDocument(document, doc) == false)
            return false;

        AutoPtr<DOMLSSerializer> writer(createWriter());

        XMLCh *xmlString = writer->writeToString(doc->getDocumentElement());
        str = xmlString;
        XMLString::release(&xmlString);

        return true;
    }
    catch(const XMLException &e)
    {
        OS_LOG_ERROR(e.getMessage());
    }
    catch(const DOMException &e)
    {
        OS_LOG_ERROR(e.getMessage());
    }
    catch(...)
    {
        OS_LOG_ERROR(OS_ERR_UNKNOWN(xml));
    }

    return false;
}
Exemple #5
0
bool exportToTarget(const OS_NAMESPACE_NAME::XMLDocument &document, XMLFormatTarget *target, const OS_NAMESPACE_NAME::String &encoding)
{
    try
    {
        AutoPtr<DOMDocument> doc = getImplementation()->createDocument();
        if(convertDocument(document, doc) == false)
            return false;

        AutoPtr<DOMLSSerializer> writer(createWriter());
        AutoPtr<DOMLSOutput> stream(createOutputStream(encoding));
        stream->setByteStream(target);

        writer->write(doc, stream);

        return true;
    }
    catch(const XMLException &e)
    {
        OS_LOG_ERROR(e.getMessage());
    }
    catch(const DOMException &e)
    {
        OS_LOG_ERROR(e.getMessage());
    }
    catch(...)
    {
        OS_LOG_ERROR(OS_ERR_UNKNOWN(xml));
    }

    return false;
}
Exemple #6
0
bool IApplication::postPrimaryProcessCommand(uint32 primaryProcessID, std::string command)
{
	if(command.empty())
	{
		OS_ASSERTFALSE();
		return false;
	}

	try
	{
		String syncFilePath = ProcessData::getSyncFilePath();
		boost::interprocess::file_mapping shared_file(syncFilePath.to_ascii().c_str(), boost::interprocess::read_write);
		boost::interprocess::mapped_region shared_region(shared_file, boost::interprocess::read_write);
		if(shared_region.get_size() != sizeof(ProcessData))
		{
			OS_LOG_ERROR("Process exception: corrupted file '" + syncFilePath + "'");
			return false;
		}

		ProcessData *processData = static_cast<ProcessData *>(shared_region.get_address());			

		boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(processData->mutex, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::millisec(OS_PROCESS_SHARED_MEMORY_LOCK_TIMEOUT));
		if(!lock)
		{
			OS_LOG_ERROR(_S("Process exception: lock timeout"));
			return false;
		}

		String dataFilePath = processData->getDataFilePath();

		shared_ptr<File> dataFile(OS_NEW File());
		if(dataFile->open(dataFilePath, File::ofWrite | File::ofNoTruncate) == false)
		{
			OS_LOG_ERROR("Error opening or creating file '" + dataFilePath + "'");
			return false;
		}

		if(dataFile->size() > 0)
		{
			dataFile->seekToEnd();
			command.insert(0, OS_IAPPLICATION_COMMANDS_SEPARATOR);
		}
		
		if(dataFile->write(command.data(), static_cast<uint32>(command.size())) != static_cast<uint32>(command.size()))
		{
			OS_LOG_ERROR("Error writing file '" + dataFilePath + "'");
			return false;
		}
	}
	catch(std::exception &e)
	{
		OS_LOG_DEBUG(_S("Process exception: ") + e.what());
		return false;
	}

	return true;
}
Exemple #7
0
shared_ptr<Portal> PortalsSystem::ensurePortal(shared_ptr<OsirisLink> link, const String &password)
{
	if(link == nullptr)
	{
		OS_ASSERTFALSE();
		return nullptr;
	}

	OS_LOCK(m_cs);

	shared_ptr<Portal> portal = getPortal(link->getPortal(), link->getPov());
	if(portal != nullptr)
		return portal;

	shared_ptr<IDbDriver> defaultDriver = DatabasesSystem::instance()->getDefaultDriver();
	if(defaultDriver == nullptr)
	{
		OS_LOG_ERROR("Invalid database driver");
		return nullptr;
	}

	PortalID portalID = link->getPortal();
	PovID povID = link->getPov();
	String portalName = link->getName();
	if(portalName.empty())
		portalName = portalID.toUTF16();
	//String portalDescription = link->getDescription();

	shared_ptr<PortalOptions> portalOptions(OS_NEW PortalOptions());
	portalOptions->setName(portalName);
	//portalOptions->setDescription(portalDescription);
	portalOptions->setPortalID(portalID);
	portalOptions->setPovID(povID);
	portalOptions->setPassword(password);
	portalOptions->setDatabaseDriver(defaultDriver->getName());
	portalOptions->setDatabaseOptions(defaultDriver->createOptions());

	// VERYURGENT: le varie createPortal/subscribePortal dovrebbero restituire il riferimento al portale
	portal = subscribePortal(portalOptions);
	if(portal == nullptr)
	{
		OS_LOG_ERROR("Cannot create portal");
		return nullptr;
	}

	//portal = getPortal(portalID, povID);
	//OS_ASSERT(portal != nullptr);
	return portal;
}
Exemple #8
0
bool IdeSkin::_parseAttributes(const shared_ptr<XMLNode> &node)
{
	OS_ASSERT(node != nullptr);

	m_id = node->getAttributeString(ID).to_ascii();
	if(m_id.validate(false) == false)
		return false;
	
	/*
	if(m_id != id)
		return false;
	*/

	m_name = node->getAttributeString(NAME);
	if(m_name.empty())
		return false;

	m_preview = node->getAttributeString(PREVIEW);
	m_description = node->getAttributeString(DESCRIPTION);
	m_version = node->getAttributeString(VERSION);
	m_author = node->getAttributeString(AUTHOR);

	if(m_compatibility.fromString(node->getAttributeString(COMPATIBILITY).to_ascii()) == false)
		return false;

	if(m_compatibility > OS_OSIRIS_VERSION())
	{
		OS_LOG_ERROR(_S("Incompatible skin"));
		return false;
	}

	return true;
}
Exemple #9
0
shared_ptr<NTPResponse> NTPClient::query(shared_ptr<boost::asio::io_service> service, shared_ptr<UDPSocket> socket, const String &server, uint32 port)
{
    try
    {
        if(socket == nullptr)
        {
            OS_ASSERTFALSE();
            return nullptr;
        }

        shared_ptr<NTPClient> client(OS_NEW NTPClient(service, socket));
        client->query(boost::asio::ip::udp::resolver::query(boost::asio::ip::udp::v4(), server.to_ascii(), conversions::to_string(port)));
        // VERYURGENT: fixme (sul servizio potrebbero essere accodate altre operazione che non sono da processare...)
        // O si fa una versione sincrona o si gestisce dall'esterno in versione asincrona
        service->run();

        return client->m_response;
    }
    catch(std::exception &e)
    {
        OS_LOG_ERROR(_S("Ntp error: ") + e.what());
    }

    return nullptr;
}
Exemple #10
0
IJob::JobStatus PortalsExporterJob::run()
{
	shared_ptr<Portal> portal = getPortal();
	if(portal == nullptr)
		return jobComplete;

	NotificationsManager::instance()->notify(_S("Exporting of '") + portal->getName() + _S("' started."));

	m_file.reset();

	shared_ptr<TemporaryFile> file = Options::instance()->createTemporaryFile();
	if(file == nullptr)
	{
		OS_LOG_ERROR("Cannot create temporary file for export");
		return jobComplete;
	}

	m_serializer->setStopped(false);
	if(m_serializer->exportStream(portal, file, m_format))
	{
		file->close();
		m_file = file;
	}

	NotificationsManager::instance()->notify(_S("Exporting of '") + portal->getName() + _S("' completed."));

	return jobComplete;
}
Exemple #11
0
bool P2pMachine::store()
{
	if(validate() == false)
		return false;

	try
	{
		shared_ptr<IDbConnection> connection = Engine::instance()->createSystemConnection();
		
		DbSqlValues values;
		values.set(_S("id"), m_id.toHex());
		values.set(_S("public_key"), m_publicKey);

		shared_ptr<IDbStatement> statement = connection->_prepare(connection->prepare_insert(_S("os_machines"), values));
		for(DbSqlValues::iterator i = values.begin(); i != values.end(); i++)
		{
			statement->addParameter()->setValue(i->second);
		}

		statement->execute();
		return true;
	}
	catch(std::exception &e)
	{
		OS_LOG_ERROR(e.what());
	}

	return false;
}
Exemple #12
0
bool IApplication::peekProcessData(std::string &data)
{
	data.clear();

	try
	{
		String syncFilePath = ProcessData::getSyncFilePath();
		boost::interprocess::file_mapping shared_file(syncFilePath.to_ascii().c_str(), boost::interprocess::read_write);
		boost::interprocess::mapped_region shared_region(shared_file, boost::interprocess::read_write);
		if(shared_region.get_size() != sizeof(ProcessData))
		{
			OS_LOG_ERROR("Process exception: corrupted file '" + syncFilePath + "'");
			return false;
		}

		ProcessData *processData = static_cast<ProcessData *>(shared_region.get_address());			

		boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(processData->mutex, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::millisec(OS_PROCESS_SHARED_MEMORY_LOCK_TIMEOUT));
		if(!lock)
		{
			OS_LOG_ERROR(_S("Process exception: lock timeout"));
			return false;
		}

		String dataFilePath = processData->getDataFilePath();

		Buffer dataFileBuffer;
		if(dataFileBuffer.load(dataFilePath) == false)
			return false;

		if(FileSystem::instance()->remove(dataFilePath) == false)
		{
			OS_LOG_ERROR("Cannot remove file '" + dataFilePath + "'");
			return false;
		}

		data.assign(reinterpret_cast<const char *>(dataFileBuffer.getData()), dataFileBuffer.getSize());
	}
	catch(std::exception &e)
	{
		OS_LOG_DEBUG(_S("Process exception: ") + e.what());
		return false;
	}

	return data.empty() == false;
}
Exemple #13
0
void IApplication::cleanupProcess()
{
	OS_ASSERT(isPrimaryProcess());

	if(m_notifyListener != nullptr)
	{
		OS_ASSERT(m_notifyListener->running() == false);
		m_notifyListener.reset();
	}

	try
	{
		String syncFilePath = ProcessData::getSyncFilePath();

		{
			boost::interprocess::file_mapping shared_file(syncFilePath.to_ascii().c_str(), boost::interprocess::read_write);

			boost::interprocess::mapped_region shared_region(shared_file, boost::interprocess::read_write, 0, sizeof(ProcessData));

			ProcessData *processData = OS_PLACEMENT_NEW(shared_region.get_address(), ProcessData);

			boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(processData->mutex, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::millisec(OS_PROCESS_SHARED_MEMORY_LOCK_TIMEOUT));
			if(lock)
			{
				String dataFilePath = ProcessData::getDataFilePath(m_processID);
				if(FileSystem::instance()->remove(dataFilePath) == false)
					OS_LOG_ERROR("Error removing file '" + dataFilePath + "'");
			}
			else
			{
				OS_LOG_ERROR("Process exception: lock timeout");
			}
		}

		if(isPrimaryProcess())
		{			
			if(boost::interprocess::file_mapping::remove(syncFilePath.to_ascii().c_str()) == false)
				OS_LOG_ERROR("Process exception: error removing file '" + syncFilePath + "'");
		}
	}
	catch(std::exception &e)
	{
		OS_LOG_DEBUG(_S("Process exception: ") + e.what());
	}
}
Exemple #14
0
bool PortalsSystem::_setupPortal(shared_ptr<PortalOptions> options, const String &path)
{
	if(options->writeFile(utils::makeFilePath(path, OS_PORTAL_XML)) == false)
		return false;

	shared_ptr<DbSchemaSchema> schema(OS_NEW DbSchemaSchema());
	if(schema->parse(DatabasesSystem::instance()->getDatabasePath(OS_PORTAL_DB_TYPE, OS_PORTAL_DB_VERSION, false)) == false)
	{
		OS_LOG_ERROR(_S("Cannot parse portal's database schema"));
		return false;
	}

	shared_ptr<IDbDriver> driver = DatabasesSystem::instance()->getDriver(options->getDatabaseDriver().to_ascii());
	if(driver == nullptr)
	{
		OS_LOG_ERROR(_S("Invalid database driver"));
		return false;
	}

	return DatabasesSystem::instance()->createDatabase(driver, options->getDatabaseName(), options->getDatabaseOptions(), schema);
}
Exemple #15
0
bool IApplication::init(int argc, wchar_t *argv[])
{
	if(argc == 0)
	{
		OS_ASSERTFALSE();

		OS_LOG_ERROR("Invalid args");
		return false;
	}

	FileSystem::instance()->initExecutableName(argv[0]);
	return init(FileSystem::instance()->getExecutablePath());		
}
Exemple #16
0
void NetworkService::stopService()
{
	try
	{
		m_impl->service->stop();
	}
	catch(std::exception &e)
	{
		OS_LOG_ERROR(_S("Service error (closing): ") + e.what());
	}

	getConnectionsManager()->disable();
}
Exemple #17
0
void NetworkService::runService()
{
	while(stopped() == false)
	{
		try
		{
			m_impl->service->run();
		}
		catch(std::exception &e)
		{
			OS_LOG_ERROR(String(_S("Network service error: ")) + e.what());
		}
	}
}
Exemple #18
0
uint32 IDbConnection::value_of(shared_ptr<DbSqlICommand> command)
{
	try
	{
		String sql;
		_parse(command, sql);

		return value_of(sql);
	}
	catch(std::exception &e)
	{
		OS_LOG_ERROR(e.what());
	}

	return 0;
}
Exemple #19
0
bool IApplication::init(const String &rootPath)
{
	String versionName;
	versionName.append(OS_OSIRIS_APPLICATION_NAME);
	versionName.append(String::format(_S(" %d.%d").c_str(), OS_OSIRIS_VERSION_MAJOR, OS_OSIRIS_VERSION_MINOR));
	/* // Show release name only with "... is ready.".
	if(OS_OSIRIS_RELEASE_NAME != String::EMPTY)
	{
		versionName.append(_S(" "));
		versionName.append(OS_OSIRIS_RELEASE_NAME);
	}
	*/
	NotificationsManager::instance()->notify(versionName + _S(" is starting..."));
	
	if(PlatformManager::instance()->isPrivilegedUser())
		NotificationsManager::instance()->notify(_S("Running with a user with system privileges."));
	else
		NotificationsManager::instance()->notify(_S("Running with a user without system privileges. Some options maybe unavailable."));

	NotificationsManager::instance()->notify(_S("Platform: ") + Engine::getPlatformName());

	NotificationsManager::instance()->notify("Initializing options...");

	if(Options::instance()->load(rootPath) == false)
	{
		OS_LOG_ERROR("Error loading options");
		return false;
	}

	// Compatibility - TOCLEAN - Inutile collocarla più pulita, tanto la tolgo proprio con Razor (che non supporterà l'aggiornamento da 0.X).
	if(FileSystem::instance()->directoryExists(utils::makeFolderPath(Options::instance()->getDataPath(), OS_PLUGINS_PATH)))
		FileSystem::instance()->rename(utils::makeFolderPath(Options::instance()->getDataPath(), OS_PLUGINS_PATH), utils::makeFolderPath(Options::instance()->getDataPath(), OS_STORE_PATH));

	initProcess();

	if(isPrimaryProcess() == false)
		return false;

	return true;
}
Exemple #20
0
/// Start the timer to fire once at the indicated date/time
bool OsTimer::Timer::oneshotAt(const OsDateTime& t)
{
  OsTimer::Time now = OsTimer::now();
  OsTime t_os;
  t.cvtToTimeSinceEpoch(t_os);
  OsTimer::Time expireFromNow = (OsTimer::Time)(t_os.seconds()) * TIMER_TIME_UNIT + t_os.usecs();

  {
    mutex_lock lock(_mutex);
    if (_isRunning)
      return false;
    else
      _isRunning = true;
 
    if (expireFromNow <= now)
    {
      OS_LOG_ERROR(FAC_KERNEL, "OsTimer::Timer::oneshotAt timer expiration is in the past.  Call ignored.");
      _isRunning = false;
      return false;
    }
    _expiresAt = expireFromNow;
  }


  //
  // This function sets the expiry time. Any pending asynchronous wait 
  // operations will be cancelled. The handler for each cancelled operation will
  // be invoked with the boost::asio::error::operation_aborted error code.
  //
  {
    mutex_lock lock(gTimerServiceMutex);
    boost::system::error_code ec;
    _pDeadline->expires_from_now(boost::posix_time::microseconds(expireFromNow - now), ec);
    //
    // Perform an assynchronous wait on the timer
    //
    _pDeadline->async_wait(boost::bind(&OsTimer::Timer::onTimerFire, shared_from_this(), boost::asio::placeholders::error, &_owner));
  }  
  return _isRunning;
}
Exemple #21
0
bool P2pMachine::load(const String &id)
{
	try
	{
		shared_ptr<IDbConnection> connection = Engine::instance()->createSystemConnection();
		
		shared_ptr<DbSqlSelect> select(OS_NEW DbSqlSelect(_S("os_machines")));
		select->where.add(_S("id"), Convert::toSQL(id));
		select->limit.setCount(1);

		DataTable result;
		connection->query(select, result);

		if(result.rows() == 1)
		{
			DataTableRow row = result[0];

			DbValue<String> id;
			id.read(row, _S("id"));
			if(m_id.fromHex(id->to_ascii()) == false)
			{
				OS_ASSERTFALSE();
				return false;
			}

			DbValue<Buffer> public_key;
			public_key.read(row, _S("public_key"));
			m_publicKey = public_key;

			return true;
		}
	}
	catch(std::exception &e)
	{
		OS_LOG_ERROR(e.what());
	}

	return false;
}
Exemple #22
0
bool CompatibilityManager::razorUpgrade(const String &folder)
{
	try
	{
		if(FileSystem::instance()->directoryExists(folder))
		{
			StringList portals;
			FileSystem::instance()->getDirectories(folder, portals, false);
			for(StringList::const_iterator i = portals.begin(); i != portals.end(); ++i)
			{
				// 000000018F94C9554C8B227CF000C6E30EB281AEAE1A77E7
				String name = *i;
				if(name.length() == 48)
				{
					// Portal < Razor
					std::string oldID = name.to_ascii();

					// Options
					String oldPath = utils::standardisePath(folder + oldID);
					shared_ptr<PortalOptions> options(OS_NEW PortalOptions());
					// Carica le impostazioni del portale
					if(options->readFromPath(oldPath) == false)
						return false;
					
					shared_ptr<IDbDriver> driver = DatabasesSystem::instance()->getDriver("sqlite");

					// Query Database
					shared_ptr<IDbConnection> connection = driver->createConnection(oldID, driver->createOptions());

					connection->open();
					
					String portalName = options->getName();
					//String portalDescription = static_cast<String>(options->getOptionValue("description"));


					NotificationsManager::instance()->notify(_S("Migration of '") + portalName + _S("' to 1.0 series"));
					PlatformManager::instance()->sleep(500);

					//ObjectID userID = static_cast<String>(m_portalOptions.getOption(options::users_reference)).to_ascii();
					ObjectID userID = static_cast<String>(options->getOptionValue("users.reference")).to_ascii();

					//bool monarchic = (options->getPortalID().getPortalType() == portalTypeMonarchic);
					ID oldPortalID(oldID);
					uint8 portalType = OS_UINT8_LO(oldPortalID.getHeader().getFirst());
					bool monarchic = (portalType == 1);

					// Calcolo UserID.
					// Se non lo posso dedurre, uso il primo che trovo loggato.					
					if(userID.empty())
					{
						if(monarchic)
						{
							//userID = options->getPortalID().getAdministratorID();
#ifdef OS_NOOBJECTID
							userID = oldPortalID.getHash();
#else
							userID = ObjectID::generate(portalObjectTypeUser, oldPortalID.getHash());
#endif
						}
						else
						{
							String sql = String::EMPTY;
							sql += _S(" select tp.profile, tu.reference ");
							sql += _S(" from ");
							sql += _S(" os_snapshot_profiles tp, ");
							sql += _S(" os_snapshot_users tu ");
							sql += _S(" where  ");
							sql += _S(" tp.profile=tu.profile and ");
							sql += _S(" tu.score=1 and ");
							sql += _S(" tu.follow=1 and ");
							sql += _S(" tu.description='Auto valutation'");

							shared_ptr<IDbResult> result = connection->query(sql);
							DataTable table;
							result->init(table);
							DataTableRow row = table.addRow();

							while(result->end() == false)
							{
								result->bind(row);
								String objectID = static_cast<String>(*row[1]);

								userID = objectID.to_ascii();

								result->moveNext();

								break;
							}
						}
					}
					
#ifdef OS_NOOBJECTID
					PovID povID = userID;
#else
					PovID povID = userID.getHash();
#endif
					
					if(userID.empty() == false)
					{
						// Clean old snapshot
						connection->execute(_S("delete from os_snapshot_objects"));
						connection->execute(_S("delete from os_snapshot_users"));
						connection->execute(_S("delete from os_snapshot_profiles"));
						connection->execute(_S("delete from os_discussions_stats"));
						//connection->execute(_S("delete from os_forums_forum_stats"));
						//connection->execute(_S("delete from os_forums_section_stats"));
						connection->execute(_S("delete from os_polls_stats"));
						connection->execute(_S("delete from os_polls_options_stats"));
						connection->execute(_S("delete from os_users_stats"));

						// Old
						connection->execute(_S("drop table if exists os_forums_forum_stats"));
						connection->execute(_S("drop table if exists os_forums_section_stats"));

						// Reset acceptable
						connection->execute(_S("update os_entries set rank=-2"));

						// Clean signatures
#ifdef OS_NEWSIGNATURE
						connection->execute(_S("update os_attributes set signature=x'00'"));
						connection->execute(_S("update os_avatars set signature=x'00'"));
						connection->execute(_S("update os_calendar_events set signature=x'00'"));
						connection->execute(_S("update os_files set signature=x'00'"));
						connection->execute(_S("update os_instances set signature=x'00'"));
						connection->execute(_S("update os_models set signature=x'00'"));
						connection->execute(_S("update os_polls set signature=x'00'"));
						connection->execute(_S("update os_polls_options set signature=x'00'"));
						connection->execute(_S("update os_polls_votes set signature=x'00'"));
						connection->execute(_S("update os_posts set signature=x'00'"));
						connection->execute(_S("update os_private_messages set signature=x'00'"));
						connection->execute(_S("update os_reputations set signature=x'00'"));
						connection->execute(_S("update os_sections set signature=x'00'"));
						connection->execute(_S("update os_tags set signature=x'00'"));
						connection->execute(_S("update os_texts set signature=x'00'"));
						connection->execute(_S("update os_users set signature=x'00'"));
						connection->execute(_S("update os_votes set signature=x'00'"));
#endif
						

						// identificarli:
						// select * from os_users where signature=x'00'		

						
					}
					

					connection->close();

					if(userID.empty() == false)
					{					
						String newPortalIDKey = oldID.substr(8);
						PortalID newPortalID = CryptManager:: instance()->SHA(newPortalIDKey.buffer(), newPortalIDKey.buffer_size()).toHex();

						String newPovID = Portal::generatePovID(newPortalID, povID);
						String newPath = utils::standardisePath(folder + newPovID);

						options->setPortalID(newPortalID);
						options->setPovID(povID);
						options->setDatabaseName(newPovID);

						FileSystem::instance()->ensureDirectory(newPath);
					
						options->writeToPath(newPath);

						String sqlitePluginID = _S("532E9E0A68EB22E08240965CFA9366DFA6A26A62");
						String databaseRootPath = utils::makeFolderPath(Options::instance()->getDataPath(), utils::makeFolderPath(OS_STORE_PATH, sqlitePluginID));
						String oldDatabasePath = utils::makeFilePath(databaseRootPath,oldID) + _S(".db");
						String newDatabasePath = utils::makeFilePath(databaseRootPath,newPovID) + _S(".db");
		
						FileSystem::instance()->copyFile(oldDatabasePath, newDatabasePath);						

						FileSystem::instance()->remove(oldDatabasePath);
						FileSystem::instance()->removeDirectory(oldPath);
					}
					else
					{
						OS_LOG_ERROR("Unable to migrate portal '" + portalName + "', ID:" + oldID + ". Contact our forum, thanks.");
					}

				}			
			}
		}
	}
	catch(std::exception &e)
	{
		OS_LOG_ERROR(e.what());
		return false;
	}
	catch(...)
	{
		OS_LOG_ERROR(_S("Unknown error during Razor upgrade.'"));
		return false;
	}

	return true;
}
void StateQueuePublisher::internal_run()
{
  zmq::context_t context(1);
  zmq::socket_t socket(context, ZMQ_PUB);

  try
  {
    socket.bind(_zmqBindAddress.c_str());
  }
  catch(zmq::error_t& error_)
  {
    return;
  }

  OS_LOG_NOTICE(FAC_NET, "StateQueuePublisher::internal_run() "
          << "Started accepting subscriptions at " << _zmqBindAddress);
  
  while(!_terminate)
  {
    StateQueueRecord record;
    if (_queue.dequeue(record))
    {
      //
      // exit
      //
      if (_terminate)
        break;

      //
      // publish
      //
      std::string eventId = record.id;


      if (!record.watcherData && eventId.size() < 7)
      {
        OS_LOG_ERROR(FAC_NET, "StateQueuePublisher::publish eventId is too short - " << eventId);
        continue;
      }

      try
      {
        s_sendmore(socket, eventId);

        std::string data;

        if (!record.watcherData)
        {
          for (std::vector<std::string>::const_iterator iter = record.exclude.begin();
                  iter != record.exclude.end(); iter++)
          {
            data += *iter;
            data += " ";
          }

          if (data.empty())
            data = "initial_data";

          OS_LOG_DEBUG(FAC_NET, "StateQueuePublisher::publish "
                  << " message-id: " << eventId
                  << " exclude-app-id: " << data);
        }
        else
        {
          data = record.data;
        }

        //
        // Send the address
        //
        s_sendmore(socket, _zmqBindAddress);
        //
        // Send the data vector
        //
        s_sendmore(socket, data);
        //
        // Send the number of subscribers
        //
        std::string ev = eventId.substr(0, 7);
        int count = countSubscribers(ev);
        std::string strcount = boost::lexical_cast<std::string>(count);
        s_send(socket, strcount);


        OS_LOG_DEBUG(FAC_NET, "StateQueuePublisher::publish ZeroMQ send: " << eventId << ":" << data);

        if (!record.watcherData && !count)
        {
          OS_LOG_WARNING(FAC_NET, "StateQueuePublisher::publish "
                << "ZERO subscribers to handle message-id: " << eventId);
        }
      }
      catch(zmq::error_t& error_)
      {
        OS_LOG_WARNING(FAC_NET, "StateQueuePublisher::publish "
                << "ZMQ Error sending publish " << eventId << " Error: " << error_.what());
      }
    }
    else
    {
      OS_LOG_ERROR(FAC_NET, "FAILED TO DEQUEUE!");
    }
  }
  OS_LOG_NOTICE(FAC_NET, "StateQueuePublisher::internal_run() TERMINATED.");
}
Exemple #24
0
EntityRecord& EntityRecord::operator = (const MongoDB::BSONObj& bsonObj)
{
    try
    {
        _oid = bsonObj.getStringField(EntityRecord::oid_fld());

        if (bsonObj.hasField(EntityRecord::userId_fld()))
        {
            _userId = bsonObj.getStringField(EntityRecord::userId_fld());
        }

        if (bsonObj.hasField(EntityRecord::identity_fld()))
        {
            _identity = bsonObj.getStringField(EntityRecord::identity_fld());
        }

        if (bsonObj.hasField(EntityRecord::realm_fld()))
        {
            _realm = bsonObj.getStringField(EntityRecord::realm_fld());
        }

        if (bsonObj.hasField(EntityRecord::password_fld()))
        {
            _password = bsonObj.getStringField(EntityRecord::password_fld());
        }

        if (bsonObj.hasField(EntityRecord::pin_fld()))
        {
            _pin = bsonObj.getStringField(EntityRecord::pin_fld());
        }

        if (bsonObj.hasField(EntityRecord::authType_fld()))
        {
            _authType = bsonObj.getStringField(EntityRecord::authType_fld());
        }

        if (bsonObj.hasField(EntityRecord::location_fld()))
        {
            _location = bsonObj.getStringField(EntityRecord::location_fld());
        }

        if (bsonObj.hasField(EntityRecord::callForwardTime_fld()))
        {
            _callForwardTime = bsonObj.getIntField(EntityRecord::callForwardTime_fld());
        }

        if (bsonObj.hasField(EntityRecord::vmOnDnd_fld()))
        {
            _vmOnDnd = bsonObj.getBoolField(EntityRecord::vmOnDnd_fld());
        }

        if (bsonObj.hasField(EntityRecord::callerId_fld()))
        {
            _callerId.id = bsonObj.getStringField(EntityRecord::callerId_fld());
            _callerId.enforcePrivacy = bsonObj.getBoolField(EntityRecord::callerIdEnforcePrivacy_fld());
            _callerId.ignoreUserCalleId = bsonObj.getBoolField(EntityRecord::callerIdIgnoreUserCalleId_fld());
            _callerId.transformExtension = bsonObj.getBoolField(EntityRecord::callerIdTransformExtension_fld());
            _callerId.extensionLength = bsonObj.getIntField(EntityRecord::callerIdExtensionLength_fld());
            _callerId.extensionPrefix = bsonObj.getStringField(EntityRecord::callerIdExtensionPrefix_fld());
            if (_userId == "~~gw")
                _callerId.type = "gateway";
            else
                _callerId.type = "user";
        }

        if (bsonObj.hasField(EntityRecord::permission_fld()))
        {
            MongoDB::BSONElement obj = bsonObj[EntityRecord::permission_fld()];
            if ( obj.isABSONObj() &&  obj.type() == mongo::Array)
            {
                std::vector<MongoDB::BSONElement> permissions = obj.Array();
                _permissions.clear();
                for (std::vector<MongoDB::BSONElement>::iterator iter = permissions.begin();
                    iter != permissions.end(); iter++)
                {
                    _permissions.insert(iter->String());
                }
            }
        }

        if (bsonObj.hasField(EntityRecord::aliases_fld()))
        {
            MongoDB::BSONElement obj = bsonObj[EntityRecord::aliases_fld()];
            if ( obj.isABSONObj() &&  obj.type() == mongo::Array)
            {
                std::vector<MongoDB::BSONElement> aliases = obj.Array();
                for (std::vector<MongoDB::BSONElement>::iterator iter = aliases.begin();
                    iter != aliases.end(); iter++)
                {
                    MongoDB::BSONObj innerObj = iter->Obj();
                    Alias alias;
                    if (innerObj.hasField(EntityRecord::aliasesId_fld()))
                        alias.id = innerObj.getStringField(EntityRecord::aliasesId_fld());
                    if (innerObj.hasField(EntityRecord::aliasesContact_fld()))
                        alias.contact = innerObj.getStringField(EntityRecord::aliasesContact_fld());
                    if (innerObj.hasField(EntityRecord::aliasesRelation_fld()))
                        alias.relation = innerObj.getStringField(EntityRecord::aliasesRelation_fld());
                    _aliases.push_back(alias);
                }
            }
        }

        if (bsonObj.hasField(EntityRecord::staticUserLoc_fld()))
        {
            MongoDB::BSONElement obj = bsonObj[EntityRecord::staticUserLoc_fld()];
            if ( obj.isABSONObj() &&  obj.type() == mongo::Array)
            {
                std::vector<MongoDB::BSONElement> userLocs = obj.Array();
                for (std::vector<MongoDB::BSONElement>::iterator iter = userLocs.begin();
                    iter != userLocs.end(); iter++)
                {
                    MongoDB::BSONObj innerObj = iter->Obj();
                    StaticUserLoc userLoc;
                    if (innerObj.hasField(EntityRecord::staticUserLocEvent_fld()))
                        userLoc.event = innerObj.getStringField(EntityRecord::staticUserLocEvent_fld());
                    if (innerObj.hasField(EntityRecord::staticUserLocContact_fld()))
                        userLoc.contact = innerObj.getStringField(EntityRecord::staticUserLocContact_fld());
                    if (innerObj.hasField(EntityRecord::staticUserLocFromUri_fld()))
                        userLoc.fromUri = innerObj.getStringField(EntityRecord::staticUserLocFromUri_fld());
                    if (innerObj.hasField(EntityRecord::staticUserLocToUri_fld()))
                        userLoc.toUri = innerObj.getStringField(EntityRecord::staticUserLocToUri_fld());
                    if (innerObj.hasField(EntityRecord::staticUserLocCallId_fld()))
                        userLoc.callId = innerObj.getStringField(EntityRecord::staticUserLocCallId_fld());
                    _staticUserLoc.push_back(userLoc);
                }
            }
        }
    }
    catch(std::exception& e)
    {
        OS_LOG_ERROR(FAC_ODBC, "MongoDB Exception: (EntityRecord::operator =(const MongoDB::BSONObj& bsonObj))" << e.what());
    }

    return *this;
}
Exemple #25
0
bool parseSource(const InputSource &source, OS_NAMESPACE_NAME::IXMLHandler *handler, InputSource *xsd)
{
    bool result = false;

    OS_NAMESPACE_NAME::scoped_ptr<SAX2XMLReader> parser(XMLReaderFactory::createXMLReader());

    try
    {
        if(handler != nullptr)
        {
            handler->setStopParser(false);
            parser->setContentHandler(handler->getImpl());
            parser->setErrorHandler(handler->getImpl());
        }

        if(xsd != nullptr)
        {
            // Carica lo schema
            Grammar *grammar = parser->loadGrammar(*xsd, Grammar::SchemaGrammarType, true);
            if(grammar == nullptr)
            {
                OS_NAMESPACE_NAME::String error = _S("Invalid xml schema");

                const XMLCh *id = xsd->getSystemId();
                if(id != nullptr)
                {
                    error += _S(", id=");
                    error += id;
                }

                OS_EXCEPTION(error.to_utf8());
            }
            else
            {
                // Abilita la validazione dello schema
                parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
                // Disabilita la validazione opzionale (solo se esiste la con dichiarazione DOCTYPE dello schema nell'xml)
                parser->setFeature(XMLUni::fgXercesDynamic, false);

                // Questi flag stranamente non sono abilitati di default, sono comunque necessari altrimenti la validazione fallisce...
                parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
                parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
            }
        }

        XMLPScanToken scanToken;
        if(parser->parseFirst(source, scanToken))
        {
            XMLPScanTokenScope scanTokenScope(parser.get(), scanToken);

            while(parser->getErrorCount() == 0)
            {
                if(handler != nullptr && handler->getStopParser())
                    break;

                if(parser->parseNext(scanToken) == false)
                    break;
            }

            result = parser->getErrorCount() == 0;
        }
    }
    catch(const XMLException &e)
    {
        OS_LOG_ERROR(e.getMessage());
    }
    catch(const SAXException &e)
    {
        OS_LOG_ERROR(e.getMessage());
    }
    catch(std::exception &e)
    {
        OS_LOG_ERROR(e.what());
    }
    catch(...)
    {
        OS_LOG_ERROR(OS_ERR_UNKNOWN(xml));
    }

    return result;
}
Exemple #26
0
void IDbConnection::logError(const String &sql, std::exception &e) const
{
	OS_ASSERTFALSE();

	OS_LOG_ERROR(e.what() + _S(" - DB: ") + getDatabase() + _S(" - Sql: ") + sql);
}
Exemple #27
0
void NTPClient::onTimeout(const boost::system::error_code &e, shared_ptr<ConnectionScope> scope)
{
    OS_LOG_ERROR(_S("Ntp timeout"));
    m_socket->close();
}
Exemple #28
0
void FeedViewer::onLoad()
{
	ViewerBase::onLoad();

	shared_ptr<XMLNode> root = getModuleDocument()->getRoot();
	OS_ASSERT(root != nullptr);

	// Ajax:
	// - Creo un controllo per contenere quanto sotto
	// - Chiamo un "isDirect" a livello di ModuleViewer, che restituisce un "true" se son puntato diretto.
	// - Se si, leggo il parametro "mode", se è "direct" restituisco il contenuto del controllo secco via transmit-buffer
	// - Qui dumpo una chiamata ad ajax passandogli l'url di me in direct mode
	String mode = _S("direct");  // Proprietà?
	mode = _S("ajax");
	
	shared_ptr<HtmlDiv> divData(OS_NEW HtmlDiv());

	String controlID = getInstance().toUTF16();
	if(controlID.empty())
	{
		controlID = _S("preview"); // Se il modulo è in preview, non ha un'ID di istanza. Ma un ID mi serve x forza per gli eventi.
		mode = _S("direct"); // Ajax non è supportato nell'anteprima, perchè non ho un id da referenziare secco per avere il contenuto in un secondo momento.
	}
	setID(controlID);

	if(mode == _S("ajax"))
	{
		// - Chiamo un "isDirect" a livello di ModuleViewer, che restituisce un "true" se son puntato diretto.
		// - Se si, leggo il parametro "mode", se è "direct" restituisco il contenuto del controllo secco via transmit-buffer
		if(getPage()->getRequest()->getUrlParam(_W("mode")) == _W("content"))
			mode = _S("content");
		else
			mode = _S("delayed");
	}

	if( (mode == _S("direct")) || (mode == _S("content")) )
	{	
		String url = root->getAttributeString(OS_MODULES_FEED_URL);
		bool showTitle = root->getAttributeBool(OS_MODULES_FEED_SHOWTITLE);
		bool showDescription = root->getAttributeBool(OS_MODULES_FEED_SHOWDESCRIPTION);
		bool showImage = root->getAttributeBool(OS_MODULES_FEED_SHOWIMAGE);
		int32 nItems = root->getAttributeInt32(OS_MODULES_FEED_NITEMS);
		String showItemDescription = root->getAttributeString(OS_MODULES_FEED_SHOWITEMDESCRIPTION);
		String templateModel = root->getAttributeString(OS_MODULES_FEED_TEMPLATEMODEL);
		String templateCustom = root->getAttributeString(OS_MODULES_FEED_TEMPLATECUSTOM);

		shared_ptr<XMLDocument> document(OS_NEW XMLDocument());
		shared_ptr<XMLStylesheet> transformer(OS_NEW XMLStylesheet());

		try
		{
			shared_ptr<boost::asio::io_service> service = getSession()->getService();

			String output;
			String error;

			String userAgent = Engine::getDefaultHttpUserAgent();	
			document->parseUrl(url.to_ascii(), userAgent, service, Engine::instance()->createTCPSocket(service, true, true));

			shared_ptr<XMLNode> rssRoot = document->getRoot();

			if(rssRoot == nullptr)
			{
				// Error reading RSS Feed.				
				error = _S("Feed reading error.");				
			}
			else
			{		
				// Aggiungo all'xml RSS le proprietà del modulo.
				rssRoot->setAttributeString(OS_MODULES_FEED_URL, url);
				rssRoot->setAttributeBool(OS_MODULES_FEED_SHOWTITLE, showTitle);
				rssRoot->setAttributeBool(OS_MODULES_FEED_SHOWDESCRIPTION, showDescription);
				rssRoot->setAttributeBool(OS_MODULES_FEED_SHOWIMAGE, showImage);
				rssRoot->setAttributeInt32(OS_MODULES_FEED_NITEMS, nItems);
				rssRoot->setAttributeString(OS_MODULES_FEED_SHOWITEMDESCRIPTION, showItemDescription);
				rssRoot->setAttributeString(OS_MODULES_FEED_TEMPLATEMODEL, templateModel);
				
				if(templateModel.empty())
				{
					shared_ptr<XMLStylesheet> stylesheet(OS_NEW XMLStylesheet());
					if(stylesheet->parseString(templateCustom))
					{
						// Inizializza le funzioni del template
						getPage()->initStylesheet(stylesheet);

						if(stylesheet->applyToString(document, output))
						{
							//getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(getPage()->parseBBCode(output, true, false, false, false))));
						}
						else
						{
							// Transformazione fallita.
							error = _S("Transformation failed.");
						}
					}
					else
					{
						// Template custom invalido.
						error = _S("Invalid custom template.");
					}
				}
				else
				{
					shared_ptr<XMLStylesheet> stylesheet(OS_NEW XMLStylesheet());
					// Inizializza le funzioni del template
					getPage()->initStylesheet(stylesheet);

					String path = utils::makeFilePath(utils::makeFolderPath(g_componentsPath, _S("feed")), _S("feed_viewer_") + templateModel + _S(".xsl"));

					// Carica l'xsl
					if(stylesheet->parseFile(path))
					{
						if(stylesheet->applyToString(document, output))
						{
							// Qui potrei aggiungere un literal diretto, non parserizzato bb...
							//getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(getPage()->parseBBCode(output, true, false, false, false))));
						}
						else
						{
							// Transformazione fallita.
							error = _S("Transformation failed.");
						}
					}
					else
					{
						// Template non valido.
						error = _S("Invalid template.");
					}
				}

				if(output.empty() == true)
				{
					error = _S("Unknown error.");										
				}
			}

			if(error.empty() == false)
			{
				divData->setCss(_S("os_plugins_components_feed_error_reading"));
				divData->getControls()->add(shared_ptr<HtmlText>(OS_NEW HtmlText(error)));
			}
			else
			{
				divData->setCss(_S("os_plugins_components_feed_ok"));
				output = output.trim();
				//output = _S("[nobr]") + output + _S("[/nobr]");

				// Debugging
				//output = _S("[code]") + output + _S("[/code]") + output;
				
				divData->getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(getPage()->parseOml(output, true, false, false, omlRenderModeOsiris, getInstance().getString()))));
			}
		}
		catch(std::exception &e)
		{
			OS_LOG_ERROR(e.what());
		}	
	}

	if(mode == _S("direct"))
	{
		getControls()->add(divData);		
	}
	else if(mode == _S("delayed"))
	{
		String urlAjaxContent = getPage()->getPortal()->getViewObjectLink(getInstance()) + _S("&mode=content");
		divData->getControls()->add(shared_ptr<HtmlLiteral>(OS_NEW HtmlLiteral(_S("<div data-os-wait=\"center\" data-os-url=\"") + urlAjaxContent + _S("\"></div>"))));		
		getControls()->add(divData);		
	}
	else if(mode == _S("content"))
	{
		// trasmitbuffer solo di divData.
		HtmlWriter writer;
		divData->render(getPage(), writer);		
		
		getPage()->getSession()->transmitHtml(writer.getHtml().to_utf8(), httpStatusOK);
	}
}
Exemple #29
0
/*
shared_ptr<Portal> PortalsSystem::createPortal(shared_ptr<PortalOptions> options) // TOCLEAN
{
	options->setPortalID(PortalID::generate());

	
	Buffer public_key;
	Buffer private_key;

	// Genera la coppia di chiavi dell'amministratore
	if(CryptManager::instance()->rsaGenerateKeys(rsaType2048, private_key, public_key) == false)
		return false;
	

	//PortalAccess access = options->getPassword().empty() ? portalAccessPublic : portalAccessPrivate;
	//options->setPortalID(PortalID::generateAnarchic(access));
	

	
	if(options->getPortalID().empty())
		options->setPortalID(PortalID::generateAnarchic(access));
	
	if(options->getUserID().empty())
	{
		// Create account
		shared_ptr<IdeAccount> account = IdeAccountsManager::instance()->createAccount(OS_DEFAULT_ADMIN_USERNAME, OS_DEFAULT_ADMIN_PASSWORD, true);
		if(account == nullptr)
		{
			OS_LOG_ERROR("Cannot create account");
			return false;
		}

		Buffer publicKey;
		account->getAccount()->decodePublicKey(OS_DEFAULT_ADMIN_PASSWORD, publicKey);
		options->setUserID(DataAccount::getReferenceUser(publicKey));
	}
	
			
	shared_ptr<Portal> portal = subscribePortal(options);
	if(portal == nullptr)
	{
		OS_LOG_ERROR("Cannot create portal");
		return nullptr;
	}

	return portal;
}
*/
shared_ptr<Portal> PortalsSystem::subscribePortal(shared_ptr<PortalOptions> options)
{
	OS_LOCK(m_cs);

	if(options == nullptr)
	{
		OS_ASSERTFALSE();
		return nullptr;
	}

	PortalID id = options->getPortalID();
	if(id.empty())
	{
		id = PortalID::generate();		
		options->setPortalID(id);
	}

	PovID pov = options->getPovID();
	if(pov.empty())
		return nullptr;
	
	//if(id.getType() != ID::idPortal || id.validate(false) == false)
	//	return nullptr;

	String fullPov = Portal::generatePovID(id, pov);

	if(getPortal(id, pov) != nullptr)
		return nullptr;

	if(options->getDatabaseName().empty())
		options->setDatabaseName(fullPov);

	if(options->validate() == false)
		return nullptr;

	String folder = utils::standardisePath(getPath() + fullPov);

	if(FileSystem::instance()->exists(folder))
	{
		OS_LOG_ERROR(String::format(_S("Folder '%S' already exists").c_str(), folder.c_str()));
		return nullptr;
	}

	// Assicura che la root dei portali esista
	FileSystem::instance()->createDirectory(getPath());
	// Crea la root del portale
	if(FileSystem::instance()->createDirectory(folder) == false)
	{
		OS_LOG_ERROR(String::format(_S("Cannot create folder '%S'").c_str(), folder.c_str()));
		return nullptr;
	}

	// Crea il portale
	if(_setupPortal(options, folder) == false)
	{
		FileSystem::instance()->removeDirectory(folder);
		return nullptr;
	}

	return _loadPortal(folder, false, true);
}
Exemple #30
0
bool ExtensionsExtension::init(const ExtensionID &id, const Path &path)
{
	OS_ASSERT(path.empty() == false);
	OS_ASSERT(m_path.empty());

	m_path = path;

	//String filename = utils::makeFilePath(path, id.toUTF16() + ".xml"); // 0.13
	String filename = utils::makeFilePath(path, OS_MANIFESTXML); // 0.14
	if(FileSystem::instance()->fileExists(filename) == false)
		return false;
	
	shared_ptr<XMLDocument> document(OS_NEW XMLDocument(XMLSchema::fromFile(utils::makeFilePath(utils::makeFolderPath(Options::instance()->getSharePath(), OS_SCHEMAS_PATH), OS_EXTENSIONS_EXTENSION_SCHEMA))));
	if(document->parseFile(filename) == false)
		return false;

	String languagesPath = utils::makeFolderPath(path.path(), OS_LANGUAGES_PATH);
	if(FileSystem::instance()->directoryExists(languagesPath))
	{
		m_languageFolder.reset(OS_NEW LanguageFolder());
		m_languageFolder->addPath(languagesPath);
	}

	String htdocsPath = utils::makeFolderPath(path.path(), OS_HTDOCS_PATH);
	if(FileSystem::instance()->directoryExists(htdocsPath))
	{
		// TODO: Qui dovrei fare un'opzione a livello di xml extension, che stabilisce il nome della virtual-directory. Se omesso, è l'ID.
		// Per ora, forzo l'unico caso in cui mi servirebbe.
		String virtualName = id.toUTF16();
		if(id.toUTF16() == OS_EXTENSIONS_CORE)
			virtualName = OS_HTDOCS_PATH;

		m_httpDirectory.reset(OS_NEW HttpPhysicalDirectory(virtualName, htdocsPath));
	}

	// Auto-discovery IdeSkinSimple
	String skinsPath = utils::makeFolderPath(path.path(), "skins");
	{
		if(FileSystem::instance()->directoryExists(skinsPath))
		{
			StringList skins;
			FileSystem::instance()->getFiles(skinsPath, skins, false);
			for(StringList::const_iterator i = skins.begin(); i != skins.end(); ++i)
			{
				String config = "/skins/" + *i;
				String title = FileSystem::instance()->getFileTitle(*i);
				shared_ptr<IdeSkinSimple> skin(OS_NEW IdeSkinSimple());
				if(skin->init(get_this_ptr(), config, title))
					m_skins.push_back(skin);
			}
		}
	}

	shared_ptr<XMLNode> root = document->getRoot();

	if(root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_ID) != id.getString()) // Ensure that the directory name is equal to ID.
		return false;

	m_id = id;
	m_name = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_NAME);	
	m_description = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_DESCRIPTION);
	m_content = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_CONTENT);
	m_category = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_CATEGORY);
	m_tags = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_TAGS);
	m_trust = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_TRUST);
	m_author = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_AUTHOR);
	m_versionCode = root->getAttributeInt32(OS_EXTENSION_XML_NODE_ROOT_VERSION_CODE);
	m_versionName = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_VERSION_NAME);
	m_compatibility = root->getAttributeInt32(OS_EXTENSION_XML_NODE_ROOT_COMPATIBILITY);
	/*
	if(m_version.fromString(root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_VERSION).to_ascii()) == false)
		return false;
	String compatibility = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_COMPATIBILITY);
	if( (compatibility.empty() == false) && (m_compatibility.fromString(compatibility.to_ascii()) == false) )
		return false;
	*/
	m_homepage = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_HOMEPAGE);
	m_icon = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_ICON);
	m_logo = root->getAttributeString(OS_EXTENSION_XML_NODE_ROOT_LOGO);
	
	NotificationsManager::instance()->notify(_S("Loading extension: ") + m_name);
	
	shared_ptr<XMLNode> nodeFiles = document->getRoot()->getNode(OS_EXTENSION_XML_NODE_SCRIPTS);
	if(nodeFiles != nullptr)
	{
		shared_ptr<XMLNodes> files = nodeFiles->getNodes();
		for(XMLNodes::const_iterator i = files->begin(); i != files->end(); ++i)
		{
			String scriptPath = utils::makeFilePath(path, (*i)->getAttributeString(OS_EXTENSION_XML_NODE_SCRIPT_PATH));
			String scriptLanguage = (*i)->getAttributeString(OS_EXTENSION_XML_NODE_SCRIPT_LANGUAGE);

			shared_ptr<IExtensionsCodeProvider> codeProvider = ExtensionsSystem::instance()->getCodeProvider(scriptLanguage);
			if(codeProvider == nullptr)
			{
				OS_LOG_ERROR(_S("Invalid script language '") + scriptLanguage + _S("'"));
				return false;
			}

			shared_ptr<IExtensionsCodeContext> context = codeProvider->createContext();
			if(context == nullptr)
			{
				OS_LOG_ERROR(_S("Cannot create context for script language '") + scriptLanguage + _S("'"));
				return false;
			}

			if(context->parseFile(scriptPath))
				m_contexts.push_back(context);				
			else
				OS_LOG_ERROR(_S("Cannot parse extension file '") + scriptPath + _S("'"));
		}
	}
	
	return true;
}