Example #1
0
QString KUrlNavigator::Private::firstButtonText() const
{
    QString text;

    // The first URL navigator button should get the name of the
    // place instead of the directory name
    if ((m_placesSelector != 0) && !m_showFullPath) {
        const KUrl placeUrl = m_placesSelector->selectedPlaceUrl();
        text = m_placesSelector->selectedPlaceText();
    }

    if (text.isEmpty()) {
        const KUrl currentUrl = q->locationUrl();
        if (currentUrl.isLocalFile()) {
            text = m_showFullPath ? QLatin1String("/") : i18n("Custom Path");
        } else {
            text = currentUrl.protocol() + QLatin1Char(':');
            if (!currentUrl.host().isEmpty()) {
                text += QLatin1Char(' ') + currentUrl.host();
            }
        }
    }

    return text;
}
Example #2
0
QVariantHash ChooseSamba::values() const
{
    QVariantHash ret = m_args;

    QString address = ui->addressLE->text().trimmed();
    KUrl url;
    if (address.startsWith(QLatin1String("//"))) {
        url = QLatin1String("smb:") % address;
    } else if (address.startsWith(QLatin1String("/"))) {
        url = QLatin1String("smb:/") % address;
    } else if (address.startsWith(QLatin1String("://"))) {
        url = QLatin1String("smb") % address;
    } else if (address.startsWith(QLatin1String("smb://"))) {
        url = address;
    } else if (!KUrl(address).protocol().isEmpty() &&
               KUrl(address).protocol() != QLatin1String("smb")) {
        url = address;
        url.setProtocol(QLatin1String("smb"));
    } else {
        url = QLatin1String("smb://") % address;
    }

    kDebug() << 1 << url;
    if (!ui->usernameLE->text().isEmpty()) {
        url.setUser(ui->usernameLE->text());
    }

    if (!ui->passwordLE->text().isEmpty()) {
        url.setPass(ui->passwordLE->text());
    }

    kDebug() << 2 << url;
    kDebug() << 3 << url.url() << url.path().section(QLatin1Char('/'), -1, -1);// same as url.fileName()
    kDebug() << 4 << url.fileName();
    kDebug() << 5 << url.host() << url.url().section(QLatin1Char('/'), 3, 3).toLower();

    ret[KCUPS_DEVICE_URI] = url.url();
    ret[KCUPS_DEVICE_INFO] = url.fileName();

    // if there is 4 '/' means the url is like
    // smb://group/host/printer, so the location is at a different place
    if (url.url().count(QLatin1Char('/') == 4)) {
        ret[KCUPS_DEVICE_LOCATION] = url.url().section(QLatin1Char('/'), 3, 3).toLower();
    } else {
        ret[KCUPS_DEVICE_LOCATION] = url.host();
    }

    return ret;
}
Example #3
0
void MainWindow::fileSaveAs()
{
    WebTab *w = currentTab();
    KUrl srcUrl = w->url();
    
    // First, try with suggested file name...
    QString name = w->page()->suggestedFileName();

    // Second, with KUrl fileName...
    if (name.isEmpty())
    {
        name = srcUrl.fileName();
    }
    
    // Last chance...
    if(name.isEmpty())
    {
        name = srcUrl.host() + QString(".html");
    }
    
    const QString destUrl = KFileDialog::getSaveFileName(name, QString(), this);
    if (destUrl.isEmpty()) 
        return;
    
    KIO::Job *job = KIO::file_copy(srcUrl, KUrl(destUrl), -1, KIO::Overwrite);
    job->addMetaData("MaxCacheSize", "0");  // Don't store in http cache.
    job->addMetaData("cache", "cache");     // Use entry from cache if available.
    job->uiDelegate()->setAutoErrorHandlingEnabled(true);
}
Example #4
0
VncView::VncView(QWidget *parent, const KUrl &url, KConfigGroup configGroup)
        : RemoteView(parent),
        m_initDone(false),
        m_buttonMask(0),
        m_repaint(false),
        m_quitFlag(false),
        m_firstPasswordTry(true),
        m_dontSendClipboard(false),
        m_horizontalFactor(1.0),
        m_verticalFactor(1.0),
        m_forceLocalCursor(false)
{
    m_url = url;
    m_host = url.host();
    m_port = url.port();

    // BlockingQueuedConnection can cause deadlocks when exiting, handled in startQuitting()
    connect(&vncThread, SIGNAL(imageUpdated(int,int,int,int)), this, SLOT(updateImage(int,int,int,int)), Qt::BlockingQueuedConnection);
    connect(&vncThread, SIGNAL(gotCut(QString)), this, SLOT(setCut(QString)), Qt::BlockingQueuedConnection);
    connect(&vncThread, SIGNAL(passwordRequest(bool)), this, SLOT(requestPassword(bool)), Qt::BlockingQueuedConnection);
    connect(&vncThread, SIGNAL(outputErrorMessage(QString)), this, SLOT(outputErrorMessage(QString)));

    m_clipboard = QApplication::clipboard();
    connect(m_clipboard, SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
    
#ifndef QTONLY
    m_hostPreferences = new VncHostPreferences(configGroup, this);
#else
    Q_UNUSED(configGroup);
#endif
}
Example #5
0
bool SocketConnectionBackend::connectToRemote(const KUrl &url)
{
    Q_ASSERT(state == Idle);
    Q_ASSERT(!socket);
    Q_ASSERT(!localServer);     // !tcpServer as well

    if (mode == LocalSocketMode) {
        KLocalSocket *sock = new KLocalSocket(this);
        QString path = url.path();
#if 0
        // TODO: Activate once abstract socket support is implemented in Qt.
        KLocalSocket::LocalSocketType type = KLocalSocket::UnixSocket;

        if (url.queryItem(QLatin1String("abstract")) == QLatin1String("1"))
            type = KLocalSocket::AbstractUnixSocket;
#endif
        sock->connectToPath(path);
        socket = sock;
    } else {
        socket = new QTcpSocket(this);
        socket->connectToHost(url.host(),url.port());

        if (!socket->waitForConnected(1000)) {
            state = Idle;
            kDebug() << "could not connect to " << url;
            return false;
        }
    }
    connect(socket, SIGNAL(readyRead()), SLOT(socketReadyRead()));
    connect(socket, SIGNAL(disconnected()), SLOT(socketDisconnected()));
    state = Connected;
    return true;
}
Example #6
0
 bool destMatch(const KUrl &url, const QString &protClass, const KUrl &base, const QString &baseClass) const
 {
    if (destProtEqual)
    {
       if ( (url.protocol() != base.protocol()) &&
            (protClass.isEmpty() || baseClass.isEmpty() || protClass != baseClass) )
          return false;
    }
    else if (destProtWildCard)
    {
       if ( !destProt.isEmpty() && !url.protocol().startsWith(destProt) &&
            (protClass.isEmpty() || (protClass != destProt)) )
          return false;
    }
    else
    {
       if ( (url.protocol() != destProt) &&
            (protClass.isEmpty() || (protClass != destProt)) )
          return false;
    }
    if (destHostWildCard)
    {
       if (!destHost.isEmpty() && !url.host().endsWith(destHost))
          return false;
    }
    else if (destHostEqual)
    {
       if (url.host() != base.host())
          return false;
    }
    else
    {
       if (url.host() != destHost)
          return false;
    }
    if (destPathWildCard)
    {
       if (!destPath.isEmpty() && !url.path().startsWith(destPath))
          return false;
    }
    else
    {
       if (url.path() != destPath)
          return false;
    }
    return true;
 }
Example #7
0
 TestLaunchConfiguration(KUrl script) {
     c = new KConfig();
     cfg = c->group("launch");
     cfg.writeEntry("Server", script.host());
     cfg.writeEntry("Path", script.path());
     cfg.writeEntry("Arguments", script.query());
     KConfigGroup pmCfg = cfg.group("Path Mappings").group("0");
     pmCfg.writeEntry("Remote", KUrl(buildBaseUrl));
     pmCfg.writeEntry("Local", KUrl(QDir::currentPath()));
 }
Example #8
0
bool KRunnerItemHandler::openUrl(const KUrl& url)
{
    QString runner = url.host();
    QString id = url.fragment();
    if (id.startsWith(QLatin1Char('/'))) {
        id = id.remove(0, 1);
    }

    runnerManager()->run(id);
    return true;
}
Example #9
0
void LinkImporter::addTransfer(QString &link)
{
    KUrl auxUrl;
    
    if (link.contains("://")) {
        auxUrl = KUrl(link);
    } else {
        auxUrl = KUrl(QString("http://") + link);
    }

    if(!link.isEmpty() && auxUrl.isValid() && m_transfers.indexOf(link) < 0 &&
       !auxUrl.scheme().isEmpty() && !auxUrl.host().isEmpty()) {
        m_transfers << link;
    }
}
// The opposite of parseURL
static QString splitURL( int mRealArgType, const KUrl& url )
{
  if ( mRealArgType == 33 ) { // LDAP server
    // The format is HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN
    Q_ASSERT( url.protocol() == "ldap" );
    return urlpart_encode( url.host() ) + ':' +
      ( url.port() != -1 ? QString::number( url.port() ) : QString() ) + ':' + // -1 is used for default ports, omit
      urlpart_encode( url.user() ) + ':' +
      urlpart_encode( url.pass() ) + ':' +
      // KUrl automatically encoded the query (e.g. for spaces inside it),
      // so decode it before writing it out to gpgconf (issue119)
      urlpart_encode( KUrl::fromPercentEncoding( url.query().mid(1).toLatin1() ) );
  }
  return url.path();
}
Example #11
0
 bool baseMatch(const KUrl &url, const QString &protClass) const
 {
    if (baseProtWildCard)
    {
       if ( !baseProt.isEmpty() && !url.protocol().startsWith(baseProt) &&
            (protClass.isEmpty() || (protClass != baseProt)) )
          return false;
    }
    else
    {
       if ( (url.protocol() != baseProt) &&
            (protClass.isEmpty() || (protClass != baseProt)) )
          return false;
    }
    if (baseHostWildCard)
    {
       if (!baseHost.isEmpty() && !url.host().endsWith(baseHost))
          return false;
    }
    else
    {
       if (url.host() != baseHost)
          return false;
    }
    if (basePathWildCard)
    {
       if (!basePath.isEmpty() && !url.path().startsWith(basePath))
          return false;
    }
    else
    {
       if (url.path() != basePath)
          return false;
    }
    return true;
 }
Example #12
0
Qt::ItemFlags KRunnerModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags flags = QStandardItemModel::flags(index);

    if (index.isValid()) {
        KUrl url = data(index, CommonModel::Url).toString();
        QString host = url.host();
        if (host != "services") {
            flags &= ~ ( Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled );
        }
    } else {
        flags = 0;
    }

    return flags;
}
void KonqSidebarTree::addUrl(KonqSidebarTreeTopLevelItem* item, const KUrl & url)
{
    QString path;
    if (item)
        path = item->path();
    else
        path = m_dirtreeDir.dir.path();

    KUrl destUrl;

    if (url.isLocalFile() && url.fileName().endsWith(".desktop"))
    {
        QString filename = findUniqueFilename(path, url.fileName());
        destUrl.setPath(filename);
        KIO::NetAccess::file_copy(url, destUrl, this);
    }
    else
    {
        QString name = url.host();
        if (name.isEmpty())
            name = url.fileName();
        QString filename = findUniqueFilename(path, name);
        destUrl.setPath(filename);

        KDesktopFile desktopFile(filename);
        KConfigGroup cfg = desktopFile.desktopGroup();
        cfg.writeEntry("Encoding", "UTF-8");
        cfg.writeEntry("Type","Link");
        cfg.writeEntry("URL", url.url());
        QString icon = "folder";
        if (!url.isLocalFile())
            icon = KMimeType::favIconForUrl(url);
        if (icon.isEmpty())
            icon = KProtocolInfo::icon( url.protocol() );
        cfg.writeEntry("Icon", icon);
        cfg.writeEntry("Name", name);
        cfg.writeEntry("Open", false);
        cfg.sync();
    }

    destUrl.setPath( destUrl.directory() );
    OrgKdeKDirNotifyInterface::emitFilesAdded( destUrl.url() );

    if (item)
        item->setOpen(true);
}
Example #14
0
KService::Ptr serviceForUrl(const KUrl & url)
{
    QString runner = url.host();
    QString id = url.fragment();

    if (id.startsWith(QLatin1Char('/'))) {
        id = id.remove(0, 1);
    }

    if (runner != QLatin1String("services")) {
        return KService::Ptr(NULL);
    }

    // URL path example: services_kde4-kate.desktop
    // or: services_firefox.desktop
    id.remove("services_");

    return KService::serviceByStorageId(id);
}
Example #15
0
void ChooseSocket::setValues(const QVariantHash &args)
{
    if (m_args == args) {
        return;
    }

    m_args = args;
    ui->addressLE->clear();
    ui->portISB->setValue(9100);
    QString deviceUri = args[KCUPS_DEVICE_URI].toString();
    KUrl url = deviceUri;
    if (url.scheme() == QLatin1String("socket")) {
        ui->addressLE->setText(url.host());
        ui->portISB->setValue(url.port(9100));
    }
    ui->addressLE->setFocus();

    m_isValid = true;
}
Example #16
0
Slave *SlaveKeeper::takeSlaveForJob(SimpleJob *job)
{
    Slave *slave = heldSlaveForJob(job);
    if (slave) {
        return slave;
    }

    KUrl url = SimpleJobPrivate::get(job)->m_url;
    // TODO take port, username and password into account
    QMultiHash<QString, Slave *>::Iterator it = m_idleSlaves.find(url.host());
    if (it == m_idleSlaves.end()) {
        it = m_idleSlaves.begin();
    }
    if (it == m_idleSlaves.end()) {
        return 0;
    }
    slave = it.value();
    m_idleSlaves.erase(it);
    return slave;
}
static QString generateKey(const KUrl& url)
{
  QString key;

  if (url.isValid()) {
    key = url.protocol();
    key += QLatin1Char(':');

    if (url.hasHost()) {
      key += url.host();
      key += QLatin1Char(':');
    }

    if (url.hasPath()) {
        key += url.path();
    }
  }

  return key;
}
Example #18
0
bool BupSlave::checkCorrectRepository(const KUrl &pUrl, QStringList &pPathInRepository) {
	// make this slave accept most URLs.. even incorrect ones. (no slash (wrong),
	// one slash (correct), two slashes (wrong), three slashes (correct))
	QString lPath;
	if(pUrl.hasHost()) {
		lPath = QLatin1String("/") + pUrl.host() + pUrl.path(KUrl::AddTrailingSlash);
	} else {
		lPath = pUrl.path(KUrl::AddTrailingSlash);
		if(!lPath.startsWith(QLatin1Char('/'))) {
			lPath.prepend(QLatin1Char('/'));
		}
	}

	if(mRepository && mRepository->isValid()) {
		if(lPath.startsWith(mRepository->objectName())) {
			lPath.remove(0, mRepository->objectName().length());
			pPathInRepository = lPath.split(QLatin1Char('/'), QString::SkipEmptyParts);
			return true;
		}
		else {
			delete mRepository;
			mRepository = NULL;
		}
	}

	pPathInRepository = lPath.split(QLatin1Char('/'), QString::SkipEmptyParts);
	QString lRepoPath = QString::fromLatin1("/");
	while(!pPathInRepository.isEmpty()) {
		// make sure the repo path will end with a slash
		lRepoPath += pPathInRepository.takeFirst();
		lRepoPath += QLatin1String("/");
		if((QFile::exists(lRepoPath + QLatin1String("objects")) &&
		    QFile::exists(lRepoPath + QLatin1String("refs"))) ||
		      (QFile::exists(lRepoPath + QLatin1String(".git/objects")) &&
		       QFile::exists(lRepoPath + QLatin1String(".git/refs")))) {
			mRepository = new Repository(NULL, lRepoPath);
			return mRepository->isValid();
		}
	}
	return false;
}
Example #19
0
SecurityOrigin::SecurityOrigin(const KUrl& url) :
      m_protocol(url.protocol().toLower())
    , m_host(url.host().toLower())
    , m_port(url.port())
    , m_domainWasSetInDOM(false)
    , m_isUnique(false)
{
    // These protocols do not create security origins; the owner frame provides the origin
    if (m_protocol == "about" || m_protocol == "javascript")
        m_protocol = "";

    // For edge case URLs that were probably misparsed, make sure that the origin is unique.
    if (m_host.isEmpty() && KProtocolInfo::protocolClass(m_protocol) == QLatin1String(":internet"))
        m_isUnique = true;

    // document.domain starts as m_host, but can be set by the DOM.
    m_domain = m_host;

    if (url.port() == -1 || isDefaultPortForProtocol(m_port, m_protocol))
        m_port = 0;
}
void KonqPixmapProvider::notifyChange( bool isHost, const QString& hostOrURL,
    const QString& iconName )
{
    KUrl u;
    if ( !isHost )
        u = hostOrURL;

    QMap<KUrl,QString>::iterator itEnd = iconMap.end();
    for ( QMap<KUrl,QString>::iterator it = iconMap.begin(); it != itEnd; ++it )
    {
        KUrl url( it.key() );
        if ( ( isHost && url.host() == hostOrURL ) ||
             ( !isHost && url.host() == u.host() && url.path() == u.path() ) )
        {
            // For host default-icons still query the favicon manager to get
            // the correct icon for pages that have an own one.
            QString icon = isHost ? KMimeType::favIconForUrl( url ) : iconName;
            if ( !icon.isEmpty() )
                *it = icon;
        }
    }

    emit changed();
}
Example #21
0
bool KShortUriFilter::filterUri( KUriFilterData& data ) const
{
 /*
  * Here is a description of how the shortURI deals with the supplied
  * data.  First it expands any environment variable settings and then
  * deals with special shortURI cases. These special cases are the "smb:"
  * URL scheme which is very specific to KDE, "#" and "##" which are
  * shortcuts for man:/ and info:/ protocols respectively. It then handles
  * local files.  Then it checks to see if the URL is valid and one that is
  * supported by KDE's IO system.  If all the above checks fails, it simply
  * lookups the URL in the user-defined list and returns without filtering
  * if it is not found. TODO: the user-defined table is currently only manually
  * hackable and is missing a config dialog.
  */

  KUrl url = data.uri();
  QString cmd = data.typedString();

  // WORKAROUND: Allow the use of '@' in the username component of a URL since
  // other browsers such as firefox in their infinite wisdom allow such blatant
  // violations of RFC 3986. BR# 69326/118413.
  if (cmd.count(QLatin1Char('@')) > 1) {
    const int lastIndex = cmd.lastIndexOf(QLatin1Char('@'));
    // Percent encode all but the last '@'.
    QString encodedCmd = QUrl::toPercentEncoding(cmd.left(lastIndex), ":/");
    encodedCmd += cmd.mid(lastIndex);
    KUrl u (encodedCmd);
    if (u.isValid()) {
      cmd = encodedCmd;
      url = u;
    }
  }

  const bool isMalformed = !url.isValid();
  QString protocol = url.protocol();

  kDebug(7023) << cmd;

  // Fix misparsing of "foo:80", QUrl thinks "foo" is the protocol and "80" is the path.
  // However, be careful not to do that for valid hostless URLs, e.g. file:///foo!
  if (!protocol.isEmpty() && url.host().isEmpty() && !url.path().isEmpty()
      && cmd.contains(':') && !KProtocolInfo::protocols().contains(protocol)) {
    protocol.clear();
  }

  //kDebug(7023) << "url=" << url << "cmd=" << cmd << "isMalformed=" << isMalformed;

  if (!isMalformed &&
      (protocol.length() == 4) &&
      (protocol != QLatin1String("http")) &&
      (protocol[0]=='h') &&
      (protocol[1]==protocol[2]) &&
      (protocol[3]=='p'))
  {
     // Handle "encrypted" URLs like: h++p://www.kde.org
     url.setProtocol( QLatin1String("http"));
     setFilteredUri( data, url);
     setUriType( data, KUriFilterData::NetProtocol );
     return true;
  }

  // TODO: Make this a bit more intelligent for Minicli! There
  // is no need to make comparisons if the supplied data is a local
  // executable and only the argument part, if any, changed! (Dawit)
  // You mean caching the last filtering, to try and reuse it, to save stat()s? (David)

  const QString starthere_proto = QL1S("start-here:");
  if (cmd.indexOf(starthere_proto) == 0 )
  {
    setFilteredUri( data, KUrl("system:/") );
    setUriType( data, KUriFilterData::LocalDir );
    return true;
  }

  // Handle MAN & INFO pages shortcuts...
  const QString man_proto = QL1S("man:");
  const QString info_proto = QL1S("info:");
  if( cmd[0] == '#' ||
      cmd.indexOf( man_proto ) == 0 ||
      cmd.indexOf( info_proto ) == 0 )
  {
    if( cmd.left(2) == QL1S("##") )
      cmd = QL1S("info:/") + cmd.mid(2);
    else if ( cmd[0] == '#' )
      cmd = QL1S("man:/") + cmd.mid(1);

    else if ((cmd==info_proto) || (cmd==man_proto))
      cmd+='/';

    setFilteredUri( data, KUrl( cmd ));
    setUriType( data, KUriFilterData::Help );
    return true;
  }

  // Detect UNC style (aka windows SMB) URLs
  if ( cmd.startsWith( QLatin1String( "\\\\") ) )
  {
    // make sure path is unix style
    cmd.replace('\\', '/');
    cmd.prepend( QLatin1String( "smb:" ) );
    setFilteredUri( data, KUrl( cmd ));
    setUriType( data, KUriFilterData::NetProtocol );
    return true;
  }

  bool expanded = false;

  // Expanding shortcut to HOME URL...
  QString path;
  QString ref;
  QString query;
  QString nameFilter;

  if (KUrl::isRelativeUrl(cmd) && QDir::isRelativePath(cmd)) {
     path = cmd;
     //kDebug(7023) << "path=cmd=" << path;
  } else {
    if (url.isLocalFile())
    {
      //kDebug(7023) << "hasRef=" << url.hasRef();
      // Split path from ref/query
      // but not for "/tmp/a#b", if "a#b" is an existing file,
      // or for "/tmp/a?b" (#58990)
      if( ( url.hasRef() || !url.query().isEmpty() )
           && !url.path().endsWith(QL1S("/")) ) // /tmp/?foo is a namefilter, not a query
      {
        path = url.path();
        ref = url.ref();
        //kDebug(7023) << "isLocalFile set path to " << stringDetails( path );
        //kDebug(7023) << "isLocalFile set ref to " << stringDetails( ref );
        query = url.query();
        if (path.isEmpty() && url.hasHost())
          path = '/';
      }
      else
      {
        path = cmd;
        //kDebug(7023) << "(2) path=cmd=" << path;
      }
    }
  }

  if( path[0] == '~' )
  {
    int slashPos = path.indexOf('/');
    if( slashPos == -1 )
      slashPos = path.length();
    if( slashPos == 1 )   // ~/
    {
      path.replace ( 0, 1, QDir::homePath() );
    }
    else // ~username/
    {
      const QString userName (path.mid( 1, slashPos-1 ));
      KUser user (userName);
      if( user.isValid() && !user.homeDir().isEmpty())
      {
        path.replace (0, slashPos, user.homeDir());
      }
      else
      {
        if (user.isValid()) {
          setErrorMsg(data, i18n("<qt><b>%1</b> does not have a home folder.</qt>", userName));
        } else {
          setErrorMsg(data, i18n("<qt>There is no user called <b>%1</b>.</qt>", userName));
        }
        setUriType( data, KUriFilterData::Error );
        // Always return true for error conditions so
        // that other filters will not be invoked !!
        return true;
      }
    }
    expanded = true;
  }
  else if ( path[0] == '$' ) {
    // Environment variable expansion.
    if ( sEnvVarExp.indexIn( path ) == 0 )
    {
      QByteArray exp = qgetenv( path.mid( 1, sEnvVarExp.matchedLength() - 1 ).toLocal8Bit().data() );
      if(! exp.isNull())
      {
        path.replace( 0, sEnvVarExp.matchedLength(), QString::fromLocal8Bit(exp.constData()) );
        expanded = true;
      }
    }
  }

  if ( expanded || cmd.startsWith( '/' ) )
  {
    // Look for #ref again, after $ and ~ expansion (testcase: $QTDIR/doc/html/functions.html#s)
    // Can't use KUrl here, setPath would escape it...
    const int pos = path.indexOf('#');
    if ( pos > -1 )
    {
      const QString newPath = path.left( pos );
      if ( QFile::exists( newPath ) )
      {
        ref = path.mid( pos + 1 );
        path = newPath;
        //kDebug(7023) << "Extracted ref: path=" << path << " ref=" << ref;
      }
    }
  }


  bool isLocalFullPath = (!path.isEmpty() && path[0] == '/');

  // Checking for local resource match...
  // Determine if "uri" is an absolute path to a local resource  OR
  // A local resource with a supplied absolute path in KUriFilterData
  const QString abs_path = data.absolutePath();

  const bool canBeAbsolute = (protocol.isEmpty() && !abs_path.isEmpty());
  const bool canBeLocalAbsolute = (canBeAbsolute && abs_path[0] =='/' && !isMalformed);
  bool exists = false;

  /*kDebug(7023) << "abs_path=" << abs_path
               << "protocol=" << protocol
               << "canBeAbsolute=" << canBeAbsolute
               << "canBeLocalAbsolute=" << canBeLocalAbsolute
               << "isLocalFullPath=" << isLocalFullPath;*/

  KDE_struct_stat buff;
  if ( canBeLocalAbsolute )
  {
    QString abs = QDir::cleanPath( abs_path );
    // combine absolute path (abs_path) and relative path (cmd) into abs_path
    int len = path.length();
    if( (len==1 && path[0]=='.') || (len==2 && path[0]=='.' && path[1]=='.') )
        path += '/';
    //kDebug(7023) << "adding " << abs << " and " << path;
    abs = QDir::cleanPath(abs + '/' + path);
    //kDebug(7023) << "checking whether " << abs << " exists.";
    // Check if it exists
    if( KDE::stat( abs, &buff ) == 0 )
    {
      path = abs; // yes -> store as the new cmd
      exists = true;
      isLocalFullPath = true;
    }
  }

  if (isLocalFullPath && !exists && !isMalformed) {
    exists = ( KDE::stat( path, &buff ) == 0 );

    if ( !exists ) {
      // Support for name filter (/foo/*.txt), see also KonqMainWindow::detectNameFilter
      // If the app using this filter doesn't support it, well, it'll simply error out itself
      int lastSlash = path.lastIndexOf( '/' );
      if ( lastSlash > -1 && path.indexOf( ' ', lastSlash ) == -1 ) // no space after last slash, otherwise it's more likely command-line arguments
      {
        QString fileName = path.mid( lastSlash + 1 );
        QString testPath = path.left( lastSlash + 1 );
        if ( ( fileName.indexOf( '*' ) != -1 || fileName.indexOf( '[' ) != -1 || fileName.indexOf( '?' ) != -1 )
           && KDE::stat( testPath, &buff ) == 0 )
        {
          nameFilter = fileName;
          //kDebug(7023) << "Setting nameFilter to " << nameFilter;
          path = testPath;
          exists = true;
        }
      }
    }
  }

  //kDebug(7023) << "path =" << path << " isLocalFullPath=" << isLocalFullPath << " exists=" << exists;
  if( exists )
  {
    KUrl u;
    u.setPath(path);
    //kDebug(7023) << "ref=" << stringDetails(ref) << " query=" << stringDetails(query);
    u.setRef(ref);
    u.setQuery(query);

    if (!KAuthorized::authorizeUrlAction( QLatin1String("open"), KUrl(), u))
    {
      // No authorization, we pretend it's a file will get
      // an access denied error later on.
      setFilteredUri( data, u );
      setUriType( data, KUriFilterData::LocalFile );
      return true;
    }

    // Can be abs path to file or directory, or to executable with args
    bool isDir = S_ISDIR( buff.st_mode );
    if( !isDir && access ( QFile::encodeName(path).data(), X_OK) == 0 )
    {
      //kDebug(7023) << "Abs path to EXECUTABLE";
      setFilteredUri( data, u );
      setUriType( data, KUriFilterData::Executable );
      return true;
    }

    // Open "uri" as file:/xxx if it is a non-executable local resource.
    if( isDir || S_ISREG( buff.st_mode ) )
    {
      //kDebug(7023) << "Abs path as local file or directory";
      if ( !nameFilter.isEmpty() )
        u.setFileName( nameFilter );
      setFilteredUri( data, u );
      setUriType( data, ( isDir ) ? KUriFilterData::LocalDir : KUriFilterData::LocalFile );
      return true;
    }

    // Should we return LOCAL_FILE for non-regular files too?
    kDebug(7023) << "File found, but not a regular file nor dir... socket?";
  }

  if( data.checkForExecutables())
  {
    // Let us deal with possible relative URLs to see
    // if it is executable under the user's $PATH variable.
    // We try hard to avoid parsing any possible command
    // line arguments or options that might have been supplied.
    QString exe = removeArgs( cmd );
    //kDebug(7023) << "findExe with" << exe;

    if (!KStandardDirs::findExe( exe ).isNull() )
    {
      //kDebug(7023) << "EXECUTABLE  exe=" << exe;
      setFilteredUri( data, KUrl::fromPath( exe ));
      // check if we have command line arguments
      if( exe != cmd )
          setArguments(data, cmd.right(cmd.length() - exe.length()));
      setUriType( data, KUriFilterData::Executable );
      return true;
    }
  }

  // Process URLs of known and supported protocols so we don't have
  // to resort to the pattern matching scheme below which can possibly
  // slow things down...
  if ( !isMalformed && !isLocalFullPath && !protocol.isEmpty() )
  {
    //kDebug(7023) << "looking for protocol " << protocol;
    if ( KProtocolInfo::isKnownProtocol( protocol ) )
    {
      setFilteredUri( data, url );
      if ( protocol == QL1S("man") || protocol == QL1S("help") )
        setUriType( data, KUriFilterData::Help );
      else
        setUriType( data, KUriFilterData::NetProtocol );
      return true;
    }
  }

  // Short url matches
  if ( !cmd.contains( ' ' ) )
  {
    // Okay this is the code that allows users to supply custom matches for
    // specific URLs using Qt's regexp class. This is hard-coded for now.
    // TODO: Make configurable at some point...
    Q_FOREACH(const URLHint& hint, m_urlHints)
    {
      if (hint.regexp.indexIn(cmd) == 0)
      {
        //kDebug(7023) << "match - prepending" << (*it).prepend;
        const QString cmdStr = hint.prepend + cmd;
        KUrl url(cmdStr);
        if (KProtocolInfo::isKnownProtocol(url))
        {
          setFilteredUri( data, url );
          setUriType( data, hint.type );
          return true;
        }
      }
    }

    // No protocol and not malformed means a valid short URL such as kde.org or
    // [email protected]. However, it might also be valid only because it lacks
    // the scheme component, e.g. www.kde,org (illegal ',' before 'org'). The
    // check below properly deciphers the difference between the two and sends
    // back the proper result.
    if (protocol.isEmpty() && isPotentialShortURL(cmd))
    {
      QString urlStr = data.defaultUrlScheme();
      if (urlStr.isEmpty())
          urlStr = m_strDefaultUrlScheme;

      const int index = urlStr.indexOf(QL1C(':'));
      if (index == -1 || !KProtocolInfo::isKnownProtocol(urlStr.left(index)))
        urlStr += QL1S("://");
      urlStr += cmd;

      KUrl url (urlStr);
      if (url.isValid())
      {
        setFilteredUri(data, url);
        setUriType(data, KUriFilterData::NetProtocol);
      }
      else if (KProtocolInfo::isKnownProtocol(url.protocol()))
      {
        setFilteredUri(data, data.uri());
        setUriType(data, KUriFilterData::Error);
      }
      return true;
    }
  }
Example #22
0
QNetworkReply *AccessManager::createRequest(Operation op, const QNetworkRequest &req, QIODevice *outgoingData)
{
    const KUrl reqUrl (req.url());

    if (!d->externalContentAllowed &&
        !KDEPrivate::AccessManagerReply::isLocalRequest(reqUrl) &&
        reqUrl.scheme() != QL1S("data")) {
        kDebug( 7044 ) << "Blocked: " << reqUrl;
        return new KDEPrivate::AccessManagerReply(op, req, QNetworkReply::ContentAccessDenied, i18n("Blocked request."), this);
    }

    // Check if the internal ignore content disposition header is set.
    const bool ignoreContentDisposition = req.hasRawHeader("x-kdewebkit-ignore-disposition");

    // Retrieve the KIO meta data...
    KIO::MetaData metaData;
    d->setMetaDataForRequest(req, metaData);

    KIO::SimpleJob *kioJob = 0;

    switch (op) {
        case HeadOperation: {
            //kDebug( 7044 ) << "HeadOperation:" << reqUrl;
            kioJob = KIO::mimetype(reqUrl, KIO::HideProgressInfo);
            break;
        }
        case GetOperation: {
            //kDebug( 7044 ) << "GetOperation:" << reqUrl;
            if (!reqUrl.path().isEmpty() || reqUrl.host().isEmpty())
                kioJob = KIO::get(reqUrl, KIO::NoReload, KIO::HideProgressInfo);
            else
                kioJob = KIO::stat(reqUrl, KIO::HideProgressInfo);

            // WORKAROUND: Avoid the brain damaged stuff QtWebKit does when a POST
            // operation is redirected! See BR# 268694.
            metaData.remove(QL1S("content-type")); // Remove the content-type from a GET/HEAD request!
            break;
        }
        case PutOperation: {
            //kDebug( 7044 ) << "PutOperation:" << reqUrl;
            if (outgoingData)
                kioJob = KIO::storedPut(outgoingData->readAll(), reqUrl, -1, KIO::HideProgressInfo);
            else
                kioJob = KIO::put(reqUrl, -1, KIO::HideProgressInfo);
            break;
        }
        case PostOperation: {
            kioJob = KIO::http_post(reqUrl, outgoingData, sizeFromRequest(req), KIO::HideProgressInfo);
            if (!metaData.contains(QL1S("content-type")))  {
                const QVariant header = req.header(QNetworkRequest::ContentTypeHeader);
                if (header.isValid()) {
                    metaData.insert(QL1S("content-type"),
                                    (QL1S("Content-Type: ") + header.toString()));
                } else {
                    metaData.insert(QL1S("content-type"),
                                    QL1S("Content-Type: application/x-www-form-urlencoded"));
                }
            }
            break;
        }
        case DeleteOperation: {
            //kDebug(7044) << "DeleteOperation:" << reqUrl;
            kioJob = KIO::http_delete(reqUrl, KIO::HideProgressInfo);
            break;
        }
        case CustomOperation: {
            const QByteArray& method = req.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray();
            //kDebug(7044) << "CustomOperation:" << reqUrl << "method:" << method << "outgoing data:" << outgoingData;

            if (method.isEmpty()) {
                return new KDEPrivate::AccessManagerReply(op, req, QNetworkReply::ProtocolUnknownError, i18n("Unknown HTTP verb."), this);
            }

            if (outgoingData)
                kioJob = KIO::http_post(reqUrl, outgoingData, sizeFromRequest(req), KIO::HideProgressInfo);
            else
                kioJob = KIO::get(reqUrl, KIO::NoReload, KIO::HideProgressInfo);

            metaData.insert(QL1S("CustomHTTPMethod"), method);
            break;
        }
        default: {
            kWarning(7044) << "Unsupported KIO operation requested! Defering to QNetworkAccessManager...";
            return QNetworkAccessManager::createRequest(op, req, outgoingData);
        }
    }

    // Set the job priority
    switch (req.priority()) {
    case QNetworkRequest::HighPriority:
        KIO::Scheduler::setJobPriority(kioJob, -5);
        break;
    case QNetworkRequest::LowPriority:
        KIO::Scheduler::setJobPriority(kioJob, 5);
        break;
    default:
        break;
    }

    KDEPrivate::AccessManagerReply *reply;

    /*
      NOTE: Here we attempt to handle synchronous XHR requests. Unfortunately,
      due to the fact that QNAM is both synchronous and multi-thread while KIO
      is completely the opposite (asynchronous and not thread safe), the code
      below might cause crashes like the one reported in bug# 287778 (nested
      event loops are inherently dangerous).

      Unfortunately, all attempts to address the crash has so far failed due to
      the many regressions they caused, e.g. bug# 231932 and 297954. Hence, until
      a solution is found, we have to live with the side effects of creating
      nested event loops.
    */
    if (req.attribute(gSynchronousNetworkRequestAttribute).toBool()) {
        KUrl finalURL;
        QByteArray data;

        if (KIO::NetAccess::synchronousRun(kioJob, d->window, &data, &finalURL, &metaData)) {
            reply = new KDEPrivate::AccessManagerReply(op, req, data, finalURL, metaData, this);
            kDebug(7044) << "Synchronous XHR:" << reply << reqUrl;
        } else {
            kWarning(7044) << "Failed to create a synchronous XHR for" << reqUrl;
            reply = new KDEPrivate::AccessManagerReply(op, req, QNetworkReply::UnknownNetworkError, kioJob->errorText(), this);
        }
    } else {
        // Set the window on the the KIO ui delegate
        if (d->window) {
            kioJob->ui()->setWindow(d->window);
        }

        // Disable internal automatic redirection handling
        kioJob->setRedirectionHandlingEnabled(false);

        // Set the job priority
        switch (req.priority()) {
        case QNetworkRequest::HighPriority:
            KIO::Scheduler::setJobPriority(kioJob, -5);
            break;
        case QNetworkRequest::LowPriority:
            KIO::Scheduler::setJobPriority(kioJob, 5);
            break;
        default:
            break;
        }

        // Set the meta data for this job...
        kioJob->setMetaData(metaData);

        // Create the reply...
        reply = new KDEPrivate::AccessManagerReply(op, req, kioJob, d->emitReadyReadOnMetaDataChange, this);
        //kDebug(7044) << reply << reqUrl;
    }

    if (ignoreContentDisposition && reply) {
        //kDebug(7044) << "Content-Disposition WILL BE IGNORED!";
        reply->setIgnoreContentDisposition(ignoreContentDisposition);
    }

    return reply;
}
Example #23
0
/** No descriptions */
void QuantaCommon::dirCreationError(QWidget *widget, const KUrl& url)
{
  KMessageBox::error(widget, i18n("<qt>Cannot create folder<br /><b>%1</b>.<br />Check that you have write permission in the parent folder or that the connection to<br /><b>%2</b><br />is valid.</qt>",
      url.pathOrUrl(),
      url.protocol()+"://"+url.user()+"@"+url.host()));}