Beispiel #1
0
bool AttentionPlugin::outgoingStanza(int /*account*/, QDomElement& xml) {
    if(enabled) {
        if(xml.tagName() == "iq" && xml.attribute("type") == "result")
        {
            QDomNodeList list = xml.elementsByTagNameNS("http://jabber.org/protocol/disco#info", "query");
            if(!list.isEmpty())
            {
                QDomElement query = list.at(0).toElement();
                if(!query.hasAttribute("node")) {
                    QDomDocument doc = xml.ownerDocument();
                    QDomElement feature = doc.createElement("feature");
                    feature.setAttribute("var", "urn:xmpp:attention:0");
                    query.appendChild(feature);
                }
            }
        }
        else if(xml.tagName() == "presence")
        {
            QDomNodeList list = xml.elementsByTagNameNS("http://jabber.org/protocol/caps", "c");
            if(!list.isEmpty())
            {
                QDomElement c = list.at(0).toElement();
                if(c.hasAttribute("ext")) {
                    QString ext = c.attribute("ext");
                    ext += " at-pl";
                    c.setAttribute("ext", ext);
                }
            }
        }
    }
    return false;
}
Beispiel #2
0
void OwnCloudService::loadDirectory(QString &data) {
    QDomDocument doc;
    doc.setContent(data, true);

    if (data.isEmpty()) {
        showOwnCloudServerErrorMessage("", false);
    }

    QStringList pathList;
    QDomNodeList responseNodes = doc.elementsByTagNameNS(NS_DAV, "response");

    for (int i = 0; i < responseNodes.count(); i++) {
        QDomNode responseNode = responseNodes.at(i);
        if (responseNode.isElement()) {
            QDomElement elem = responseNode.toElement();

            bool isFolder = false;
            QDomNodeList resourceTypeNodes =
                    elem.elementsByTagNameNS(NS_DAV, "resourcetype");
            if (resourceTypeNodes.length()) {
                QDomNodeList typeNodes = resourceTypeNodes.at(0).childNodes();
                for (int j = 0; j < typeNodes.length(); ++j) {
                    QDomNode typeNode = typeNodes.at(j);
                    QString typeString = typeNode.toElement().tagName();

                    if (typeString == "collection") {
                        isFolder = true;
                        break;
                    }
                }
            }

            if (!isFolder) {
                continue;
            }

            // check if we have an url
            QDomNodeList urlPartNodes = elem.elementsByTagNameNS(NS_DAV,
                                                                 "href");
            if (urlPartNodes.length()) {
                QString urlPart = urlPartNodes.at(0).toElement().text();

                QRegularExpression re(
                    QRegularExpression::escape(webdavPath) + "\\/(.+)\\/$");

                QRegularExpressionMatch match = re.match(urlPart);
                QString folderString =
                        match.hasMatch() ? match.captured(1) : "";

                if (!folderString.isEmpty()) {
                    pathList << QUrl::fromPercentEncoding(
                            folderString.toUtf8());
                }
            }
        }
    }

    settingsDialog->setNoteFolderRemotePathList(pathList);
}
Beispiel #3
0
QStringList OwnCloudService::parseCalendarHrefList(QString &data) {
    QStringList resultList;
    QDomDocument doc;
    doc.setContent(data, true);

    // loop all response blocks
    QDomNodeList responseNodes = doc.elementsByTagNameNS(NS_DAV, "response");
    for (int i = 0; i < responseNodes.length(); ++i) {
        QDomNode responseNode = responseNodes.at(i);
        if (responseNode.isElement()) {
            QDomElement elem = responseNode.toElement();
            QDomNodeList resourceTypeNodes =
                    elem.elementsByTagNameNS(NS_DAV, "resourcetype");
            if (resourceTypeNodes.length()) {
                QDomNodeList typeNodes = resourceTypeNodes.at(0).childNodes();
                for (int j = 0; j < typeNodes.length(); ++j) {
                    QDomNode typeNode = typeNodes.at(j);
                    QString typeString = typeNode.toElement().tagName();

                    // did we find a calendar?
                    // ideally we should check the
                    // "supported-calendar-component-set" for "VTODO"
                    if (typeString == "calendar") {
                        // add the href to our result list
                        QDomNodeList hrefNodes = elem.elementsByTagNameNS(
                                NS_DAV, "href");
                        if (hrefNodes.length()) {
                            const QString href = hrefNodes.at(
                                    0).toElement().text();
                            resultList << href;
                        }

                        QDomNodeList displayNameNodes =
                                elem.elementsByTagNameNS(NS_DAV, "displayname");
                        if (displayNameNodes.length()) {
                            // TODO(pbek): we want to use this display name in
                            // the future!
                            const QString displayName = displayNameNodes.at(
                                    0).toElement().text();
                            qDebug() << __func__ << " - 'displayName': " <<
                            displayName;
                        }
                    }
                }
            }
        }
    }

    return resultList;
}
Beispiel #4
0
int CoreProtocol::getOldErrorCode(const QDomElement &e)
{
	QDomElement err = e.elementsByTagNameNS(NS_CLIENT, "error").item(0).toElement();
	if(err.isNull() || !err.hasAttribute("code"))
		return -1;
	return err.attribute("code").toInt();
}
Beispiel #5
0
QStringList QgsWFSProvider::insertedFeatureIds( const QDomDocument& serverResponse ) const
{
  QStringList ids;
  if ( serverResponse.isNull() )
  {
    return ids;
  }

  QDomElement rootElem = serverResponse.documentElement();
  if ( rootElem.isNull() )
  {
    return ids;
  }

  QDomNodeList insertResultList = rootElem.elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, "InsertResult" );
  for ( int i = 0; i < insertResultList.size(); ++i )
  {
    QDomNodeList featureIdList = insertResultList.at( i ).toElement().elementsByTagNameNS( QgsWFSConstants::OGC_NAMESPACE, "FeatureId" );
    for ( int j = 0; j < featureIdList.size(); ++j )
    {
      QString fidString = featureIdList.at( j ).toElement().attribute( "fid" );
      if ( !fidString.isEmpty() )
      {
        ids << fidString;
      }
    }
  }
  return ids;
}
Beispiel #6
0
bool QgsWFSProvider::transactionSuccess( const QDomDocument& serverResponse ) const
{
  if ( serverResponse.isNull() )
  {
    return false;
  }

  QDomElement documentElem = serverResponse.documentElement();
  if ( documentElem.isNull() )
  {
    return false;
  }

  QDomNodeList transactionResultList = documentElem.elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, "TransactionResult" );
  if ( transactionResultList.size() < 1 )
  {
    return false;
  }

  QDomNodeList statusList = transactionResultList.at( 0 ).toElement().elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, "Status" );
  if ( statusList.size() < 1 )
  {
    return false;
  }

  if ( statusList.at( 0 ).firstChildElement().localName() == "SUCCESS" )
  {
    return true;
  }
  else
  {
    return false;
  }
}
int QgsSOAPRequestHandler::parseGetMapElement( QMap<QString, QString>& parameterMap, const QDomElement& getMapElement ) const
{
  QDomNodeList boundingBoxList = getMapElement.elementsByTagName( "BoundingBox" );
  if ( !boundingBoxList.isEmpty() )
  {
    parseBoundingBoxElement( parameterMap, boundingBoxList.item( 0 ).toElement() );
  }
  QDomNodeList CRSList = getMapElement.elementsByTagName( "coordinateReferenceSystem" );
  if ( !CRSList.isEmpty() )
  {
    QString crsText = CRSList.item( 0 ).toElement().text();
    QString epsgNumber;
    if ( !crsText.startsWith( "EPSG_" ) ) //use underscore in SOAP because ':' is reserved for namespaces
    {
      //error
    }
    else
    {
      epsgNumber = crsText.replace( 4, 1, ":" );//replace the underscore with a ':' to make it WMS compatible
    }
    parameterMap.insert( "CRS", epsgNumber );
  }
  QDomNodeList GMLList = getMapElement.elementsByTagNameNS( "http://www.eu-orchestra.org/services/ms", "GML" );
  if ( !GMLList.isEmpty() )
  {
    QString gmlText;
    QTextStream gmlStream( &gmlText );
    GMLList.at( 0 ).save( gmlStream, 2 );
    parameterMap.insert( "GML", gmlText );
  }

  //outputAttributes
  QDomNodeList imageDocumentAttributesList = getMapElement.elementsByTagName( "Output" );
  if ( !imageDocumentAttributesList.isEmpty() )
  {
    parseOutputAttributesElement( parameterMap, imageDocumentAttributesList.item( 0 ).toElement() );
  }

  //SLD
  QDomNodeList sldList = getMapElement.elementsByTagName( "StyledLayerDescriptor" );
  if ( !sldList.isEmpty() )
  {
    QString sldString;
    QTextStream sldStream( &sldString );
    sldList.item( 0 ).save( sldStream, 0 );
    //Replace some special characters
    sldString.replace( "&lt;", "<" );
    sldString.replace( "&gt;", ">" );
    parameterMap.insert( "SLD", sldString );
  }

  return 0;
}
Beispiel #8
0
bool WebdavHandler::extractStringList( const QDomElement &node, const QString &entry, QStringList &value )
{
  QDomElement element = node.namedItem( entry ).toElement();
  if ( !element.isNull() ) {
    value.clear();
    QDomNodeList list = element.elementsByTagNameNS( "xml:", "v" );
    for( uint i=0; i < list.count(); i++ ) {
      QDomElement item = list.item(i).toElement();
      value.append( item.text() );
    }
    return true;
  }
  return false;
}
Beispiel #9
0
void BasicProtocol::extractStreamError(const QDomElement &e)
{
	QString text;
	QDomElement appSpec;

	QDomElement t = firstChildElement(e);
	if(t.isNull() || t.namespaceURI() != NS_STREAMS) {
		// probably old-style error
		errCond = -1;
		errText = e.text();
	}
	else
		errCond = stringToStreamCond(t.tagName());

	if(errCond != -1) {
		if(errCond == SeeOtherHost)
			otherHost = t.text();

		t = e.elementsByTagNameNS(NS_STREAMS, "text").item(0).toElement();
		if(!t.isNull())
			text = t.text();

		// find first non-standard namespaced element
		QDomNodeList nl = e.childNodes();
		for(int n = 0; n < nl.count(); ++n) {
			QDomNode i = nl.item(n);
			if(i.isElement() && i.namespaceURI() != NS_STREAMS) {
				appSpec = i.toElement();
				break;
			}
		}

		errText = text;
		errAppSpec = appSpec;
	}
}
Beispiel #10
0
int QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, QString& geometryAttribute, QgsFields& fields, QGis::WkbType& geomType )
{
  //get the <schema> root element
  QDomNodeList schemaNodeList = schemaDoc.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "schema" );
  if ( schemaNodeList.length() < 1 )
  {
    return 1;
  }
  QDomElement schemaElement = schemaNodeList.at( 0 ).toElement();
  mApplicationNamespace = schemaElement.attribute( "targetNamespace" );
  QDomElement complexTypeElement; //the <complexType> element corresponding to the feature type

  //find out, on which lines the first <element> or the first <complexType> occur. If <element> occurs first (mapserver), read the type of the relevant <complexType> tag. If <complexType> occurs first (geoserver), search for information about the feature type directly under this first complexType element

  int firstElementTagPos = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" ).at( 0 ).toElement().columnNumber();
  int firstComplexTypeTagPos = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "complexType" ).at( 0 ).toElement().columnNumber();

  if ( firstComplexTypeTagPos < firstElementTagPos )
  {
    //geoserver
    complexTypeElement = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "complexType" ).at( 0 ).toElement();
  }
  else
  {
    //UMN mapserver
    QString complexTypeType;
    QDomNodeList typeElementNodeList = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" );
    QDomElement typeElement = typeElementNodeList.at( 0 ).toElement();
    complexTypeType = typeElement.attribute( "type" );

    if ( complexTypeType.isEmpty() )
    {
      return 3;
    }

    //remove the namespace on complexTypeType
    if ( complexTypeType.contains( ':' ) )
    {
      complexTypeType = complexTypeType.section( ':', 1, 1 );
    }

    //find <complexType name=complexTypeType
    QDomNodeList complexTypeNodeList = schemaElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "complexType" );
    for ( int i = 0; i < complexTypeNodeList.size(); ++i )
    {
      if ( complexTypeNodeList.at( i ).toElement().attribute( "name" ) == complexTypeType )
      {
        complexTypeElement = complexTypeNodeList.at( i ).toElement();
        break;
      }
    }
  }

  if ( complexTypeElement.isNull() )
  {
    return 4;
  }

  //we have the relevant <complexType> element. Now find out the geometry and the thematic attributes
  QDomNodeList attributeNodeList = complexTypeElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" );
  if ( attributeNodeList.size() < 1 )
  {
    return 5;
  }

  bool foundGeometryAttribute = false;

  for ( int i = 0; i < attributeNodeList.size(); ++i )
  {
    QDomElement attributeElement = attributeNodeList.at( i ).toElement();
    //attribute name
    QString name = attributeElement.attribute( "name" );
    //attribute type
    QString type = attributeElement.attribute( "type" );

    //is it a geometry attribute?
    //MH 090428: sometimes the <element> tags for geometry attributes have only attribute ref="gml:polygonProperty" and no name
    QRegExp gmlPT( "gml:(.*)PropertyType" );
    // the GeometryAssociationType has been seen in #11785
    if ( type.indexOf( gmlPT ) == 0 || type == "gml:GeometryAssociationType" || name.isEmpty() )
    {
      foundGeometryAttribute = true;
      geometryAttribute = name;
      geomType = geomTypeFromPropertyType( geometryAttribute, gmlPT.cap( 1 ) );
    }
    else //todo: distinguish between numerical and non-numerical types
    {
      QVariant::Type  attributeType = QVariant::String; //string is default type
      if ( type.contains( "double", Qt::CaseInsensitive ) || type.contains( "float", Qt::CaseInsensitive ) || type.contains( "decimal", Qt::CaseInsensitive ) )
      {
        attributeType = QVariant::Double;
      }
      else if ( type.contains( "int", Qt::CaseInsensitive ) )
      {
        attributeType = QVariant::Int;
      }
      else if ( type.contains( "long", Qt::CaseInsensitive ) )
      {
        attributeType = QVariant::LongLong;
      }
      fields.append( QgsField( name, attributeType, type ) );
    }
  }
  if ( !foundGeometryAttribute )
  {
    geomType = QGis::WKBNoGeometry;
  }

  return 0;
}
Beispiel #11
0
void RSSEditPopup::slotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    bool download;
    if (m_download->GetCheckState() == MythUIStateType::Full)
        download = true;
    else
        download = false;

    VERBOSE(VB_GENERAL|VB_EXTRA, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull ())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL = channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd", "image");
            if (nodes.size())
            {
                thumbnailURL = nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = QDateTime::currentDateTime();
        QString filename("");

        if (file.isEmpty())
            filename = file;

        QString link = m_urlEdit->GetText();

        if (!thumbnailURL.isEmpty() && filename.isEmpty())
        {
            QString fileprefix = GetConfDir();

            QDir dir(fileprefix);
            if (!dir.exists())
                    dir.mkdir(fileprefix);

            fileprefix += "/MythNetvision";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            fileprefix += "/sitecovers";

            dir = QDir(fileprefix);
            if (!dir.exists())
                dir.mkdir(fileprefix);

            QFileInfo fi(thumbnailURL);
            QString rawFilename = fi.fileName();

            filename = QString("%1/%2").arg(fileprefix).arg(rawFilename);

            bool exists = QFile::exists(filename);
            if (!exists)
                HttpComms::getHttpFile(filename, thumbnailURL, 20000, 1, 2);
        }
        if (insertInDB(new RSSSite(title, filename, VIDEO_PODCAST, description, link,
                author, download, QDateTime::currentDateTime())))
            emit saving();
    }
    Close();
}
Beispiel #12
0
void QgsWFSCapabilities::capabilitiesReplyFinished()
{
  QNetworkReply *reply = mCapabilitiesReply;
  reply->deleteLater();
  mCapabilitiesReply = 0;

  // handle network errors
  if ( reply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSCapabilities::NetworkError;
    mErrorMessage = reply->errorString();
    emit gotCapabilities();
    return;
  }

  // handle HTTP redirects
  QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
  if ( !redirect.isNull() )
  {
    QgsDebugMsg( "redirecting to " + redirect.toUrl().toString() );
    QNetworkRequest request( redirect.toUrl() );
    setAuthorization( request );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );

    connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
    return;
  }

  QByteArray buffer = reply->readAll();

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWFSCapabilities::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // hangle exceptions
  if ( doc.tagName() == "ExceptionReport" )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWFSCapabilities::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  //test wfs version
  QString version = capabilitiesDocument.documentElement().attribute( "version" );
  if ( version != "1.0.0" && version != "1.0" )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "Either the WFS server does not support WFS version 1.0.0 or the WFS url is wrong" );
    emit gotCapabilities();
    return;
  }

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = capabilitiesDocument.elementsByTagNameNS( WFS_NAMESPACE, "FeatureType" );
  for ( unsigned int i = 0; i < featureTypeList.length(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Abstract" );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "DefaultSRS" );
    if ( defaultCRSList.length() > 0 )
    {
      featureType.crslist.append( defaultCRSList.at( 0 ).toElement().text() );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "OtherSRS" );
    for ( unsigned int i = 0; i < otherCRSList.length(); ++i )
    {
      featureType.crslist.append( otherCRSList.at( i ).toElement().text() );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "SRS" );
    for ( unsigned int i = 0; i < srsList.length(); ++i )
    {
      featureType.crslist.append( srsList.at( i ).toElement().text() );
    }

    mCaps.featureTypes.append( featureType );
  }

  emit gotCapabilities();
}
Beispiel #13
0
  QDomDocument createTransactionDocument( QgsServerInterface* serverIface, const QString& version,
                                          const QgsServerRequest& request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsWfsProjectParser* configParser = getConfigParser( serverIface );
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl* accessControl = serverIface->accessControls();
#endif
    const QString requestBody = request.getParameter( QStringLiteral( "REQUEST_BODY" ) );

    QString errorMsg;
    if ( !doc.setContent( requestBody, true, &errorMsg ) )
    {
      throw QgsRequestNotWellFormedException( errorMsg );
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList docChildNodes = docElem.childNodes();

    // Re-organize the transaction document
    QDomDocument mDoc;
    QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) );
    mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    mDoc.appendChild( mDocElem );

    QDomElement actionElem;
    QString actionName;
    QDomElement typeNameElem;
    QString typeName;

    for ( int i = docChildNodes.count(); 0 < i; --i )
    {
      actionElem = docChildNodes.at( i - 1 ).toElement();
      actionName = actionElem.localName();

      if ( actionName == QLatin1String( "Insert" ) )
      {
        QDomElement featureElem = actionElem.firstChild().toElement();
        typeName = featureElem.localName();
      }
      else if ( actionName == QLatin1String( "Update" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }
      else if ( actionName == QLatin1String( "Delete" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }

      if ( typeName.contains( QLatin1String( ":" ) ) )
        typeName = typeName.section( QStringLiteral( ":" ), 1, 1 );

      QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName );
      if ( typeNameList.count() == 0 )
      {
        typeNameElem = mDoc.createElement( typeName );
        mDocElem.appendChild( typeNameElem );
      }
      else
        typeNameElem = typeNameList.at( 0 ).toElement();

      typeNameElem.appendChild( actionElem );
    }

    // It's time to make the transaction
    // Create the response document
    QDomDocument resp;
    //wfs:WFS_TransactionRespone element
    QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ );
    respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" );
    respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    resp.appendChild( respElem );

    // Store the created feature id for WFS
    QStringList insertResults;
    // Get the WFS layers id
    QStringList wfsLayersId = configParser->wfsLayers();;

    QList<QgsMapLayer*> layerList;
    QgsMapLayer* currentLayer = nullptr;

    // Loop through the layer transaction elements
    docChildNodes = mDocElem.childNodes();
    for ( int i = 0; i < docChildNodes.count(); ++i )
    {
      // Get the vector layer
      typeNameElem = docChildNodes.at( i ).toElement();
      typeName = typeNameElem.tagName();

      layerList = configParser->mapLayerFromTypeName( typeName );
      // Could be empty!
      if ( layerList.count() > 0 )
      {
        currentLayer = layerList.at( 0 );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "Wrong TypeName: %1" ).arg( typeName ) );
      }

      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( currentLayer );
      // it's a vectorlayer and defined by the administrator as a WFS layer
      if ( layer && wfsLayersId.contains( layer->id() ) )
      {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( actionName == QLatin1String( "Insert" ) )
        {
          if ( !accessControl->layerInsertPermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature insert permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Update" ) )
        {
          if ( !accessControl->layerUpdatePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature update permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Delete" ) )
        {
          if ( !accessControl->layerDeletePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature delete permission denied" ) );
          }
        }
#endif

        // Get the provider and it's capabilities
        QgsVectorDataProvider* provider = layer->dataProvider();
        if ( !provider )
        {
          continue;
        }

        int cap = provider->capabilities();

        // Start the update transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) )
        {
          // Loop through the update elements for this layer
          QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) );
          for ( int j = 0; j < upNodeList.count(); ++j )
          {
            if ( !configParser->wfstUpdateLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg );
              return resp;
            }

            actionElem = upNodeList.at( j ).toElement();

            // Get the Feature Ids for this filter on the layer
            QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement();
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

            // Loop through the property elements
            // Store properties and the geometry element
            QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) );
            QMap<QString, QString> propertyMap;
            QDomElement propertyElem;
            QDomElement nameElem;
            QDomElement valueElem;
            QDomElement geometryElem;

            for ( int l = 0; l < propertyNodeList.count(); ++l )
            {
              propertyElem = propertyNodeList.at( l ).toElement();
              nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement();
              valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement();
              if ( nameElem.text() != QLatin1String( "geometry" ) )
              {
                propertyMap.insert( nameElem.text(), valueElem.text() );
              }
              else
              {
                geometryElem = valueElem;
              }
            }

            // Update the features
            QgsFields fields = provider->fields();
            QMap<QString, int> fieldMap = provider->fieldNameMap();
            QMap<QString, int>::const_iterator fieldMapIt;
            QString fieldName;
            bool conversionSuccess;

            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif

              QMap< QString, QString >::const_iterator it = propertyMap.constBegin();
              for ( ; it != propertyMap.constEnd(); ++it )
              {
                fieldName = it.key();
                fieldMapIt = fieldMap.find( fieldName );
                if ( fieldMapIt == fieldMap.constEnd() )
                {
                  continue;
                }
                QgsField field = fields.at( fieldMapIt.value() );
                if ( field.type() == 2 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toInt( &conversionSuccess ) );
                else if ( field.type() == 6 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toDouble( &conversionSuccess ) );
                else
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value() );
              }

              if ( !geometryElem.isNull() )
              {
                QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem );
                if ( !layer->changeGeometry( *fidIt, g ) )
                {
                  throw QgsRequestNotWellFormedException( QStringLiteral( "Error in change geometry" ) );
                }
              }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
              fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  layer->rollBack();
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif
            }
          }
        }
        // Commit the changes of the update elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }
        // Start the delete transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::DeleteFeatures ) )
        {
          // Loop through the delete elements
          QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) );
          for ( int j = 0; j < delNodeList.count(); ++j )
          {
            if ( !configParser->wfstDeleteLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg );
              return resp;
            }

            actionElem = delNodeList.at( j ).toElement();
            QDomElement filterElem = actionElem.firstChild().toElement();
            // Get Feature Ids for the Filter element
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

#ifdef HAVE_SERVER_PYTHON_PLUGINS
            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
            }
#endif

            layer->selectByIds( fids );
            layer->deleteSelectedFeatures();
          }
        }
        // Commit the changes of the delete elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }

        // Store the inserted features
        QgsFeatureList inFeatList;
        if ( cap & QgsVectorDataProvider::AddFeatures )
        {
          // Get Layer Field Information
          QgsFields fields = provider->fields();
          QMap<QString, int> fieldMap = provider->fieldNameMap();
          QMap<QString, int>::const_iterator fieldMapIt;

          // Loop through the insert elements
          QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) );
          for ( int j = 0; j < inNodeList.count(); ++j )
          {
            if ( !configParser->wfstInsertLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg );
              return resp;
            }

            actionElem = inNodeList.at( j ).toElement();
            // Loop through the feature element
            QDomNodeList featNodes = actionElem.childNodes();
            for ( int l = 0; l < featNodes.count(); l++ )
            {
              // Add the feature to the layer
              // and store it to put it's Feature Id in the response
              inFeatList << QgsFeature( fields );

              // Create feature for this layer
              QDomElement featureElem = featNodes.at( l ).toElement();

              QDomNode currentAttributeChild = featureElem.firstChild();

              while ( !currentAttributeChild.isNull() )
              {
                QDomElement currentAttributeElement = currentAttributeChild.toElement();
                QString attrName = currentAttributeElement.localName();

                if ( attrName != QLatin1String( "boundedBy" ) )
                {
                  if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute
                  {
                    fieldMapIt = fieldMap.find( attrName );
                    if ( fieldMapIt == fieldMap.constEnd() )
                    {
                      continue;
                    }
                    QgsField field = fields.at( fieldMapIt.value() );
                    QString attrValue = currentAttributeElement.text();
                    int attrType = field.type();
                    QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) );
                    if ( attrType == QVariant::Int )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() );
                    else if ( attrType == QVariant::Double )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toDouble() );
                    else
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue );
                  }
                  else //a geometry attribute
                  {
                    QgsGeometry g = QgsOgcUtils::geometryFromGML( currentAttributeElement );
                    inFeatList.last().setGeometry( g );
                  }
                }
                currentAttributeChild = currentAttributeChild.nextSibling();
              }
            }
          }
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        QgsFeatureList::iterator featureIt = inFeatList.begin();
        while ( featureIt != inFeatList.end() )
        {
          if ( !accessControl->allowToEdit( layer, *featureIt ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
          }
          featureIt++;
        }
#endif

        // add the features
        if ( !provider->addFeatures( inFeatList ) )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          if ( provider->hasErrors() )
          {
            provider->clearErrors();
          }
          return resp;
        }
        // Get the Feature Ids of the inserted feature
        for ( int j = 0; j < inFeatList.size(); j++ )
        {
          insertResults << typeName + "." + QString::number( inFeatList[j].id() );
        }
      }
    }

    // Put the Feature Ids of the inserted feature
    if ( !insertResults.isEmpty() )
    {
      Q_FOREACH ( const QString &fidStr, insertResults )
      {
        QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) );
        QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) );
        fiElem.setAttribute( QStringLiteral( "fid" ), fidStr );
        irElem.appendChild( fiElem );
        respElem.appendChild( irElem );
      }
Beispiel #14
0
/**
	\brief Reads the error from XML

	This function finds and reads the error element \a e.

	You need to provide the base namespace of the stream which this stanza belongs to
	(probably by using stream.baseNS() function).
*/
bool Stanza::Error::fromXml(const QDomElement &e, const QString &baseNS)
{
	if(e.tagName() != "error" && e.namespaceURI() != baseNS)
		return false;

	// type
	type = Private::stringToErrorType(e.attribute("type"));

	// condition
	QDomNodeList nl = e.childNodes();
	QDomElement t;
	condition = -1;
	int n;
	for(n = 0; n < nl.count(); ++n) {
		QDomNode i = nl.item(n);
		t = i.toElement();
		if(!t.isNull()) {
			// FIX-ME: this shouldn't be needed
			if(t.namespaceURI() == NS_STANZAS || t.attribute("xmlns") == NS_STANZAS) {
				condition = Private::stringToErrorCond(t.tagName());
				if (condition != -1)
					break;
			}
		}
	}

	// code
	originalCode = e.attribute("code").toInt();

	// try to guess type/condition
	if(type == -1 || condition == -1) {
		QPair<int, int> guess(-1, -1);
		if (originalCode)
			guess = Private::errorCodeToTypeCond(originalCode);

		if (type == -1)
			type = guess.first != -1 ? guess.first : Cancel;
		if (condition == -1)
			condition = guess.second != -1 ? guess.second : UndefinedCondition;
	}

	// text
	t = e.elementsByTagNameNS(NS_STANZAS, "text").item(0).toElement();
	if(!t.isNull())
		text = t.text().trimmed();
	else
		text = e.text().trimmed();

	// appspec: find first non-standard namespaced element
	appSpec = QDomElement();
	nl = e.childNodes();
	for(n = 0; n < nl.count(); ++n) {
		QDomNode i = nl.item(n);
		if(i.isElement() && i.namespaceURI() != NS_STANZAS) {
			appSpec = i.toElement();
			break;
		}
	}

	return true;
}
void ExchangeDownload::slotPropFindResult(KIO::Job *job)
{
    kdDebug() << "slotPropFindResult" << endl;

    int error = job->error();
    if(error)
    {
        job->showErrorDialog(0);
        finishUp(ExchangeClient::CommunicationError, job);
        return;
    }

    QDomDocument response = static_cast<KIO::DavJob *>(job)->response();
    kdDebug() << "Response: " << endl;
    kdDebug() << response.toString() << endl;

    QDomElement prop = response.documentElement().namedItem("response")
                       .namedItem("propstat").namedItem("prop").toElement();

    KCal::Event *event = new KCal::Event();

    QDomElement uidElement = prop.namedItem("uid").toElement();
    if(uidElement.isNull())
    {
        kdError() << "Error: no uid in Exchange server reply" << endl;
        finishUp(ExchangeClient::IllegalAppointmentError,
                 "WebDAV server response:\n" + response.toString());
        return;
    }
    event->setUid(uidElement.text());
    // kdDebug() << "Got UID: " << uidElement.text() << endl;

    QString timezoneid = prop.namedItem("timezoneid").toElement().text();
    // kdDebug() << "DEBUG: timezoneid = " << timezoneid << endl;

    QString timezone = prop.namedItem("timezone").toElement().text();
    // kdDebug() << "DEBUG: timezone = " << timezone << endl;

    // mFormat is used for parsing recurrence rules.
    QString localTimeZoneId;
    if(mCalendar)
    {
        mFormat->setTimeZone(mCalendar->timeZoneId(), !mCalendar->isLocalTime());
        localTimeZoneId = mCalendar->timeZoneId();
    }
    else
    {
        localTimeZoneId = "UTC";
        // If no mCalendar, stay in UTC
    }

    QString lastModified = prop.namedItem("lastmodified").toElement().text();
    if(!lastModified.isEmpty())
    {
        QDateTime dt = utcAsZone(QDateTime::fromString(lastModified, Qt::ISODate), localTimeZoneId);
        event->setLastModified(dt);
        kdDebug() << "Got lastModified:" << lastModified << ", " << dt.toString() << endl;
    }

    QString organizer = prop.namedItem("organizer").toElement().text();
    // TODO: Does outlook have a common name? Or does the organizer already contain both?
    event->setOrganizer(organizer);
    // kdDebug() << "Got organizer: " << organizer << endl;

    // Trying to find attendees, not working yet
    QString contact = prop.namedItem("contact").toElement().text();
    //  event->setOrganizer( organizer );
    // kdDebug() << "DEBUG: Got contact: " << contact << endl;

    // This looks promising for finding attendees
    // FIXME: get this to work
    QString to = prop.namedItem("to").toElement().text();
    // kdDebug() << "DEBUG: Got to: " << to << endl;
    QStringList attn = QStringList::split(",", to);   // This doesn't work: there can be commas between ""
    QStringList::iterator it;
    for(it = attn.begin(); it != attn.end(); ++it)
    {
        // kdDebug() << "    attendee: " << (*it) << endl;
        QString name = "";
        // KCal::Attendee* a = new KCal::Attendee( name, email );

        // event->addAttendee( a );
    }

    QString readonly = prop.namedItem("isreadonly").toElement().text();
    event->setReadOnly(readonly == "1");
    kdDebug() << "Got readonly: " << readonly << ":" << (readonly != "0") << endl;

    QString created = prop.namedItem("created").toElement().text();
    if(!created.isEmpty())
    {
        QDateTime dt = utcAsZone(QDateTime::fromString(created, Qt::ISODate),
                                 localTimeZoneId);
        event->setCreated(dt);
        kdDebug() << "got created: " << dt.toString() << endl;
    }

    QString dtstart = prop.namedItem("dtstart").toElement().text();
    if(!dtstart.isEmpty())
    {
        QDateTime dt = utcAsZone(QDateTime::fromString(dtstart, Qt::ISODate),
                                 localTimeZoneId);
        event->setDtStart(dt);
        kdDebug() << "got dtstart: " << dtstart << " becomes in timezone " << dt.toString() << endl;
    }

    QString alldayevent = prop.namedItem("alldayevent").toElement().text();
    bool floats = alldayevent.toInt() != 0;
    event->setFloats(floats);
    kdDebug() << "Got alldayevent: \"" << alldayevent << "\":" << floats << endl;

    QString dtend = prop.namedItem("dtend").toElement().text();
    if(!dtend.isEmpty())
    {
        QDateTime dt = utcAsZone(QDateTime::fromString(dtend, Qt::ISODate),
                                 localTimeZoneId);
        // Outlook thinks differently about floating event timing than libkcal
        if(floats) dt = dt.addDays(-1);
        event->setDtEnd(dt);
        kdDebug() << "got dtend: " << dtend << " becomes in timezone " << dt.toString() << endl;
    }

    QString transparent = prop.namedItem("transparent").toElement().text();
    event->setTransparency(transparent.toInt() > 0 ? KCal::Event::Transparent
                           : KCal::Event::Opaque);
    // kdDebug() << "Got transparent: " << transparent << endl;

    QString description = prop.namedItem("textdescription").toElement().text();
    event->setDescription(description);
    kdDebug() << "Got description: " << description << endl;

    QString subject = prop.namedItem("subject").toElement().text();
    event->setSummary(subject);
    kdDebug() << "Got summary: " << subject << endl;

    QString location =  prop.namedItem("location").toElement().text();
    event->setLocation(location);
    // kdDebug() << "Got location: " << location << endl;

    QString rrule = prop.namedItem("rrule").toElement().text();
    kdDebug() << "Got rrule: " << rrule << endl;
    if(!rrule.isEmpty())
    {
        // Timezone should be handled automatically
        // because we used mFormat->setTimeZone() earlier
        KCal::RecurrenceRule *rr = event->recurrence()->defaultRRule(true);

        if(!rr || !mFormat->fromString(rr, rrule))
        {
            kdError() << "ERROR parsing rrule " << rrule << endl;
        }
    }

    QDomElement keywords = prop.namedItem("Keywords").toElement();
    QStringList categories;
    QDomNodeList list = keywords.elementsByTagNameNS("xml:", "v");
    for(uint i = 0; i < list.count(); i++)
    {
        QDomElement item = list.item(i).toElement();
        categories.append(item.text());
    }
    event->setCategories(categories);
    // kdDebug() << "Got categories: " << categories.join( ", " ) << endl;


    QDomElement exdate = prop.namedItem("exdate").toElement();
    KCal::DateList exdates;
    list = exdate.elementsByTagNameNS("xml:", "v");
    for(uint i = 0; i < list.count(); i++)
    {
        QDomElement item = list.item(i).toElement();
        QDate date = utcAsZone(QDateTime::fromString(item.text(), Qt::ISODate), localTimeZoneId).date();
        exdates.append(date);
        // kdDebug() << "Got exdate: " << date.toString() << endl;
    }
    event->recurrence()->setExDates(exdates);

    // Exchange sentitivity values:
    // 0 None
    // 1 Personal
    // 2 Private
    // 3 Company Confidential
    QString sensitivity = prop.namedItem("sensitivity").toElement().text();
    if(! sensitivity.isNull())
        switch(sensitivity.toInt())
        {
            case 0:
                event->setSecrecy(KCal::Incidence::SecrecyPublic);
                break;
            case 1:
                event->setSecrecy(KCal::Incidence::SecrecyPrivate);
                break;
            case 2:
                event->setSecrecy(KCal::Incidence::SecrecyPrivate);
                break;
            case 3:
                event->setSecrecy(KCal::Incidence::SecrecyConfidential);
                break;
            default:
                kdWarning() << "Unknown sensitivity: " << sensitivity << endl;
        }
    // kdDebug() << "Got sensitivity: " << sensitivity << endl;


    QString reminder = prop.namedItem("reminderoffset").toElement().text();
    // kdDebug() << "Reminder offset: " << reminder << endl;
    if(!reminder.isEmpty())
    {
        // Duration before event in seconds
        KCal::Duration offset(- reminder.toInt());
        KCal::Alarm *alarm = event->newAlarm();
        alarm->setStartOffset(offset);
        alarm->setDisplayAlarm("");
        alarm->setEnabled(true);
        // TODO: multiple alarms; alarm->setType( KCal::Alarm::xxxx );
    }
    /** Create a new alarm which is associated with this incidence */
    //Alarm* newAlarm();
    /** Add an alarm which is associated with this incidence */
    //void addAlarm(Alarm*);

    /** point at some other event to which the event relates */
    //void setRelatedTo(Incidence *relatedTo);
    /** Add an event which is related to this event */
    //void addRelation(Incidence *);

    /** set the list of attachments/associated files for this event */
    //void setAttachments(const QStringList &attachments);

    /** set resources used, such as Office, Car, etc. */
    //void setResources(const QStringList &resources);

    /** set the event's priority, 0 is undefined, 1 highest (decreasing order) */
    //void setPriority(int priority);

    /**
      Add Attendee to this incidence. IncidenceBase takes ownership of the
      Attendee object.
    */

    //void addAttendee(Attendee *a, bool doupdate=true );

    // THE FOLLOWING EVENT PROPERTIES ARE NOT READ

    // Revision ID in webdav is a String, not an int
    /** set the number of revisions this event has seen */
    //void setRevision(int rev);

    // Problem: When you sync Outlook to a Palm, the conduit splits up
    // multi-day events into single-day events WITH ALL THE SAME UID
    // Grrrrrrr.
    if(mCalendar)
    {
        KCal::Event *oldEvent = mCalendar->event(event->uid());
        if(oldEvent)
        {
            kdWarning() << "Already got his event, replace it..." << endl;
            mCalendar->deleteEvent(oldEvent);
        }
        kdDebug() << "ADD EVENT" << endl;
        mCalendar->addEvent(event);
    }
    else
    {
        kdDebug() << "EMIT gotEvent" << endl;
        emit gotEvent(event, static_cast<KIO::DavJob *>(job)->url());
        //    mEvents->append( event );
    }

    decreaseDownloads();
}
void ExchangeDownload::handleAppointments(const QDomDocument &response,
        bool recurrence)
{
    kdDebug() << "Entering handleAppointments" << endl;
    int successCount = 0;

    if(response.documentElement().firstChild().toElement().isNull())
    {
        // Got an empty response, but no error. This would mean there are
        // no appointments in this time period.
        return;
    }

    for(QDomElement item = response.documentElement().firstChild().toElement();
            !item.isNull();
            item = item.nextSibling().toElement())
    {
        //kdDebug() << "Current item:" << item.tagName() << endl;
        QDomNodeList propstats = item.elementsByTagNameNS("DAV:", "propstat");
        // kdDebug() << "Item has " << propstats.count() << " propstat children" << endl;
        for(uint i = 0; i < propstats.count(); i++)
        {
            QDomElement propstat = propstats.item(i).toElement();
            QDomElement prop = propstat.namedItem("prop").toElement();
            if(prop.isNull())
            {
                kdError() << "Error: no <prop> in response" << endl;
                continue;
            }

            QDomElement instancetypeElement = prop.namedItem("instancetype").toElement();
            if(instancetypeElement.isNull())
            {
                kdError() << "Error: no instance type in Exchange server reply" << endl;
                continue;
            }
            int instanceType = instancetypeElement.text().toInt();
            //kdDebug() << "Instance type: " << instanceType << endl;

            if(recurrence && instanceType > 0)
            {
                QDomElement uidElement = prop.namedItem("uid").toElement();
                if(uidElement.isNull())
                {
                    kdError() << "Error: no uid in Exchange server reply" << endl;
                    continue;
                }
                QString uid = uidElement.text();
                if(! m_uids.contains(uid))
                {
                    m_uids[uid] = 1;
                    handleRecurrence(uid);
                    successCount++;
                }
                continue;
            }

            QDomElement hrefElement = prop.namedItem("href").toElement();
            if(hrefElement.isNull())
            {
                kdError() << "Error: no href in Exchange server reply" << endl;
                continue;
            }
            QString href = hrefElement.text();
            KURL url(href);

            kdDebug() << "Getting appointment from url: " << url.prettyURL() << endl;

            readAppointment(toDAV(url));
            successCount++;
        }
    }
    if(!successCount)
    {
        finishUp(ExchangeClient::ServerResponseError,
                 "WebDAV SEARCH response:\n" + response.toString());
    }
}
Beispiel #17
0
bool CoreProtocol::normalStep(const QDomElement &e)
{
	if(step == Start) {
		if(isIncoming()) {
			need = NSASLMechs;
			step = SendFeatures;
			return false;
		}
		else {
			if(old) {
				if(doAuth)
					step = HandleAuthGet;
				else
					return loginComplete();
			}
			else
				step = GetFeatures;

			return processStep();
		}
	}
	else if(step == HandleFeatures) {
		// deal with TLS?
		if(doTLS && !tls_started && !sasl_authed && features.tls_supported) {
			QDomElement e = doc.createElementNS(NS_TLS, "starttls");

			send(e, true);
			event = ESend;
			step = GetTLSProceed;
			return true;
		}

		// Should we go further ?
		if (!doAuth)
			return loginComplete();
		
		// Deal with compression
		if (doCompress && !compress_started && features.compress_supported && features.compression_mechs.contains("zlib")) {
			QDomElement e = doc.createElementNS(NS_COMPRESS_PROTOCOL, "compress");
			QDomElement m = doc.createElementNS(NS_COMPRESS_PROTOCOL, "method");
			m.appendChild(doc.createTextNode("zlib"));
			e.appendChild(m);
			send(e,true);
			event = ESend;
			step = GetCompressProceed;
			return true;
		}

		// deal with SASL?
		if(!sasl_authed) {
			if(!features.sasl_supported) {
				// SASL MUST be supported
				//event = EError;
				//errorCode = ErrProtocol;
				//return true;
				
				// Fall back on auth for non-compliant servers 
				step = HandleAuthGet;
				old = true;
				return true;
			}

#ifdef XMPP_TEST
			TD::msg("starting SASL authentication...");
#endif
			need = NSASLFirst;
			step = GetSASLFirst;
			return false;
		}

		if(server) {
			return loginComplete();
		}
		else {
			if(!doBinding)
				return loginComplete();
		}

		// deal with bind
		if(!features.bind_supported) {
			// bind MUST be supported
			event = EError;
			errorCode = ErrProtocol;
			return true;
		}

		QDomElement e = doc.createElement("iq");
		e.setAttribute("type", "set");
		e.setAttribute("id", "bind_1");
		QDomElement b = doc.createElementNS(NS_BIND, "bind");

		// request specific resource?
		QString resource = jid_.resource();
		if(!resource.isEmpty()) {
			QDomElement r = doc.createElement("resource");
			r.appendChild(doc.createTextNode(jid_.resource()));
			b.appendChild(r);
		}

		e.appendChild(b);

		send(e);
		event = ESend;
		step = GetBindResponse;
		return true;
	}
	else if(step == GetSASLFirst) {
		QDomElement e = doc.createElementNS(NS_SASL, "auth");
		e.setAttribute("mechanism", sasl_mech);
		if(!sasl_step.isEmpty()) {
#ifdef XMPP_TEST
			TD::msg(QString("SASL OUT: [%1]").arg(printArray(sasl_step)));
#endif
			e.appendChild(doc.createTextNode(QCA::Base64().arrayToString(sasl_step)));
		}

		send(e, true);
		event = ESend;
		step = GetSASLChallenge;
		return true;
	}
	else if(step == GetSASLNext) {
		if(isIncoming()) {
			if(sasl_authed) {
				QDomElement e = doc.createElementNS(NS_SASL, "success");
				writeElement(e, TypeElement, false, true);
				event = ESend;
				step = IncHandleSASLSuccess;
				return true;
			}
			else {
				QByteArray stepData = sasl_step;
				QDomElement e = doc.createElementNS(NS_SASL, "challenge");
				if(!stepData.isEmpty())
					e.appendChild(doc.createTextNode(QCA::Base64().arrayToString(stepData)));

				writeElement(e, TypeElement, false, true);
				event = ESend;
				step = GetSASLResponse;
				return true;
			}
		}
		else {
			// already authed?  then ignore last client step
			//   (this happens if "additional data with success"
			//   is used)
			if(sasl_authed)
			{
				event = ESASLSuccess;
				step = HandleSASLSuccess;
				return true;
			}

			QByteArray stepData = sasl_step;
#ifdef XMPP_TEST
			TD::msg(QString("SASL OUT: [%1]").arg(printArray(sasl_step)));
#endif
			QDomElement e = doc.createElementNS(NS_SASL, "response");
			if(!stepData.isEmpty())
				e.appendChild(doc.createTextNode(QCA::Base64().arrayToString(stepData)));

			send(e, true);
			event = ESend;
			step = GetSASLChallenge;
			return true;
		}
	}
	else if(step == HandleSASLSuccess) {
		need = NSASLLayer;
		spare = resetStream();
		step = Start;
		return false;
	}
	else if(step == HandleAuthGet) {
		QDomElement e = doc.createElement("iq");
		e.setAttribute("to", to);
		e.setAttribute("type", "get");
		e.setAttribute("id", "auth_1");
		QDomElement q = doc.createElementNS("jabber:iq:auth", "query");
		QDomElement u = doc.createElement("username");
		u.appendChild(doc.createTextNode(jid_.node()));
		q.appendChild(u);
		e.appendChild(q);

		send(e);
		event = ESend;
		step = GetAuthGetResponse;
		return true;
	}
	else if(step == HandleAuthSet) {
		QDomElement e = doc.createElement("iq");
		e.setAttribute("to", to);
		e.setAttribute("type", "set");
		e.setAttribute("id", "auth_2");
		QDomElement q = doc.createElementNS("jabber:iq:auth", "query");
		QDomElement u = doc.createElement("username");
		u.appendChild(doc.createTextNode(jid_.node()));
		q.appendChild(u);
		QDomElement p;
		if(digest) {
			// need SHA1 here
			//if(!QCA::isSupported(QCA::CAP_SHA1))
			//	QCA::insertProvider(createProviderHash());

			p = doc.createElement("digest");
			Q3CString cs = id.utf8() + password.utf8();
			p.appendChild(doc.createTextNode(QCA::Hash("sha1").hashToString(cs)));
		}
		else {
			p = doc.createElement("password");
			p.appendChild(doc.createTextNode(password));
		}
		q.appendChild(p);
		QDomElement r = doc.createElement("resource");
		r.appendChild(doc.createTextNode(jid_.resource()));
		q.appendChild(r);
		e.appendChild(q);

		send(e, true);
		event = ESend;
		step = GetAuthSetResponse;
		return true;
	}
	// server
	else if(step == SendFeatures) {
		QDomElement f = doc.createElementNS(NS_ETHERX, "stream:features");
		if(!tls_started && !sasl_authed) { // don't offer tls if we are already sasl'd
			QDomElement tls = doc.createElementNS(NS_TLS, "starttls");
			f.appendChild(tls);
		}

		if(sasl_authed) {
			if(!server) {
				QDomElement bind = doc.createElementNS(NS_BIND, "bind");
				f.appendChild(bind);
			}
		}
		else {
			QDomElement mechs = doc.createElementNS(NS_SASL, "mechanisms");
			for(QStringList::ConstIterator it = sasl_mechlist.begin(); it != sasl_mechlist.end(); ++it) {
				QDomElement m = doc.createElement("mechanism");
				m.appendChild(doc.createTextNode(*it));
				mechs.appendChild(m);
			}
			f.appendChild(mechs);
		}

		writeElement(f, TypeElement, false);
		event = ESend;
		step = GetRequest;
		return true;
	}
	// server
	else if(step == HandleTLS) {
		tls_started = true;
		need = NStartTLS;
		spare = resetStream();
		step = Start;
		return false;
	}
	// server
	else if(step == IncHandleSASLSuccess) {
		event = ESASLSuccess;
		spare = resetStream();
		step = Start;
		printf("sasl success\n");
		return true;
	}
	else if(step == GetFeatures) {
		// we are waiting for stream features
		if(e.namespaceURI() == NS_ETHERX && e.tagName() == "features") {
			// extract features
			StreamFeatures f;
			QDomElement s = e.elementsByTagNameNS(NS_TLS, "starttls").item(0).toElement();
			if(!s.isNull()) {
				f.tls_supported = true;
				f.tls_required = s.elementsByTagNameNS(NS_TLS, "required").count() > 0;
			}
			QDomElement m = e.elementsByTagNameNS(NS_SASL, "mechanisms").item(0).toElement();
			if(!m.isNull()) {
				f.sasl_supported = true;
				QDomNodeList l = m.elementsByTagNameNS(NS_SASL, "mechanism");
				for(int n = 0; n < l.count(); ++n)
					f.sasl_mechs += l.item(n).toElement().text();
			}
			QDomElement c = e.elementsByTagNameNS(NS_COMPRESS_FEATURE, "compression").item(0).toElement();
			if(!c.isNull()) {
				f.compress_supported = true;
				QDomNodeList l = c.elementsByTagNameNS(NS_COMPRESS_FEATURE, "method");
				for(int n = 0; n < l.count(); ++n)
					f.compression_mechs += l.item(n).toElement().text();
			}
			QDomElement b = e.elementsByTagNameNS(NS_BIND, "bind").item(0).toElement();
			if(!b.isNull())
				f.bind_supported = true;

			if(f.tls_supported) {
#ifdef XMPP_TEST
				QString s = "STARTTLS is available";
				if(f.tls_required)
					s += " (required)";
				TD::msg(s);
#endif
			}
			if(f.sasl_supported) {
#ifdef XMPP_TEST
				QString s = "SASL mechs:";
				for(QStringList::ConstIterator it = f.sasl_mechs.begin(); it != f.sasl_mechs.end(); ++it)
					s += QString(" [%1]").arg((*it));
				TD::msg(s);
#endif
			}
			if(f.compress_supported) {
#ifdef XMPP_TEST
				QString s = "Compression mechs:";
				for(QStringList::ConstIterator it = f.compression_mechs.begin(); it != f.compression_mechs.end(); ++it)
					s += QString(" [%1]").arg((*it));
				TD::msg(s);
#endif
			}

			event = EFeatures;
			features = f;
			step = HandleFeatures;
			return true;
		}
		else {
			// ignore
		}
	}
	else if(step == GetTLSProceed) {
		// waiting for proceed to starttls
		if(e.namespaceURI() == NS_TLS) {
			if(e.tagName() == "proceed") {
#ifdef XMPP_TEST
				TD::msg("Server wants us to proceed with ssl handshake");
#endif
				tls_started = true;
				need = NStartTLS;
				spare = resetStream();
				step = Start;
				return false;
			}
			else if(e.tagName() == "failure") {
				event = EError;
				errorCode = ErrStartTLS;
				return true;
			}
			else {
				event = EError;
				errorCode = ErrProtocol;
				return true;
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetCompressProceed) {
		// waiting for proceed to compression
		if(e.namespaceURI() == NS_COMPRESS_PROTOCOL) {
			if(e.tagName() == "compressed") {
#ifdef XMPP_TEST
				TD::msg("Server wants us to proceed with compression");
#endif
				compress_started = true;
				need = NCompress;
				spare = resetStream();
				step = Start;
				return false;
			}
			else if(e.tagName() == "failure") {
				event = EError;
				errorCode = ErrCompress;
				return true;
			}
			else {
				event = EError;
				errorCode = ErrProtocol;
				return true;
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetSASLChallenge) {
		// waiting for sasl challenge/success/fail
		if(e.namespaceURI() == NS_SASL) {
			if(e.tagName() == "challenge") {
				QByteArray a = QCA::Base64().stringToArray(e.text()).toByteArray();
#ifdef XMPP_TEST
				TD::msg(QString("SASL IN: [%1]").arg(printArray(a)));
#endif
				sasl_step = a;
				need = NSASLNext;
				step = GetSASLNext;
				return false;
			}
			else if(e.tagName() == "success") {
				QString str = e.text();
				// "additional data with success" ?
				if(!str.isEmpty())
				{
					QByteArray a = QCA::Base64().stringToArray(str).toByteArray();
					sasl_step = a;
					sasl_authed = true;
					need = NSASLNext;
					step = GetSASLNext;
					return false;
				}

				sasl_authed = true;
				event = ESASLSuccess;
				step = HandleSASLSuccess;
				return true;
			}
			else if(e.tagName() == "failure") {
				QDomElement t = firstChildElement(e);
				if(t.isNull() || t.namespaceURI() != NS_SASL)
					errCond = -1;
				else
					errCond = stringToSASLCond(t.tagName());

				event = EError;
				errorCode = ErrAuth;
				return true;
			}
			else {
				event = EError;
				errorCode = ErrProtocol;
				return true;
			}
		}
	}
	else if(step == GetBindResponse) {
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			QString type(e.attribute("type"));
			QString id(e.attribute("id"));

			if(id == "bind_1" && (type == "result" || type == "error")) {
				if(type == "result") {
					QDomElement b = e.elementsByTagNameNS(NS_BIND, "bind").item(0).toElement();
					Jid j;
					if(!b.isNull()) {
						QDomElement je = e.elementsByTagName("jid").item(0).toElement();
						j = je.text();
					}
					if(!j.isValid()) {
						event = EError;
						errorCode = ErrProtocol;
						return true;
					}
					jid_ = j;
					return loginComplete();
				}
				else {
					errCond = -1;

					QDomElement err = e.elementsByTagNameNS(NS_CLIENT, "error").item(0).toElement();
					if(!err.isNull()) {
						// get error condition
						QDomNodeList nl = err.childNodes();
						QDomElement t;
						for(int n = 0; n < nl.count(); ++n) {
							QDomNode i = nl.item(n);
							if(i.isElement()) {
								t = i.toElement();
								break;
							}
						}
						if(!t.isNull() && t.namespaceURI() == NS_STANZAS) {
							QString cond = t.tagName();
							if(cond == "not-allowed")
								errCond = BindNotAllowed;
							else if(cond == "conflict")
								errCond = BindConflict;
						}
					}

					event = EError;
					errorCode = ErrBind;
					return true;
				}
			}
			else {
				// ignore
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetAuthGetResponse) {
		// waiting for an iq
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			Jid from(e.attribute("from"));
			QString type(e.attribute("type"));
			QString id(e.attribute("id"));

			bool okfrom = (from.isEmpty() || from.compare(Jid(to)));
			if(okfrom && id == "auth_1" && (type == "result" || type == "error")) {
				if(type == "result") {
					QDomElement q = e.elementsByTagNameNS("jabber:iq:auth", "query").item(0).toElement();
					if(q.isNull() || q.elementsByTagName("username").item(0).isNull() || q.elementsByTagName("resource").item(0).isNull()) {
						event = EError;
						errorCode = ErrProtocol;
						return true;
					}
					bool plain_supported = !q.elementsByTagName("password").item(0).isNull();
					bool digest_supported = !q.elementsByTagName("digest").item(0).isNull();

					if(!digest_supported && !plain_supported) {
						event = EError;
						errorCode = ErrProtocol;
						return true;
					}

					// plain text not allowed?
					if(!digest_supported && !allowPlain) {
						event = EError;
						errorCode = ErrPlain;
						return true;
					}

					digest = digest_supported;
					need = NPassword;
					step = HandleAuthSet;
					return false;
				}
				else {
					errCond = getOldErrorCode(e);

					event = EError;
					errorCode = ErrAuth;
					return true;
				}
			}
			else {
				// ignore
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetAuthSetResponse) {
		// waiting for an iq
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			Jid from(e.attribute("from"));
			QString type(e.attribute("type"));
			QString id(e.attribute("id"));

			bool okfrom = (from.isEmpty() || from.compare(Jid(to)));
			if(okfrom && id == "auth_2" && (type == "result" || type == "error")) {
				if(type == "result") {
					return loginComplete();
				}
				else {
					errCond = getOldErrorCode(e);

					event = EError;
					errorCode = ErrAuth;
					return true;
				}
			}
			else {
				// ignore
			}
		}
		else {
			// ignore
		}
	}
	// server
	else if(step == GetRequest) {
		printf("get request: [%s], %s\n", e.namespaceURI().latin1(), e.tagName().latin1());
		if(e.namespaceURI() == NS_TLS && e.localName() == "starttls") {
			// TODO: don't let this be done twice

			QDomElement e = doc.createElementNS(NS_TLS, "proceed");
			writeElement(e, TypeElement, false, true);
			event = ESend;
			step = HandleTLS;
			return true;
		}
		if(e.namespaceURI() == NS_SASL) {
			if(e.localName() == "auth") {
				if(sasl_started) {
					// TODO
					printf("error\n");
					return false;
				}

				sasl_started = true;
				sasl_mech = e.attribute("mechanism");
				// TODO: if child text missing, don't pass it
				sasl_step = QCA::Base64().stringToArray(e.text()).toByteArray();
				need = NSASLFirst;
				step = GetSASLNext;
				return false;
			}
			else {
				// TODO
				printf("unknown sasl tag\n");
				return false;
			}
		}
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			QDomElement b = e.elementsByTagNameNS(NS_BIND, "bind").item(0).toElement();
			if(!b.isNull()) {
				QDomElement res = b.elementsByTagName("resource").item(0).toElement();
				QString resource = res.text();

				QDomElement r = doc.createElement("iq");
				r.setAttribute("type", "result");
				r.setAttribute("id", e.attribute("id"));
				QDomElement bind = doc.createElementNS(NS_BIND, "bind");
				QDomElement jid = doc.createElement("jid");
				Jid j = user + '@' + host + '/' + resource;
				jid.appendChild(doc.createTextNode(j.full()));
				bind.appendChild(jid);
				r.appendChild(bind);

				writeElement(r, TypeElement, false);
				event = ESend;
				// TODO
				return true;
			}
			else {
				// TODO
			}
		}
	}
	else if(step == GetSASLResponse) {
		if(e.namespaceURI() == NS_SASL && e.localName() == "response") {
			sasl_step = QCA::Base64().stringToArray(e.text()).toByteArray();
			need = NSASLNext;
			step = GetSASLNext;
			return false;
		}
	}

	if(isReady()) {
		if(!e.isNull() && isValidStanza(e)) {
			stanzaToRecv = e;
			event = EStanzaReady;
			setIncomingAsExternal();
			return true;
		}
	}

	need = NNotify;
	notify |= NRecv;
	return false;
}
Beispiel #18
0
	channels_container_t RSS10Parser::Parse (const QDomDocument& doc,
			const IDType_t& feedId) const
	{
		channels_container_t result;
	
		QMap<QString, Channel_ptr> item2Channel;
		QDomElement root = doc.documentElement ();
		QDomElement channelDescr = root.firstChildElement ("channel");
		while (!channelDescr.isNull ())
		{
			Channel_ptr channel (new Channel (feedId));
			channel->Title_ = channelDescr.firstChildElement ("title").text ().trimmed ();
			channel->Link_ = channelDescr.firstChildElement ("link").text ();
			channel->Description_ =
				channelDescr.firstChildElement ("description").text ();
			channel->PixmapURL_ =
				channelDescr.firstChildElement ("image")
				.firstChildElement ("url").text ();
			channel->LastBuild_ = GetDCDateTime (channelDescr);
	
			QDomElement itemsRoot = channelDescr.firstChildElement ("items");
			QDomNodeList seqs = itemsRoot.elementsByTagNameNS (RDF_, "Seq");
	
			channelDescr = channelDescr.nextSiblingElement ("channel");
	
			if (!seqs.size ())
				continue;
	
			QDomElement seqElem = seqs.at (0).toElement ();
			QDomNodeList lis = seqElem.elementsByTagNameNS (RDF_, "li");
			for (int i = 0; i < lis.size (); ++i)
				item2Channel [lis.at (i).toElement ().attribute ("resource")] = channel;
	
			result.push_back (channel);
		}
	
		QDomElement itemDescr = root.firstChildElement ("item");
		while (!itemDescr.isNull ())
		{
			QString about = itemDescr.attributeNS (RDF_, "about");
			if (item2Channel.contains (about))
			{
				Item_ptr item (new Item (item2Channel [about]->ChannelID_));
				item->Title_ = itemDescr.firstChildElement ("title").text ();
				item->Link_ = itemDescr.firstChildElement ("link").text ();
				item->Description_ = itemDescr.firstChildElement ("description").text ();
				GetDescription (itemDescr, item->Description_);
	
				item->Categories_ = GetAllCategories (itemDescr);
				item->Author_ = GetAuthor (itemDescr);
				item->PubDate_ = GetDCDateTime (itemDescr);
				item->Unread_ = true;
				item->NumComments_ = GetNumComments (itemDescr);
				item->CommentsLink_ = GetCommentsRSS (itemDescr);
				item->CommentsPageLink_ = GetCommentsLink (itemDescr);
				item->Enclosures_ = GetEncEnclosures (itemDescr, item->ItemID_);
				QPair<double, double> point = GetGeoPoint (itemDescr);
				item->Latitude_ = point.first;
				item->Longitude_ = point.second;
				if (item->Guid_.isEmpty ())
					item->Guid_ = "empty";
	
				item2Channel [about]->Items_.push_back (item);
			}
			itemDescr = itemDescr.nextSiblingElement ("item");
		}
	
		return result;
	}
Beispiel #19
0
void RSSEditPopup::SlotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    LOG(VB_GENERAL, LOG_DEBUG, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL =
            channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd",
                           "image");
            if (nodes.size())
            {
                thumbnailURL =
                    nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = MythDate::current();
        QString filename("");

        if (!file.isEmpty())
            filename = file;
        else if (!thumbnailURL.isEmpty())
            filename = thumbnailURL;

        QString link = m_urlEdit->GetText();

        RSSSite site(title, filename, VIDEO_PODCAST, description, link,
                     author, download, MythDate::current());
        if (insertInDB(&site))
            emit Saving();
    }

    Close();
}
Beispiel #20
0
void OwnCloudService::loadTodoItems(QString &data) {
    QDomDocument doc;
    doc.setContent(data, true);

    // fetch all urls that are currently in the calendar
    QList<QUrl> calendarItemUrlRemoveList =
            CalendarItem::fetchAllUrlsByCalendar(calendarName);

    QDomNodeList responseNodes = doc.elementsByTagNameNS(NS_DAV, "response");
    int responseNodesCount = responseNodes.length();
    int requestCount = 0;

    // set the preliminary maximum of the progress bar
    this->todoDialog->todoItemLoadingProgressBarSetMaximum(responseNodesCount);

    // loop all response blocks
    for (int i = 0; i < responseNodesCount; ++i) {
        QDomNode responseNode = responseNodes.at(i);
        if (responseNode.isElement()) {
            QDomElement elem = responseNode.toElement();

            // check if we have an url
            QDomNodeList urlPartNodes = elem.elementsByTagNameNS(NS_DAV,
                                                                 "href");
            if (urlPartNodes.length()) {
                QString urlPart = urlPartNodes.at(0).toElement().text();

                if (urlPart == "") {
                    continue;
                }

                QUrl calendarItemUrl = QUrl(serverUrlWithoutPath + urlPart);

                // check if we have an etag
                QDomNodeList etagNodes = elem.elementsByTagNameNS(NS_DAV,
                                                                  "getetag");
                if (etagNodes.length()) {
                    QString etag = etagNodes.at(0).toElement().text();
                    etag.replace("\"", "");
                    qDebug() << __func__ << " - 'etag': " << etag;

                    // check if we have a last modified date
                    QDomNodeList lastModifiedNodes = elem.elementsByTagNameNS(
                            NS_DAV, "getlastmodified");
                    if (lastModifiedNodes.length()) {
                        const QString lastModified = lastModifiedNodes.at(
                                0).toElement().text();
                        bool fetchItem = false;

                        // try to fetch the calendar item by url
                        CalendarItem calItem = CalendarItem::fetchByUrl(
                                calendarItemUrl);
                        if (calItem.isFetched()) {
                            // check if calendar item was modified
                            if (calItem.getETag() != etag) {
                                // store etag and last modified date
                                calItem.setETag(etag);
                                calItem.setLastModifiedString(lastModified);
                                calItem.store();

                                // we want to update the item from server
                                fetchItem = true;
                            }
                        } else {
                            // calendar item was not found
                            // create calendar item for fetching
                            CalendarItem::addCalendarItemForRequest(
                                    calendarName, calendarItemUrl, etag,
                                    lastModified);
                            fetchItem = true;
                        }

                        // remove the url from the list of calendar item urls
                        // to remove
                        if (calendarItemUrlRemoveList.contains(
                                calendarItemUrl)) {
                            calendarItemUrlRemoveList.removeAll(
                                    calendarItemUrl);
                        }

                        // fetch the calendar item
                        if (fetchItem) {
                            QNetworkRequest r(calendarItemUrl);
                            addAuthHeader(&r);

                            QNetworkReply *reply = networkManager->get(r);
                            ignoreSslErrorsIfAllowed(reply);

                            requestCount++;
                        }
                    }
                }
            }
        }
    }

    // set the real maximum of the progress bar
    this->todoDialog->todoItemLoadingProgressBarSetMaximum(requestCount);

    // hide progress bar if there were no updates
    if (requestCount == 0) {
        this->todoDialog->todoItemLoadingProgressBarHide();
    }

    // remove all not found items
    for (int i = 0; i < calendarItemUrlRemoveList.length(); ++i) {
        QUrl url = calendarItemUrlRemoveList.at(i);
        CalendarItem calItem = CalendarItem::fetchByUrl(url);

        if (calItem.isFetched()) {
            calItem.remove();
        }
    }

    // reload the existing items
    this->todoDialog->reloadTodoListItems();

    qDebug() << CalendarItem::fetchAllByCalendar(calendarName);
}