Example #1
0
void DocCHMPlugin::setCatalogURL(DocumentationCatalogItem* item)
{
    KURL chmURL = item->url();
    chmURL.setProtocol("ms-its");
    chmURL.addPath("/");
    item->setURL(chmURL);
}
Example #2
0
void RemoteProtocol::listDir(const KURL &url)
{
    kdDebug(1220) << "RemoteProtocol::listDir: " << url << endl;

    if(url.path().length() <= 1)
    {
        listRoot();
        return;
    }

    int second_slash_idx = url.path().find('/', 1);
    QString root_dirname = url.path().mid(1, second_slash_idx - 1);

    KURL target = m_impl.findBaseURL(root_dirname);
    kdDebug(1220) << "possible redirection target : " << target << endl;
    if(target.isValid())
    {
        target.addPath(url.path().remove(0, second_slash_idx));
        redirection(target);
        finished();
        return;
    }

    error(KIO::ERR_MALFORMED_URL, url.prettyURL());
}
Example #3
0
void
NfsDeviceHandler::getURL( KURL &absolutePath, const KURL &relativePath )
{
    absolutePath.setPath( m_mountPoint );
    absolutePath.addPath( relativePath.path() );
    absolutePath.cleanPath();
}
Example #4
0
KURL SystemDirNotify::toSystemURL(const KURL &url)
{
	kdDebug() << "SystemDirNotify::toSystemURL(" << url << ")" << endl;

	init();
	QMap<KURL,KURL>::const_iterator it = m_urlMap.begin();
	QMap<KURL,KURL>::const_iterator end = m_urlMap.end();

	for (; it!=end; ++it)
	{
		KURL base = it.key();

		if ( base.isParentOf(url) )
		{
			QString path = KURL::relativePath(base.path(),
			                                  url.path());
			KURL result = it.data();
			result.addPath(path);
			result.cleanPath();
			kdDebug() << result << endl;
			return result;
		}
	}

	kdDebug() << "KURL()" << endl;
	return KURL();
}
Example #5
0
void RemoteProtocol::stat(const KURL &url)
{
    kdDebug(1220) << "RemoteProtocol::stat: " << url << endl;

    QString path = url.path();
    if(path.isEmpty() || path == "/")
    {
        // The root is "virtual" - it's not a single physical directory
        KIO::UDSEntry entry;
        m_impl.createTopLevelEntry(entry);
        statEntry(entry);
        finished();
        return;
    }

    if(m_impl.isWizardURL(url))
    {
        KIO::UDSEntry entry;
        if(m_impl.createWizardEntry(entry))
        {
            statEntry(entry);
            finished();
        }
        else
        {
            error(KIO::ERR_DOES_NOT_EXIST, url.prettyURL());
        }
        return;
    }

    int second_slash_idx = url.path().find('/', 1);
    QString root_dirname = url.path().mid(1, second_slash_idx - 1);

    if(second_slash_idx == -1 || ((int)url.path().length()) == second_slash_idx + 1)
    {
        KIO::UDSEntry entry;
        if(m_impl.statNetworkFolder(entry, root_dirname))
        {
            statEntry(entry);
            finished();
            return;
        }
    }
    else
    {
        KURL target = m_impl.findBaseURL(root_dirname);
        kdDebug(1220) << "possible redirection target : " << target << endl;
        if(target.isValid())
        {
            target.addPath(url.path().remove(0, second_slash_idx));
            redirection(target);
            finished();
            return;
        }
    }

    error(KIO::ERR_MALFORMED_URL, url.prettyURL());
}
Example #6
0
void JobTest::copyFileToSystem(bool resolve_local_urls)
{
    kdDebug() << k_funcinfo << resolve_local_urls << endl;
    extern KIO_EXPORT bool kio_resolve_local_urls;
    kio_resolve_local_urls = resolve_local_urls;

    const QString src = homeTmpDir() + "fileFromHome";
    createTestFile(src);
    KURL u;
    u.setPath(src);
    KURL d = systemTmpDir();
    d.addPath("fileFromHome_copied");

    kdDebug() << "copying " << u << " to " << d << endl;

    // copy the file with file_copy
    KIO::FileCopyJob *job = KIO::file_copy(u, d);
    connect(job, SIGNAL(mimetype(KIO::Job *, const QString &)), this, SLOT(slotMimetype(KIO::Job *, const QString &)));
    bool ok = KIO::NetAccess::synchronousRun(job, 0);
    assert(ok);

    QString dest = realSystemPath() + "fileFromHome_copied";

    assert(QFile::exists(dest));
    assert(QFile::exists(src)); // still there

    {
        // do NOT check that the timestamp is the same.
        // It can't work with file_copy when it uses the datapump,
        // unless we use setModificationTime in the app code.
    }

    // Check mimetype
    kdDebug() << m_mimetype << endl;
    // There's no mimemagic determination in kio_file in kde3. Fixing this for kde4...
    assert(m_mimetype == "application/octet-stream");
    // assert( m_mimetype == "text/plain" );

    // cleanup and retry with KIO::copy()
    QFile::remove(dest);
    ok = KIO::NetAccess::dircopy(u, d, 0);
    assert(ok);
    assert(QFile::exists(dest));
    assert(QFile::exists(src)); // still there
    {
        // check that the timestamp is the same (#79937)
        QFileInfo srcInfo(src);
        QFileInfo destInfo(dest);
        assert(srcInfo.lastModified() == destInfo.lastModified());
    }

    // restore normal behavior
    kio_resolve_local_urls = true;
}
Example #7
0
bool HomeImpl::realURL(const QString &name, const QString &path, KURL &url)
{
	KUser user(name);
	
	if ( user.isValid() )
	{
		KURL res;
		res.setPath( user.homeDir() );
		res.addPath(path);
		url = res;
		return true;
	}
	
	return false;
}
Example #8
0
bool MediaImpl::realURL(const QString &name, const QString &path, KURL &url)
{
    bool ok;
    Medium m = findMediumByName(name, ok);
    if(!ok)
        return false;

    ok = ensureMediumMounted(m);
    if(!ok)
        return false;

    url = m.prettyBaseURL();
    url.addPath(path);
    return true;
}
Example #9
0
bool Manager::copyAppData(const KURL& src, const QString& subdir, const QString& fileName) {
	QString dir;
	//let saveLocation find and create the appropriate place to
	//store the templates (usually $HOME/.kde/share/apps/kile/templates)
	dir = KGlobal::dirs()->saveLocation("appdata", subdir, true);
	KURL targetURL = KURL::fromPathOrURL(dir);
	targetURL.addPath(fileName);

	//if a directory is found
	if (!dir.isNull()) {
		return KIO::NetAccess::copy(src, targetURL, kapp->mainWidget());
	}
	else {
		KMessageBox::error(0, i18n("Could not find a folder to save %1 to.\nCheck whether you have a .kde folder with write permissions in your home folder.").arg(fileName));
		return false;
	}
}
Example #10
0
QString DocCHMPlugin::getSpecialData(const QString& name, KURL url) {
    QString ret = "";
    url.setProtocol("ms-its");
    
    url.addPath("/:" + name);
    QString tmpFile;
    if( KIO::NetAccess::download( url, tmpFile, 0 ) )
    {
        std::filebuf fb;
        fb.open (tmpFile.ascii(), std::ios::in);
        std::istream is(&fb);
        char buf[5000] = " ";
        while(is.good()) {
            is.getline(buf, 5000);
            ret += buf; ret += "\n";
        }
        fb.close();
        KIO::NetAccess::removeTempFile( tmpFile );
    } else {
        kdDebug(9002) << "DocCHMPlugin::getSpecialData could not download data from " << url.url() << endl;
    }
    return ret;
}
Example #11
0
void TrashProtocol::restore(const KURL &trashURL)
{
    int trashId;
    QString fileId, relativePath;
    bool ok = TrashImpl::parseURL(trashURL, trashId, fileId, relativePath);
    if(!ok)
    {
        error(KIO::ERR_SLAVE_DEFINED, i18n("Malformed URL %1").arg(trashURL.prettyURL()));
        return;
    }
    TrashedFileInfo info;
    ok = impl.infoForFile(trashId, fileId, info);
    if(!ok)
    {
        error(impl.lastErrorCode(), impl.lastErrorMessage());
        return;
    }
    KURL dest;
    dest.setPath(info.origPath);
    if(!relativePath.isEmpty())
        dest.addPath(relativePath);

    // Check that the destination directory exists, to improve the error code in case it doesn't.
    const QString destDir = dest.directory();
    KDE_struct_stat buff;
    if(KDE_lstat(QFile::encodeName(destDir), &buff) == -1)
    {
        error(KIO::ERR_SLAVE_DEFINED,
              i18n("The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. "
                   "You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it.")
                  .arg(destDir));
        return;
    }

    copyOrMove(trashURL, dest, false /*overwrite*/, Move);
}
Example #12
0
    void addKorganizerChanges( Change::List &changes )
    {
      KURL freeBusyBaseUrl;
      // usrWriteConfig() is called first, so kolab1Legacy is correct
      if ( KolabConfig::self()->kolab1Legacy() ) {
        freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() +
                                "/freebusy/";

      ChangeConfig *c = new ChangeConfig;
      c->file = "korganizerrc";
      c->group = "FreeBusy";

      c->name = "FreeBusyPublishUrl";

      QString user = KolabConfig::self()->user();
      // We now use the full email address in the freebusy URL
      //int pos = user.find( "@" );
      //if ( pos > 0 ) user = user.left( pos );

      KURL publishURL = freeBusyBaseUrl;
      publishURL.addPath( user + ".ifb" ); // this encodes the '@' in the username
      c->value = publishURL.url();

      changes.append( c );

      } else {
          // Kolab2: only need FreeBusyRetrieveUrl
          // "Uploading" is done by triggering a server-side script with an HTTP GET
          // (done by kmail)
          freeBusyBaseUrl = "https://" + KolabConfig::self()->server() +
                            "/freebusy/";
      }

      ChangeConfig *c = new ChangeConfig;
      c->file = "korganizerrc";
      c->group = "FreeBusy";
      c->name = "FreeBusyRetrieveUrl";
      c->value = freeBusyBaseUrl.url();
      changes.append( c );

      // Use full email address for retrieval of free/busy lists
      c = new ChangeConfig;
      c->file = "korganizerrc";
      c->group = "FreeBusy";
      c->name = "FreeBusyFullDomainRetrieval";
      c->value = "true";
      changes.append( c );

      c = new ChangeConfig;
      c->file = "korganizerrc";
      c->group = "Group Scheduling";
      c->name = "Use Groupware Communication";
      c->value = "true";
      changes.append( c );

      // Use identity "from control center", i.e. from emaildefaults
      c = new ChangeConfig;
      c->file = "korganizerrc";
      c->group = "Personal Settings";
      c->name = "Use Control Center Email";
      c->value = "true";
      changes.append( c );
    }
Example #13
0
/******************************************************************************
* Check whether the specified sound file exists.
* Note that KAudioPlayer::play() can only cope with local files.
*/
bool SoundDlg::checkFile()
{
    mFileName = mFileEdit->text();
    KURL url;
    if(KURL::isRelativeURL(mFileName))
    {
        // It's not an absolute URL, so check for an absolute path
        QFileInfo f(mFileName);
        if(!f.isRelative())
            url.setPath(mFileName);
    }
    else
        url = KURL::fromPathOrURL(mFileName);   // it's an absolute URL

    if(!url.isEmpty())
    {
        // It's an absolute path or URL.
        // Only allow local files for KAudioPlayer.
        if(url.isLocalFile()  &&  KIO::NetAccess::exists(url, true, this))
        {
            mFileName = url.path();
            return true;
        }
    }
    else
    {
        // It's a relative path.
        // Find the first sound resource that contains files.
        QStringList soundDirs = KGlobal::dirs()->resourceDirs("sound");
        if(!soundDirs.isEmpty())
        {
            QDir dir;
            dir.setFilter(QDir::Files | QDir::Readable);
            for(QStringList::ConstIterator it = soundDirs.begin();  it != soundDirs.end();  ++it)
            {
                dir = *it;
                if(dir.isReadable() && dir.count() > 2)
                {
                    url.setPath(*it);
                    url.addPath(mFileName);
                    if(KIO::NetAccess::exists(url, true, this))
                    {
                        mFileName = url.path();
                        return true;
                    }
                }
            }
        }
        url.setPath(QDir::homeDirPath());
        url.addPath(mFileName);
        if(KIO::NetAccess::exists(url, true, this))
        {
            mFileName = url.path();
            return true;
        }
    }

    KMessageBox::sorry(this, i18n("File not found"));
    mFileName = QString::null;
    return false;
}
Example #14
0
/* ---------------------------------------------------------------------------------- */
void ChmProtocol::get( const KURL& url )
{
    /** When :catalog is appended to the end, a plain-text representation of the catalog
      * is given out where each entry consists of four lines, an integer representing the parent
      * of the node, an integer representing a node's ID, the Title of the Node, and it's hyperlink.
      * When :contents is appended, all contained htm- and html-files will be printed, each in a line.
      */
    kdDebug() << "kio_chm::get(const KURL& url) " << url.path() << endl;

    bool catalog = false;
    bool contents = false;
    QString bigpath = url.path();

    if(bigpath.endsWith(":catalog")) {
        catalog = true;
        int len = QString(":catalog").length();
        bigpath.remove(bigpath.length() - len, len);   ///strip :catalog from the end
    }

    if(bigpath.endsWith(":contents")) {
        contents = true;
        int len = QString(":contents").length();
        bigpath.remove(bigpath.length() - len, len);   ///strip :catalog from the end
    }

    QString path;
    if ( !checkNewFile( bigpath, path ) ) {
        error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
        return;
    }


    if (m_dirMap.find(path) == m_dirMap.end()) {
        error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
        return;
    }

    QByteArray theData;

    //init..
    //added by lucida [email protected]
    QString fname = QString();
    QString chmpath = QString();
    KTempFile f("",".html");
    fname = f.name();
    QTextStream *t = f.textStream();
    QString firstPage = QString("");
    QString m_strIndex = QString("");
    QString tmpstr = QString("");
    bool m_bIndex = 0;


    if(contents) {
        QString output;
        KURL u = url;

        ChmDirectoryMap::Iterator it;
        for ( it = m_dirMap.begin(); it != m_dirMap.end(); ++it) {
            u.setPath(bigpath);
            u.addPath(it.key());
            output += u.prettyURL() + "\n";
        }

        data(output.local8Bit());
        processedSize(output.length());
        finished();
        return;
    }


    //try get some page to display, if the chm missing index
    ChmDirectoryMap::Iterator it;
    for ( it = m_dirMap.begin(); it != m_dirMap.end(); ++it) {
        tmpstr.sprintf("%s", it.key().latin1());
        if ((m_strIndex == "") &&
                (tmpstr.endsWith(".htm") || tmpstr.endsWith(".html")))
            m_strIndex = tmpstr;
        if ((tmpstr == "/index.htm") || (tmpstr == "/index.html")) {
            m_strIndex = tmpstr;
            break;
        }
    }
    m_strIndex.remove(0,1);


    if (path == "/" || catalog) {
        bool htmlOutput = !catalog;
        int offset = m_dirMap["/@contents"].offset;
        int length = m_dirMap["/@contents"].length;
        theData.setRawData(&m_contents[offset], length);
        QString s(theData);
        QString output;

        QRegExp object("<OBJECT type=\"text/sitemap\">(.*)</OBJECT>", false);
        object.setMinimal(true);

        QRegExp nameParam("<param name=\"Name\" value=\"(.*)\">", false);
        nameParam.setMinimal(true);

        QRegExp localParam("<param name=\"Local\" value=\"(.*)\">", false);
        localParam.setMinimal(true);

        QRegExp mergeParam("<param name=\"Merge\" value=\"(.*)\">", false);
        mergeParam.setMinimal(true);

        std::stack<int> parents;
        int counter = 1;
        int current = 0;
        int old = 0, pos = 0;
        parents.push(0);
        while ((pos = s.find(object, pos)) != -1) {
            if(htmlOutput) output += s.mid(old, pos - old);
            if(catalog) {
                QRegExp ex("<UL>|</UL>", false);
                ex.setMinimal(true);
                QString ms = s.mid(old, pos - old);
                int pos = 0;
                while( (pos = ms.find(ex, pos)) != -1) {
                    if(ms.mid(pos, 4) == "<UL>") {
                        parents.push(current);
                    } else {
                        if(parents.empty()) {
                        } else {
                            current = parents.top();
                            parents.pop();
                        }
                    }
                    pos++;
                }
            }
            pos += object.matchedLength();
            old = pos;
            QString obj = object.cap(1);
            QString name, local;
            if (obj.find(nameParam) != -1) {
                name = nameParam.cap(1);
                if (obj.find(localParam) != -1) {
                    local = localParam.cap(1);
                    //output += "<a href=\"" + local + "\">" + name + "</a>";
                    //added by lucida [email protected]
                    if (local != "" && local != "/") {
                        if(!catalog) {
                            output += "<a target=\"browse\" href=\"" + url.url() + local + "\">" + name + "</a>";
                        } else {
                            current = counter;
                            ++counter;
                            KURL u = url;
                            u.setPath(bigpath + local);
                            QString str;
                            output += str.sprintf("%i\n%i\n", parents.top(), current);
                            output += name + "\n" + u.prettyURL() + "\n";
                        }
                        m_bIndex = 1;
                        if (firstPage == "") firstPage = url.url()+QString::fromLocal8Bit(local.latin1());
                    }
                    else if(htmlOutput) output += name;
                } else {
                    if(htmlOutput) output += name;
                }
            }
            if (obj.find(mergeParam) != -1 && htmlOutput) {
                QString link = mergeParam.cap(1);
                QString href = link.left(link.find("::"));
                QString path = m_chmFile.left(m_chmFile.findRev("/") + 1);
                //output += " (<a href=\"" + path + href + "\">link</a>)";
                m_bIndex = 1;
                output += " (<a target=\"browse\" href=\"" + url.url() + path + href + "\">link</a>)";
                if (firstPage == "") firstPage = url.url()+QString::fromLocal8Bit(local.latin1());
            }
        }
        if(htmlOutput) output += s.mid(old);

        //set left pane
        //added by lucida, [email protected]
        QString lframe = QString("</HEAD><FRAMESET COLS=\"25%,*\">\n");
        lframe += "<FRAME NAME=\"index\" src=\"file:"+ fname+"\"" + " marginwidth=\"0\"></FRAME>\n";
        if (!m_bIndex) {
            lframe = "</HEAD><FRAMESET>";
            firstPage = url.url() + QString::fromLocal8Bit(m_strIndex.latin1());
        }
        theData.resetRawData(&m_contents[offset], length);
        //KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( output, path );
        //kdDebug() << "Emitting mimetype " << result->mimeType() << endl;
        //mimeType( result->mimeType() );
        /*        QCString output1 = (QCString)(output.latin1());
                data(output1);
                processedSize(output1.length());*/

        //construct the frame
        //added by lucida [email protected]
        QString framestr = QString("<HTML><HEAD>\n");
        framestr += lframe;
        framestr += "<FRAME NAME=\"browse\" src=\"" + firstPage + "\">\n";
        framestr += "</FRAME>\n";
        framestr += "</FRAMESET></HTML>";
        //write index file
        //added by lucida [email protected]
        *t << QString::fromLocal8Bit(output.latin1()) << endl;

        if(catalog) {
            data(output.local8Bit());
            processedSize(output.length());
        } else {
            data(framestr.local8Bit());
            processedSize(framestr.length());
        }
    } else {
        int offset = m_dirMap[path].offset;
        int length = m_dirMap[path].length;
        totalSize(length);
        theData.setRawData(&m_contents[offset], length);

        KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType( theData, path );
        kdDebug() << "Emitting mimetype " << result->mimeType() << endl;
        mimeType( result->mimeType() );
        data(theData);
        theData.resetRawData(&m_contents[offset], length);
        processedSize(length);
    }

    finished();
}
Example #15
0
void Project::slotRemove(const KURL& urlToRemove)
{
  emit statusMsg(i18n("Removing files..."));
  progressBar->setTotalSteps(d->m_projectFiles.count());
  progressBar->setValue(0);
  progressBar->setTextEnabled(true);

  KURL url;
  bool isFolder = d->m_projectFiles.isFolder(urlToRemove);
  ProjectList projectFiles = d->m_projectFiles;
  ProjectList::Iterator it(projectFiles);
  for ( ; it.current(); ++it)
  {
    url = *(it.current());
    if (urlToRemove == url || (isFolder && urlToRemove.isParentOf(url)) )
    {
      d->m_projectFiles.removeFromListAndXML(url);
      d->m_modified = true;
      emit eventHappened("after_project_remove", url.url(), QString::null);
      if (!isFolder)
        break;
    }
    progressBar->advance(1);
  }

  progressBar->setTotalSteps(1);
  progressBar->setValue(0);
  progressBar->setTextEnabled(false);

  emit statusMsg(QString::null);

  if (d->m_modified)
    setModified();  // there happens more than setting the flag !
  emit reloadTree( &(d->m_projectFiles), false, QStringList() );
  emit newStatus();

  QString urlPath = QExtFileInfo::toRelative(urlToRemove, d->baseURL).path();
  QString nice = urlPath;
  nice = KStringHandler::lsqueeze(nice, 60);
  if (KMessageBox::warningContinueCancel(d->m_mainWindow, i18n("<qt>Do you want to remove <br><b>%1</b><br> from the server(s) as well?</qt>").arg(nice), i18n("Remove From Server"), KStdGuiItem::remove(), "RemoveFromServer") == KMessageBox::Continue )
  {
    QDomNode profilesNode = d->m_sessionDom.firstChild().firstChild().namedItem("uploadprofiles");
    QDomNodeList profileList = profilesNode.toElement().elementsByTagName("profile");
    QDomElement e;
    QString s;
    for (uint i = 0; i < profileList.count(); i++)
    {
      e = profileList.item(i).toElement();
      QString path = e.attribute("remote_path","");
      if (!path.startsWith("/"))
        path.prepend("/");
      KURL baseUrl;
      baseUrl.setProtocol(e.attribute("remote_protocol","ftp"));
      baseUrl.setPort(e.attribute("remote_port","").toInt());
      baseUrl.setHost(e.attribute("remote_host",""));
      baseUrl.setPath(path);
      baseUrl.setUser(e.attribute("user",""));
      QString passwd = password(e.attribute("remote_protocol") + "://" + e.attribute("user") + "@" + e.attribute("remote_host"));
      baseUrl.setPass(passwd);
      baseUrl.addPath(urlPath);
      KIO::NetAccess::del(baseUrl, d->m_mainWindow);
    }
  }
}
Example #16
0
bool QPEvents::handleEvent(const EventAction& ev)
{
  if (ev.type == EventAction::Internal)
  {
    if (ev.action == "email")
    {
       QString receiver = ev.arguments[0];
       TeamMember member;
       if (receiver == "teamleader")
         member = Project::ref()->teamLeader();
       else if (receiver.startsWith("subprojectleader-"))
       {
         QString s = receiver.remove("subprojectleader-");
         member = Project::ref()->subprojectLeader(s);
         SubProject subProject;
         QValueList<SubProject> *subprojects = Project::ref()->subprojects();
         for (uint i = 0 ; i < subprojects->count(); i++)
         {
           if ((*subprojects)[i].name == s)
           {
              subProject = (*subprojects)[i];
              break;
           }
         }
         if (!subProject.location.isEmpty() && !ev.arguments[2].startsWith(subProject.location))
         {
            kdDebug(24000) << ev.arguments[2] << " is not part of the " << subProject.name << "subproject \"" << subProject.location << "\". " << endl;
            return true;
         }
       }
       else if (receiver.startsWith("taskleader-"))
         member = Project::ref()->taskLeader(receiver.remove("taskleader-"));

       QString body;
       for (uint i = 2; i < ev.arguments.count(); i++)
          body += ev.arguments[i] + "\n";
       kapp->invokeMailer(member.name + "<" + member.email + ">", "", "", ev.arguments[1], body, "", QStringList(), "");

       return true;
    }
    if (ev.action == "log")
    {
      QString logFile = ev.arguments[0];
      KURL url = KURL::fromPathOrURL(logFile);
      if (url.isValid() && !url.isLocalFile())
      {
        KMessageBox::sorry(0L, i18n("Logging to remote files is not supported."));
        return false;
      }
      if (!logFile.startsWith("/"))
      {
        url = Project::ref()->projectBaseURL();
        url.addPath(logFile);
        if (!url.isLocalFile())
        {
          KMessageBox::sorry(0L, i18n("Logging to files inside a remote project is not supported."));
          return false;
        }
      }
      QFile file(url.path());
      bool result;
      if (ev.arguments[2] == "create_new")
        result = file.open(IO_WriteOnly);
      else
        result = file.open(IO_WriteOnly | IO_Append);
      if (result)
      {
        QTextStream stream(&file);
        stream.setEncoding(QTextStream::UnicodeUTF8);
        //Note: the log text should not be translated.
        QString s = QDateTime::currentDateTime().toString(Qt::ISODate) + ": ";
        s.append( "Event : " + m_eventName + " : ");
        s.append( "Action: " + ev.action + " : ");
        if (ev.arguments[1] == "full")
        {
          s.append( "Arguments: ");
          for (uint i = 1; i < ev.arguments.count(); i++)
            s.append(ev.arguments[i] + " | ");
        }
        s[s.length() - 1] = '\n';
        stream << s;
        file.close();
      }
      if (!result)
      {
        KMessageBox::sorry(0L, i18n("<qt>Logging failed. Check that you have write access to <i>%1</i>.").arg(url.path()));
        return false;
      }
    } else
      KMessageBox::sorry(0L, i18n("<qt>Unsupported internal event action : <b>%1</b>.</qt>").arg(ev.action));
  } else
  if (ev.type == EventAction::External)
  {
      //KMessageBox::sorry(0L, i18n("External event actions are not yet supported."));
      if (ev.action == "script" || ev.action =="action")
      {
          QString name = ev.arguments[0];
          KAction *action = quantaApp->actionCollection()->action(name);
          TagAction *tagAction = dynamic_cast<TagAction*>(action);
          if (tagAction)
          {
            bool blocking = (ev.arguments[1] == "yes");
            EventAction event = ev;
            event.arguments.remove(event.arguments.at(1));
            tagAction->addArguments(event.arguments);
            tagAction->execute(blocking);
          }
          else
          if (action)
          {
            action->activate();
          } else
            KMessageBox::sorry(0L, i18n("<qt>The <b>%1</b> script action was not found on your system.</qt>").arg(name), i18n("Action Execution Error"));
      }  else
      KMessageBox::sorry(0L, i18n("Unsupported external event action."));
  } else
      KMessageBox::sorry(0L, i18n("Unknown event type."));
  return false;
}
Example #17
0
bool MediaNotifier::execAutoopen(const KFileItem &medium, const QString &path, const QString &autoopenFile)
{
    // An Autoopen file MUST contain a single relative path that points
    // to a non-executable file contained on the medium. [...]
    QFile file(path + "/" + autoopenFile);
    file.open(IO_ReadOnly);
    QTextStream stream(&file);

    QString relative_path = stream.readLine().stripWhiteSpace();

    // The relative path MUST NOT contain path components that
    // refer to a parent directory ( ../ )
    if(relative_path.startsWith("/") || relative_path.contains("../"))
    {
        return false;
    }

    // The desktop environment MUST verify that the relative path points
    // to a file that is actually located on the medium [...]
    QString resolved_path = KStandardDirs::realFilePath(path + "/" + relative_path);

    if(!resolved_path.startsWith(path))
    {
        return false;
    }


    QFile document(resolved_path);

    // TODO: What about FAT all files are executable...
    // If the relative path points to an executable file then the desktop
    // environment MUST NOT execute the file.
    if(!document.exists() /*|| QFileInfo(document).isExecutable()*/)
    {
        return false;
    }

    KURL url = medium.url();
    url.addPath(relative_path);

    // The desktop environment MUST prompt the user for confirmation
    // before opening the file.
    QString mediumType = medium.mimeTypePtr()->name();
    QString filename = url.filename();
    QString text = i18n(
                       "An autoopen file has been found on your '%1'."
                       " Do you want to open '%2'?\n"
                       "Note that opening a file on a medium may compromise"
                       " your system's security")
                   .arg(mediumType)
                   .arg(filename);
    QString caption = i18n("Autoopen - %1").arg(medium.url().prettyURL());
    KGuiItem yes = KStdGuiItem::yes();
    KGuiItem no = KStdGuiItem::no();
    int options = KMessageBox::Notify | KMessageBox::Dangerous;

    int answer = KMessageBox::warningYesNo(0L, text, caption, yes, no, QString::null, options);

    // TODO: Take case of the "UNLESS" part?
    // When an Autoopen file has been detected and the user has confirmed
    // that the file indicated in the Autoopen file should be opened then
    // the file indicated in the Autoopen file MUST be opened in the
    // application normally preferred by the user for files of its kind
    // UNLESS the user instructed otherwise.
    if(answer == KMessageBox::Yes)
    {
        (void)new KRun(url);
    }

    return true;
}