Adding a File object programatically in Plone using PloneFormGen - action

I'm writing a PloneFormGen custom action adapter in order to add a File object to a folder from the File Field in the form. Here is the script:
target = context.filefolder
form = request.form
uid = str(DateTime().millis())
target.invokeFactory("File", id=uid, file=form['arquivo-do-cv_file'])
obj = target[uid]
"filefolder" is the name of a folder inside the parent folder for the PFG FormFolder. This script is configured to run with a Manager proxy role.
Problem is that the File objects created this way won't show the "Click here to download the file" link when I view them. The files can be downloaded though, if I suppress the "/view" part from the end of the URL. What am I missing when calling invokeFactory to create the File object?
UPDATE: What I meant is that I don't get the "filename - filetype, size in KBs (size in bytes)" link for the document, below the byline. When I create a File object using the normal Plone UI, it does show up.

I suspect nothing; I think that is the default behavior in Plone 4.
I just added a File and I don't see any "Click here to download the file".
And a quick search does not reveal the string "click here to download":
aclark#Alex-Clarks-MacBook-Pro:~/Developer/test-4.1/ > grep -ir "Click here to download" parts/omelette
parts/omelette/plone/app/jquerytools/browser/jquery.tools.plugins.js: (root.tagName == 'A' ? "<p>Click here to download latest version</p>" :
parts/omelette/plone/app/jquerytools/browser/jquery.tools.plugins.min.js:" or greater is required</h2><h3>"+(g[0]>0?"Your version is "+g:"You have no flash plugin installed")+"</h3>"+(a.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='"+k+"'>here</a></p>");if(a.tagName=="A")a.onclick=function(){location.href=k}}if(b.onFail){var d=b.onFail.call(this);if(typeof d=="string")a.innerHTML=d}}if(i)window[b.id]=document.getElementById(b.id);f(this,{getRoot:function(){return a},getOptions:function(){return b},getConf:function(){return c},

I don't have a Plone instance to test it, but try to call processForm() after invokeFactory. It will:
unmark creation flag;
rename object according to title;
reindex the object;
invoke the after_creation script and fire the ObjectInitialized event.
These actions are detailed on Object Construction Lifecycle. Maybe some of these actions are needed to create the KB information you're after (I'm hoping it's the index).

Related

Open a c++ application installed on computer with a custom url in browser [duplicate]

How do i set up a custom protocol handler in chrome? Something like:
myprotocol://testfile
I would need this to send a request to http://example.com?query=testfile, then send the httpresponse to my extension.
The following method registers an application to a URI Scheme. So, you can use mycustproto: in your HTML code to trigger a local application. It works on a Google Chrome Version 51.0.2704.79 m (64-bit).
I mainly used this method for printing document silently without the print dialog popping up. The result is pretty good and is a seamless solution to integrate the external application with the browser.
HTML code (simple):
Click Me
HTML code (alternative):
<input id="DealerName" />
<button id="PrintBtn"></button>
$('#PrintBtn').on('click', function(event){
event.preventDefault();
window.location.href = 'mycustproto:dealer ' + $('#DealerName').val();
});
URI Scheme will look like this:
You can create the URI Scheme manually in registry, or run the "mycustproto.reg" file (see below).
HKEY_CURRENT_USER\Software\Classes
mycustproto
(Default) = "URL:MyCustProto Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "myprogram.exe,1"
shell
open
command
(Default) = "C:\Program Files\MyProgram\myprogram.exe" "%1"
mycustproto.reg example:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\mycustproto]
"URL Protocol"="\"\""
#="\"URL:MyCustProto Protocol\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\DefaultIcon]
#="\"mycustproto.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open\command]
#="\"C:\\Program Files\\MyProgram\\myprogram.exe\" \"%1\""
C# console application - myprogram.exe:
using System;
using System.Collections.Generic;
using System.Text;
namespace myprogram
{
class Program
{
static string ProcessInput(string s)
{
// TODO Verify and validate the input
// string as appropriate for your application.
return s;
}
static void Main(string[] args)
{
Console.WriteLine("Raw command-line: \n\t" + Environment.CommandLine);
Console.WriteLine("\n\nArguments:\n");
foreach (string s in args)
{
Console.WriteLine("\t" + ProcessInput(s));
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
Try to run the program first to make sure the program has been placed in the correct path:
cmd> "C:\Program Files\MyProgram\myprogram.exe" "mycustproto:Hello World"
Click the link on your HTML page:
You will see a warning window popup for the first time.
To reset the external protocol handler setting in Chrome:
If you have ever accepted the custom protocol in Chrome and would like to reset the setting, do this (currently, there is no UI in Chrome to change the setting):
Edit "Local State" this file under this path:
C:\Users\Username\AppData\Local\Google\Chrome\User Data\
or Simply go to:
%USERPROFILE%\AppData\Local\Google\Chrome\User Data\
Then, search for this string: protocol_handler
You will see the custom protocol from there.
Note: Please close your Google Chrome before editing the file. Otherwise, the change you have made will be overwritten by Chrome.
Reference:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Chrome 13 now supports the navigator.registerProtocolHandler API. For example,
navigator.registerProtocolHandler(
'web+custom', 'http://example.com/rph?q=%s', 'My App');
Note that your protocol name has to start with web+, with a few exceptions for common ones (like mailto, etc). For more details, see: http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler
This question is old now, but there's been a recent update to Chrome (at least where packaged apps are concerned)...
http://developer.chrome.com/apps/manifest/url_handlers
and
https://github.com/GoogleChrome/chrome-extensions-samples/blob/e716678b67fd30a5876a552b9665e9f847d6d84b/apps/samples/url-handler/README.md
It allows you to register a handler for a URL (as long as you own it). Sadly no myprotocol:// but at least you can do http://myprotocol.mysite.com and can create a webpage there that points people to the app in the app store.
This is how I did it. Your app would need to install a few reg keys on installation, then in any browser you can just link to foo:\anythingHere.txt and it will open your app and pass it that value.
This is not my code, just something I found on the web when searching the same question. Just change all "foo" in the text below to the protocol name you want and change the path to your exe as well.
(put this in to a text file as save as foo.reg on your desktop, then double click it to install the keys)
-----Below this line goes into the .reg file (NOT including this line)------
REGEDIT4
[HKEY_CLASSES_ROOT\foo]
#="URL:foo Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\foo\shell]
[HKEY_CLASSES_ROOT\foo\shell\open]
[HKEY_CLASSES_ROOT\foo\shell\open\command]
#="\"C:\\Program Files (x86)\\Notepad++\\notepad++.exe\" \"%1\""
Not sure whether this is the right place for my answer, but as I found very few helpful threads and this was one of them, I am posting my solution here.
Problem: I wanted Linux Mint 19.2 Cinnamon to open Evolution when clicking on mailto links in Chromium. Gmail was registered as default handler in chrome://settings/handlers and I could not choose any other handler.
Solution:
Use the xdg-settings in the console
xdg-settings set default-url-scheme-handler mailto org.gnome.Evolution.desktop
Solution was found here https://alt.os.linux.ubuntu.narkive.com/U3Gy7inF/kubuntu-mailto-links-in-chrome-doesn-t-open-evolution and adapted for my case.
I've found the solution by Jun Hsieh and MuffinMan generally works when it comes to clicking links on pages in Chrome or pasting into the URL bar, but it doesn't seem to work in a specific case of passing the string on the command line.
For example, both of the following commands open a blank Chrome window which then does nothing.
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "foo://C:/test.txt"
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --new-window "foo://C:/test.txt"
For comparison, feeding Chrome an http or https URL with either of these commands causes the web page to be opened.
This became apparent because one of our customers reported that clicking links for our product from a PDF being displayed within Adobe Reader fails to invoke our product when Chrome is the default browser. (It works fine with MSIE and Firefox as default, but not when either Chrome or Edge are default.)
I'm guessing that instead of just telling Windows to invoke the URL and letting Windows figure things out, the Adobe product is finding the default browser, which is Chrome in this case, and then passing the URL on the command line.
I'd be interested if anyone knows of Chrome security or other settings which might be relevant here so that Chrome will fully handle a protocol handler, even if it's provided via the command line. I've been looking but so far haven't found anything.
I've been testing this against Chrome 88.0.4324.182.
open
C:\Users\<Username>\AppData\Local\Google\Chrome\User Data\Default
open Preferences then search for excluded_schemes you will find it in 'protocol_handler' delete this excluded scheme(s) to reset chrome to open url with default application

sg-cookie-optin extension throws No class named SGalinski\SgCookieOptin\Hook\LicenceCheckHook

Downloaded this https://packagist.org/packages/sgalinski/sg-cookie-optin
Copied the file to the server, activated the extension in ext manager.
Suddenly front & backend not working anymore.
Deleted the extension manually from PackageStates.php according to
https://docs.typo3.org/m/typo3/guide-installation/master/en-us/ExtensionInstallation/Index.html
Frontend now working, backend still throws the error
No class named SGalinski\SgCookieOptin\Hook\LicenceCheckHook
in /home/sc/wwn/typo3_src-10.4.10/typo3/sysext/core/Classes/Utility/GeneralUtility.php line 3340
throw new \InvalidArgumentException($errorMsg, 1294585865);
}
} else {
$errorMsg = 'No class named ' . $parts[0];
throw new \InvalidArgumentException($errorMsg, 1294585866);
}
} elseif (function_exists($funcName) && is_callable($funcName)) {
// It's a function
$content = call_user_func_array($funcName, [&$params, &$ref]);
I did set up the key and the output folder in the config file
what I didn't do since backend not working anymore :
3. Add the static TypoScript named "Cookie Optin" to your instance with the "Template" backend module.
Open up the "Template" module in the backend of TYPO3.
Go to your root site page within the page tree.
Choose "Info/Modify" at the select on the top.
Click on the button "Edit the whole template record".
Select the tab "Includes".
Choose the template "Cookie Optin (sg_cookie_optin)" on the multi select box with the name "Include static (from extensions)"
Save
4. Go into the "Cookie Opt In" backend module, configure it and save it once.
Any idea how i can fix that? Pretty stuck atm.
The install tool of your installation should still work. Try to open yourdomain.tld/typo3/install.php.
To enable the Install Tool, the file ENABLE_INSTALL_TOOL must be created in the directory typo3conf/. Make sure that the file has no file extension like .txt.
Then log in to the install tool and go to Maintenance => Flush TYPO3 and PHP Cache and flush all caches.
Then the backend should work.
If the install tool is not accessible, try to find a folder var/Cache. Most probably it will be located in typo3temp. Delete all files and subfolders from the Cache folder.

How to reference a File In Use dialog from a Word.Application object

How can one obtain a reference to a dialog that results from the following steps? I ran Microsoft Word 2013 programmatically.
Intentionally try to open a locked .docx file by passing the entire file path to the Open method of the Documents member of the Word.Application object.
Because the file is locked, a dialog entitled File In Use appears and contains the text: filename.extension is locked for editing by 'username'. Do you want to:
Open a Read Only copy
Create a local copy and merge your changes later
Receive notification when the original copy is available
followed by the buttons OK and Cancel.
I'm trying to obtain a reference to this recently-created (but not by my code) object primarily to confirm that it was created and secondarily to perhaps manipulate it from a program rather than user input. However, I can't reach it from either the Word.Application or Documents objects.
The following is the Python code (v2.7.11 on win32) I used.
import win32com.client
wordapp = win32com.client.Dispatch("Word.Application")
wordapp.Documents.Open("\\\\10.1.3.70\\subroot\\test.docx")
<COMObject Open>
wordapp.Documents.Open("\\\\10.1.3.70\\subroot2\\test.docx")
subroot and subroot2 are shares that access the same dir.

R Markdown with Shiny Server change host parameter

I am running RStudio on a server and I created a RMarkdown (.Rmd) file. It works fine if I create it as a static HTML but it does not work if I want it to be interactive (by adding runtime:shiny).
The issue is that when I add runtime:shiny and press the Run Document button the application will try to open at 127.0.0.1:xxxx (here xxxx is a random port). In order to make it work I would have to be able to change the host parameter to '0.0.0.0'. This is an option in the runApp function from the shiny package but I don't know how to add this option in RMarkdown.
Can anyone help me with this?
Thank you.
The ::run command from rmarkdown invokes shiny::runApp internally. You can set the option shiny.host before running the document:
options(shiny.host="0.0.0.0")
rmarkdown::run("myfile.Rmd")
You an also pass arbitrary paramters to runApp, so this should work too:
rmarkdown::run("myfile.Rmd", shiny_args=list(host="0.0.0.0"))
Neither of these will work with the Run Document button; that button starts a new R session in which to render the document. To change the shiny.host option in that session, you'll need to add the option to your .Rprofile.
Set the default values you want to initialize in (~/.Rprofile) under user directory
Sys.setenv(TZ = "UTC") # for Timezone
options(shiny.port = 9999)

Sitecore file download works only for admin user

I have a Sitecore 6.4 setup where an editor can click a button to generate a Word doc. I was adding the file to the media library and that was working fine. The editor would click the button in the content editor, the file was generated, media item was generated, then the content editor would show the new item in the media library and the editor could click the "download" button on the ribbon or the item to download it. However, my media library was getting unnecessarily filled up so I am trying to bypass the media library.
Instead of making the file in an arbitrary location as before, I am putting it in the temp directory like this:
wordOutputPath = Sitecore.IO.FileUtil.GetWorkFilename(Sitecore.Configuration.Settings.TempFolderPath, printItem.Name, ".docx");
File.Copy(wordTemplatePath, wordOutputPath);
WordprocessingDocument doc = WordprocessingDocument.Open(wordOutputPath, true);
After I "fill in" the file with content, I do this:
Sitecore.Context.ClientPage.ClientResponse.Download(wordFilePath);
Now if I am logged in as a Sitecore admin I get the browser's download dialog and can download the file. However, if I am logged in as a non-admin user, I get a little clicking and whirring, so to speak, and the file is generated, but the save file dialog never comes up in the browser. I can go in through the file system and see & open the Word doc, and it looks fine.
I found something in the Sitecore release notes for 6.6:
Released Sitecore CMS and DMS 6.6.0 rev. 130111 (6.6.0 Update-3)
[...]
Miscellaneous
Only Administrators were allowed to download files. (316774, 348557)
This was a problem in several areas of the system, for example the Package Generator and the Export Language Wizard in the CMS. It also affected the Export Users Wizard in the ECM module.
So I tried using SecurityDisabler (no longer have the code handy) and UserSwitcher like this:
using (new Sitecore.Security.Accounts.UserSwitcher(Sitecore.Security.Accounts.User.FromName("sitecore\admin", false)))
{
Sitecore.Context.ClientPage.ClientResponse.Download(wordFilePath);
}
The IUSR and IIS_IUSRS accounts both have read, list & read/execute permissions on the temp folder and the individual files show read & read/execute permissions for those two accounts as well.
What can I do to allow non-admin users to download these files? Does the bug that was fixed in 6.6 have anything to do with it?
Thank you.
Calling Sitecore.Context.ClientPage.ClientResponse.Download() method will result in a Download command sent back to the Sitecore Client in the Web browser, which in turn will make a call back to the server to execute it. This will be why using a security switcher (or a security disabler for that matter) before calling the Sitecore.Context.ClientPage.ClientResponse.Download() method has no effect, as the admin only restriction is being applied to the download else where.
If you search through sitecore\shell directory in your webroot, you will find that there is a file called download.aspx. This should be the actual page the download request is sent to. This web form page inherits the Sitecore.Shell.DownloadPage class, so if you take a look at that class's implementation, you will find that the OnLoad method is implemented as such:
protected override void OnLoad(EventArgs e)
{
Assert.ArgumentNotNull(e, "e");
base.OnLoad(e);
string fileHandle = StringUtil.GetString(new string[] { base.Request.QueryString["file"] });
bool flag = false;
string filename = FileHandle.GetFilename(fileHandle);
if (!string.IsNullOrEmpty(filename))
{
fileHandle = filename;
flag = true;
}
if (!string.IsNullOrEmpty(fileHandle))
{
if (MediaManager.IsMediaUrl(fileHandle))
{
this.DownloadMediaFile(fileHandle);
}
else if (fileHandle.IndexOf("id=", StringComparison.OrdinalIgnoreCase) >= 0)
{
this.DownloadMediaById(fileHandle);
}
else if (flag || Context.IsAdministrator)
{
this.DownloadFile(fileHandle);
}
}
}
As you can see, the last if block has an IsAdministrator check which would be where your non-admin users are getting blocked.
Although I haven't 100% verified that this is where the problem lies, the download restriction issue can be resolved, by creating a new class that inherits Sitecore.Shell.DownloadPage and overrides the OnLoad implementation with some extra security checks as required. I recommend that you don't remove the IsAdministrator check altogether as it is there for a good reason. Update the Inherits attribute in the download.aspx to make it use it instead.