/**
 * @fn editTaskPrivate
 */
QueuedResult<bool> QueuedCorePrivateHelper::editTaskPrivate(QueuedProcess *_process,
                                                            const QVariantHash &_taskData,
                                                            const int _userId)
{
    qCDebug(LOG_LIB) << "Edit task with ID" << _process->index() << "from" << _userId;

    // modify record in database first
    bool status = database()->modify(QueuedDB::TASKS_TABLE, _process->index(), _taskData);
    if (!status) {
        qCWarning(LOG_LIB) << "Could not modify task record" << _process->index()
                           << "in database, do not edit it in memory";
        return QueuedError("", QueuedEnums::ReturnStatus::Error);
    }
    // store modification
    for (auto &field : _taskData.keys())
        database()->add(QueuedDB::TASKS_MODS_TABLE,
                        {{"task", _process->index()},
                         {"time", QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)},
                         {"user", _userId},
                         {"field", field},
                         {"value", _taskData[field]}});

    // modify values stored in memory
    for (auto &property : _taskData.keys())
        _process->setProperty(qPrintable(property), _taskData[property]);
    // notify plugins
    if (plugins())
        emit(plugins()->interface()->onEditTask(_process->index(), _taskData));

    return true;
}
FormGenAcceptResult FormGenRecordComposition::acceptsValueImpl(const QVariant &val) const
{
    if( variantType(val) != QMetaType::QVariantHash )
        return FormGenAcceptResult::reject({}, val);

    QVariantHash hash = val.toHash();
    QStringList valueStringList;
    QSet<QString> processedTags;

    for( const auto &elm : mElements ) {
        auto elementAccepts = elm.element->acceptsValue(hash.value(elm.tag));
        if( ! elementAccepts.acceptable ) {
            QString path = elm.tag;
            if( ! elementAccepts.path.isEmpty() )
                path += QString("/%1").arg(elementAccepts.path);
            return FormGenAcceptResult::reject(path, elementAccepts.value);
        }
        valueStringList.append(FormGenElement::keyStringValuePair(elm.tag, elementAccepts.valueString));
        processedTags.insert(elm.tag);
    }

    QSet<QString> remainingTags = hash.keys().toSet() - processedTags;
    if( ! remainingTags.isEmpty() )
        return FormGenAcceptResult::reject(*remainingTags.cbegin(),
                                           hash.value(*remainingTags.cbegin()));

    return FormGenAcceptResult::accept(val, FormGenElement::objectString(valueStringList));
}
示例#3
0
void ImageUploader::saveSettings(const QString &uploaderType, const QVariantHash &settings) {
    auto globalSettings = ScreenshotManager::instance()->settings();
    globalSettings->beginGroup("upload/" + uploaderType);

    for (auto key : settings.keys()) {
        globalSettings->setValue(key, settings[key]);
    }

    globalSettings->endGroup();
}
/**
 * @fn dropAdminFields
 */
QVariantHash QueuedCorePrivateHelper::dropAdminFields(const QString &_table,
                                                      const QVariantHash &_payload)
{
    qCDebug(LOG_LIB) << "Drop admin fields from" << _payload << "in table" << _table;

    QVariantHash payload;
    for (auto &key : _payload.keys()) {
        if (QueuedDB::DBSchema[_table][key].adminField)
            continue;
        payload[key] = _payload[key];
    }

    return payload;
}
示例#5
0
/**
 * @fn loadPlugin
 */
bool QueuedPluginManager::loadPlugin(const QString &_name, const QVariantHash &_settings)
{
    qCDebug(LOG_PL) << "Load plugin" << _name << "with settings" << _settings;

    // check if it was loaded already then call QueuedPluginInterface::init()
    if (m_plugins.contains(_name)) {
        m_plugins[_name]->init(_settings);
        m_plugins[_name]->setToken(m_token);
        return true;
    }

    // normal load
    QString libraryName = QString("lib%2.so").arg(_name);
    // init plugin settings with valid keys
    QVariantHash pluginSettings;
    for (auto &key : _settings.keys())
        pluginSettings[convertOptionName(key).first] = _settings[key];

    for (auto &dir : pluginLocations()) {
        if (!QDir(dir).entryList(QDir::Files).contains(libraryName))
            continue;
        // build plugin loader
        QPluginLoader loader(QString("%1/%2").arg(dir).arg(libraryName), this);
        qCInfo(LOG_PL) << "Loading" << loader.fileName();
        // load plugin
        QObject *plugin = loader.instance();
        QueuedPluginInterface *item = nullptr;
        if (loader.isLoaded())
            item = qobject_cast<QueuedPluginInterface *>(plugin);
        else
            qCCritical(LOG_PL) << "Could not load the library for" << _name << "error"
                               << loader.errorString();
        if (item) {
            m_plugins[_name] = item;
            item->init(pluginSettings);
            item->setToken(m_token);
            item->setup(interface());
        } else {
            qCCritical(LOG_PL) << "Could not cast plugin" << _name;
        }
        // do not try to load it from other paths
        break;
    }

    return m_plugins.contains(_name);
}
bool RegisterFileTypeOperation::undoOperation()
{
#ifdef Q_OS_WIN
    ensureOptionalArgumentsRead();
    QStringList args = arguments();

    if (!checkArgumentCount(2, 5, tr("Register File Type: Invalid arguments")))
        return false;

    bool allUsers = false;
    PackageManagerCore *const core = packageManager();
    if (core && core->value(scAllUsers) == scTrue)
        allUsers = true;

    QSettingsWrapper settings(QLatin1String(allUsers ? "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER")
        , QSettingsWrapper::NativeFormat);

    const QString classesProgId = QString::fromLatin1("Software/Classes/") + m_progId;
    const QString classesFileType = QString::fromLatin1("Software/Classes/.%2").arg(args.at(0));
    const QString classesApplications = QString::fromLatin1("Software/Classes/Applications/") + m_progId;

    // Quoting MSDN here: When uninstalling an application, the ProgIDs and most other registry information
    // associated with that application should be deleted as part of the uninstallation.However, applications
    // that have taken ownership of a file type (by setting the Default value of the file type's
    // HKEY...\.extension subkey to the ProgID of the application) should not attempt to remove that value
    // when uninstalling. Leaving the data in place for the Default value avoids the difficulty of
    // determining whether another application has taken ownership of the file type and overwritten the
    // Default value after the original application was installed. Windows respects the Default value only
    // if the ProgID found there is a registered ProgID. If the ProgID is unregistered, it is ignored.

    // if the hive didn't change since we touched it
    if (value(QLatin1String("newType")).toHash() == readHive(&settings, classesFileType)) {
        // reset to the values we found
        settings.remove(classesFileType);
        settings.beginGroup(classesFileType);
        const QVariantHash keyValues = value(QLatin1String("oldType")).toHash();
        foreach (const QString &key, keyValues.keys())
            settings.setValue(key, keyValues.value(key));
        settings.endGroup();
    } else {
/**
 * @fn editUserPrivate
 */
QueuedResult<bool> QueuedCorePrivateHelper::editUserPrivate(QueuedUser *_user,
                                                            const QVariantHash &_userData)
{
    qCDebug(LOG_LIB) << "Edit user with ID" << _user->index();

    // modify record in database first
    bool status = database()->modify(QueuedDB::USERS_TABLE, _user->index(), _userData);
    if (!status) {
        qCWarning(LOG_LIB) << "Could not modify user record" << _user->index()
                           << "in database, do not edit it in memory";
        return QueuedError("", QueuedEnums::ReturnStatus::Error);
    }

    // modify values stored in memory
    for (auto &property : _userData.keys())
        _user->setProperty(qPrintable(property), _userData[property]);
    // notify plugins
    if (plugins())
        emit(plugins()->interface()->onEditUser(_user->index(), _userData));

    return true;
}
示例#8
0
qint64 HistoryManager::getRecord(const QLatin1String &table, const QVariantHash &values)
{
	const QStringList keys = values.keys();
	QStringList placeholders;

	for (int i = 0; i < keys.count(); ++i)
	{
		placeholders.append(QString('?'));
	}

	QSqlQuery selectQuery(QSqlDatabase::database(QLatin1String("browsingHistory")));
	selectQuery.prepare(QStringLiteral("SELECT \"id\" FROM \"%1\" WHERE \"%2\" = ?;").arg(table).arg(keys.join(QLatin1String("\" = ? AND \""))));

	for (int i = 0; i < keys.count(); ++i)
	{
		selectQuery.bindValue(i, values[keys.at(i)]);
	}

	selectQuery.exec();

	if (selectQuery.first())
	{
		return selectQuery.record().field(QLatin1String("id")).value().toLongLong();
	}

	QSqlQuery insertQuery(QSqlDatabase::database(QLatin1String("browsingHistory")));
	insertQuery.prepare(QStringLiteral("INSERT INTO \"%1\" (\"%2\") VALUES(%3);").arg(table).arg(keys.join(QLatin1String("\", \""))).arg(placeholders.join(QLatin1String(", "))));

	for (int i = 0; i < keys.count(); ++i)
	{
		insertQuery.bindValue(i, values[keys.at(i)]);
	}

	insertQuery.exec();

	return insertQuery.lastInsertId().toULongLong();
}
示例#9
0
void WebPage::saveSettings()
{
    QVariantHash config = m_config->saveSettings();
    for (auto key : config.keys())
        m_configuration[key] = config[key];
}
/*!
  Validates the specified parameter \a hash by the set rules.
  
  As default, TF::Required is set for all parameters. If not required, 
  set the rule to \a false like this:
    setRule("xxx", Tf::Required, false);
 */
bool TFormValidator::validate(const QVariantHash &hash)
{
    errors.clear();

    // Add default rules, Tf::Required.
    QString msg = Tf::app()->validationErrorMessage(Tf::Required);
    for (QStringListIterator i(hash.keys()); i.hasNext(); ) {
        const QString &k = i.next();
        if (!containsRule(k, Tf::Required)) {
            rules.append(RuleEntry(k, (int)Tf::Required, true, msg));
        }
    }

    for (QListIterator<RuleEntry> i(rules); i.hasNext(); ) {
        const RuleEntry &r = i.next();
        QString str = hash.value(r.key).toString();  // value string

        if (str.isEmpty()) {
            bool req = r.value.toBool();
            if (r.rule == Tf::Required && req) {
                tSystemDebug("validation error: required parameter is empty, key:%s", qPrintable(r.key)); 
                errors << qMakePair(r.key, r.rule);
            }
        } else {
            bool ok1, ok2;
            tSystemDebug("validating key:%s value: %s", qPrintable(r.key), qPrintable(str)); 
            switch (r.rule) {
            case Tf::Required:
                break;

            case Tf::MaxLength: {
                int max = r.value.toInt(&ok2);
                if (!ok2 || str.length() > max) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::MinLength: {
                int min = r.value.toInt(&ok2);
                if (!ok2 || str.length() < min) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::IntMax: {
                qint64 n = str.toLongLong(&ok1);
                qint64 max = r.value.toLongLong(&ok2);
                if (!ok1 || !ok2 || n > max) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::IntMin: {
                qint64 n = str.toLongLong(&ok1);
                qint64 min = r.value.toLongLong(&ok2);
                if (!ok1 || !ok2  || n < min) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::DoubleMax: {
                double n = str.toDouble(&ok1);
                double max = r.value.toLongLong(&ok2);
                if (!ok1 || !ok2 || n > max) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            case Tf::DoubleMin: {
                double n = str.toDouble(&ok1);
                double min = r.value.toDouble(&ok2);
                if (!ok1 || !ok2 || n < min) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }
                
            case Tf::EmailAddress: { // refer to RFC5321
                if ( r.value.toBool() ) {
                    QRegExp reg("^" ADDR_SPEC "$");
                    if (!reg.exactMatch(str)) {
                        errors << qMakePair(r.key, r.rule);
                    }
                }
                break; }

            case Tf::Url: {
                if ( r.value.toBool() ) {
                    QUrl url(str, QUrl::StrictMode);
                    if (!url.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                    }
                }
                break; }

            case Tf::Date: {
                if ( r.value.toBool() ) {
                    QDate date = QLocale().toDate(str, dateFormat());
                    if (!date.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                        tSystemDebug("Validation error: Date format: %s", qPrintable(dateFormat()));
                    }
                }
                break; }

            case Tf::Time: {
                if ( r.value.toBool() ) {
                    QTime time = QLocale().toTime(str, timeFormat());
                    if (!time.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                        tSystemDebug("Validation error: Time format: %s", qPrintable(timeFormat()));
                    }
                }
                break; }

            case Tf::DateTime: {
                if ( r.value.toBool() ) {
                    QDateTime dt = QLocale().toDateTime(str, dateTimeFormat());
                    if (!dt.isValid()) {
                        errors << qMakePair(r.key, r.rule);
                        tSystemDebug("Validation error: DateTime format: %s", qPrintable(dateTimeFormat()));
                    }
                }
                break; }

            case Tf::Pattern: {
                QRegExp rx = r.value.toRegExp();
                if (rx.isEmpty() || !rx.exactMatch(str)) {
                    errors << qMakePair(r.key, r.rule);
                }
                break; }

            default:
                tSystemError("Internal Error, invalid rule: %d  [%s:%d]", r.rule, __FILE__, __LINE__);
                break;
            }
        }
    }
    return errors.isEmpty();
}