Commit 63f5d165 authored by Jérome Perrin's avatar Jérome Perrin

Workarounds for CMFCore 2.7.0 URLTool REQUEST acquisition issues

After updating Products.CMFCore we had issues on sites where URLTool was registered as ISiteRoot.

In the case of ERP5, we don't really need portal_url.getPortalObject(), this changes to use ERP5Site.getPortalObject(), while at the same time doing something so that portal_url.getPortalObject() also works.

See https://github.com/zopefoundation/Products.CMFCore/pull/126 for more details

See merge request !1758
parents c2eb2973 58f528bb
......@@ -2,7 +2,7 @@
"""
from Products.ZSQLCatalog.SQLCatalog import SimpleQuery
from Products.ERP5Form.Report import ReportSection
portal = context.portal_url.getPortalObject()
portal = context.getPortalObject()
request = portal.REQUEST
cat_tool = portal.portal_categories
......
"""Client & vendors accounts.
"""
portal = context.portal_url.getPortalObject()
portal = context.getPortalObject()
from Products.ERP5Form.Report import ReportSection
......
......@@ -3,7 +3,7 @@
from Products.ERP5Form.Report import ReportSection
request = context.REQUEST
portal = context.portal_url.getPortalObject()
portal = context.getPortalObject()
at_date = request['at_date']
from_date = request.get('from_date', None)
......
......@@ -4,7 +4,7 @@
from Products.ERP5Form.Report import ReportSection
request = context.REQUEST
portal = context.portal_url.getPortalObject()
portal = context.getPortalObject()
at_date = request['at_date']
section_category = request['transaction_section_category']
......
<?xml version="1.0" encoding="iso-8859-1"?>
<template bottommargin='2cm' showboundary='0' topmargin='2cm'
rightmargin='2cm' tal:define='portal python:here.portal_url.getPortalObject()'
rightmargin='2cm' tal:define='portal python:here.getPortalObject()'
filename='journal.pdf' pagesize='A4' allowsplitting='1' landscape='0' leftmargin='2cm'>
<pagetemplate startframe='content' id='FirstPage'>
......
......@@ -2,7 +2,7 @@
# XXX This script could be deleted after the full transition to PAS (don't forget to update assignment workflow too)
# user_folder: NuxUserGroups or PluggableAuthService at the root of the ERP5Site.
user_folder = context.portal_url.getPortalObject()['acl_users']
user_folder = context.getPortalObject()['acl_users']
# This script can be bypassed in the context of PAS use because user groups are
# automaticcaly managed and set by ERP5Security/ERP5GroupManage.py
......
......@@ -78,5 +78,5 @@ class SkinConfiguratorItemMixin(ConfiguratorItemMixin):
.manage_addPythonScript(id = script_id)
script = container._getOb(script_id)
script.ZPythonScript_edit(script_params, script_content)
container.portal_url.getPortalObject().changeSkin(None)
container.getPortalObject().changeSkin(None)
return script
<tal:block tal:define="dummy python:request.RESPONSE.setHeader('Content-Type', 'text/html;; charset=utf-8');
global portal here/portal_url/getPortalObject;
global portal here/getPortalObject;
global portal_path portal/portal_url/getPortalPath;
portal_preferences python: here.getPortalObject().portal_preferences;
portal_preferences python: portal.portal_preferences;
global preferred_html_style_developper_mode portal_preferences/getPreferredHtmlStyleDevelopperMode;
global preferred_html_style_translator_mode portal_preferences/getPreferredHtmlStyleTranslatorMode;
global preferred_html_style_contextual_help portal_preferences/getPreferredHtmlStyleContextualHelp;
......
......@@ -29,7 +29,7 @@ Note:
</thead>
<tbody>
<tal:block metal:use-macro="here/Zuite_CommonTemplate/macros/init" />
<tal:block tal:define="portal here/portal_url/getPortalObject;
<tal:block tal:define="portal here/getPortalObject;
caller python: getattr(context, 'Zuite_setSkipSave', None);
no_file_update python: caller() if caller is not None else True;">
<tr>
......
......@@ -29,7 +29,7 @@ Note:
</thead>
<tbody>
<tal:block metal:use-macro="here/Zuite_CommonTemplate/macros/init" />
<tal:block tal:define="portal here/portal_url/getPortalObject;
<tal:block tal:define="portal here/getPortalObject;
caller python: getattr(context, 'Zuite_setSkipSave', None);
no_file_update python: caller() if caller is not None else True;">
<tr>
......
......@@ -29,7 +29,7 @@ Note:
</thead>
<tbody>
<tal:block metal:use-macro="here/Zuite_CommonTemplate/macros/init" />
<tal:block tal:define="portal here/portal_url/getPortalObject;
<tal:block tal:define="portal here/getPortalObject;
caller python: getattr(context, 'Zuite_setSkipSave', None);
no_file_update python: caller() if caller is not None else True;">
<tr>
......
......@@ -29,7 +29,7 @@ Note:
</thead>
<tbody>
<tal:block metal:use-macro="here/Zuite_CommonTemplate/macros/init" />
<tal:block tal:define="portal here/portal_url/getPortalObject;
<tal:block tal:define="portal here/getPortalObject;
caller python: getattr(context, 'Zuite_setSkipSave', None);
no_file_update python: caller() if caller is not None else True;">
<tr>
......
......@@ -29,7 +29,7 @@ Note:
</thead>
<tbody>
<tal:block metal:use-macro="here/Zuite_CommonTemplate/macros/init" />
<tal:block tal:define="portal here/portal_url/getPortalObject;
<tal:block tal:define="portal here/getPortalObject;
caller python: getattr(context, 'Zuite_setSkipSave', None);
no_file_update python: caller() if caller is not None else True;">
<tr>
......
......@@ -25,7 +25,7 @@ Note:
</thead>
<tbody>
<tal:block metal:use-macro="here/Zuite_CommonTemplate/macros/init" />
<tal:block tal:define="portal here/portal_url/getPortalObject;
<tal:block tal:define="portal here/getPortalObject;
caller python: getattr(context, 'Zuite_setSkipSave', None);
no_file_update python: caller() if caller is not None else True;">
<tr>
......
......@@ -2,7 +2,7 @@
result = ''
request = context.REQUEST
translate = context.portal_url.getPortalObject().Localizer.erp5_ui.gettext
translate = context.getPortalObject().Localizer.erp5_ui.gettext
listboxline_list = context.get_value('default', render_format='list', REQUEST=request)
......
<?xml version="1.0" encoding="iso-8859-1"?>
<template bottommargin='0.665cm' showboundary='0' topmargin='0.635cm' rightmargin='0.665cm' tal:define='portal python:here.portal_url.getPortalObject()' filename='accounting_details.pdf' pagesize='A4' allowsplitting='1' landscape='0' leftmargin='0.635cm'>
<template bottommargin='0.665cm' showboundary='0' topmargin='0.635cm' rightmargin='0.665cm' tal:define='portal python:here.getPortalObject()' filename='accounting_details.pdf' pagesize='A4' allowsplitting='1' landscape='0' leftmargin='0.635cm'>
<pagetemplate startframe='content' id='FirstPage'>
<static>
<rectangle z='' height='1.452cm' width='19.701cm' stroke='(0.0,0.0,0.0)' y='27.613cm' x='0.635cm' linewidth='1' fill='(0.4,0.4,0.4)'/>
......
......@@ -487,7 +487,7 @@ fieldset {
/* listbox */
.ListSummary {
background: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/tab_left.png') top left no-repeat;
background: url('<dtml-var expr="getPortalObject().absolute_url()">/images/tab_left.png') top left no-repeat;
color: #000;
background-color: <dtml-var document_background_color>;
padding-left: 10px;
......@@ -585,28 +585,28 @@ fieldset {
}
#favourites button .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/favourite.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/favourite.png');
}
#modules button .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/appearance.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/appearance.png');
}
#language button .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/language.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/language.png');
}
#search button .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/search.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/search.png');
}
#actions button .image{
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/exec16.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/exec16.png');
position: relative;
background-repeat: no-repeat;
}
#jump button .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/jump.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/jump.png');
position: relative;
background-repeat: no-repeat;
}
......@@ -630,76 +630,76 @@ fieldset {
}
#context_bar .separator {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/sepacla.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/sepacla.png');
height: 16px;
}
#context_bar .tool_buttons .jump_first .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/2leftarrowb.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/2leftarrowb.png');
}
#context_bar .tool_buttons .jump_previous .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/1leftarrowb.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/1leftarrowb.png');
}
#context_bar .tool_buttons .jump_next .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/1rightarrowb.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/1rightarrowb.png');
}
#context_bar .tool_buttons .jump_last .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/2rightarrowb.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/2rightarrowb.png');
}
#context_bar .tool_buttons .list_mode .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/text_block.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/text_block.png');
}
#context_bar .tool_buttons .new .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/filenew.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/filenew.png');
}
#context_bar .tool_buttons .clone .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/fileclone.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/fileclone.png');
}
#context_bar .tool_buttons .cut .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/editcut.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/editcut.png');
}
#context_bar .tool_buttons .copy .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/editcopy.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/editcopy.png');
}
#context_bar .tool_buttons .paste .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/editpaste.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/editpaste.png');
}
#context_bar .tool_buttons .delete .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/editdelete.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/editdelete.png');
}
#context_bar .tool_buttons .find .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/find.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/find.png');
}
#context_bar .tool_buttons .show_all .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/showall.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/showall.png');
}
#context_bar .tool_buttons .filter .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/filter.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/filter.png');
}
#context_bar .tool_buttons .filter_on .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/filter_on.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/filter_on.png');
}
#context_bar .tool_buttons .sort .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/sort.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/sort.png');
}
#context_bar .tool_buttons .configure .image {
background-image: url('<dtml-var expr="portal_url.getPortalObject().absolute_url()">/images/configure.png');
background-image: url('<dtml-var expr="getPortalObject().absolute_url()">/images/configure.png');
}
#navigation_buttons {
......
......@@ -23,7 +23,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-->
</tal:block>
<tal:block tal:define="form_action string:logged_in;
js_list python: ['%s/login_form.js' % (here.portal_url.getPortalObject().absolute_url(), )]">
js_list python: ['%s/login_form.js' % (here.getPortalObject().absolute_url(), )]">
<tal:block metal:use-macro="here/main_template/macros/master">
<tal:block metal:fill-slot="main">
<div class="content login">
......
......@@ -18,7 +18,7 @@
</tal:block>
</tal:block>
</tal:block>
<tal:block tal:define="portal_object here/portal_url/getPortalObject">
<tal:block tal:define="portal_object here/getPortalObject">
<tal:block tal:condition="not: sheet_per_report_section">
<table:table tal:attributes="table:name python:unicode(form.getProperty('title'), 'utf8')" i18n:attributes="table:name">
<!-- at least one table-column element is required for ODF to validate -->
......@@ -84,7 +84,7 @@
</tal:block>
</tal:block>
</tal:block>
<tal:block tal:define="portal_object here/portal_url/getPortalObject;
<tal:block tal:define="portal_object here/getPortalObject;
dummy python:report_item.popReport(portal_object, render_prefix=render_prefix)"/>
</tal:block>
</tal:block>
......
......@@ -151,7 +151,7 @@
</tal:block>
<tal:block tal:condition="not: rendered_report_item_list">
<tal:block tal:define="portal_object here/portal_url/getPortalObject">
<tal:block tal:define="portal_object here/getPortalObject">
<tal:block tal:repeat="report_item report_item_list">
<tal:block tal:define="here python:report_item.getObject(portal_object);
render_prefix python: 'x%s' % (repeat['report_item'].index, );
......
......@@ -48,7 +48,7 @@
<title>List Print</title>\n
<author>Nexedi</author>\n
<subject>Print Example</subject>\n
<content tal:define="localizer python: here.portal_url.getPortalObject().Localizer; ">\n
<content tal:define="localizer python: here.getPortalObject().Localizer; ">\n
\n
<table splitbyrow="1" repeatrows="0" repeatcols="0" style="AttributesTable" >\n
<tr>\n
......
......@@ -19,7 +19,7 @@
meta_reference python: here.getProperty('reference') or '';
meta_description python: here.getProperty('description') or '';
meta_title python: here.getProperty('title') or here.getPortalObject().title_or_id();
global portal here/portal_url/getPortalObject;
global portal here/getPortalObject;
global portal_path portal_path | portal/absolute_url;
request python: context.REQUEST;
dynamic_path_url python: request['PATH_INFO'];
......
......@@ -185,7 +185,7 @@ class ReferCheckerBeforeTraverseHook:
if user is not None and 'Manager' in user.getRoles():
return
portal_url = container.portal_url.getPortalObject().absolute_url()
portal_url = container.getPortalObject().absolute_url()
if http_referer != '':
# if HTTP_REFERER is set, user can acces the object if referer is ok
if http_referer.startswith(portal_url):
......@@ -486,6 +486,16 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
setSite(old_site)
else:
self._registerMissingTools()
# Some old ERP5 Sites have ISiteRoot registered, which
# makes URLTool.getPortalObject() returns the portal in
# an incorrect acquisition context. We unregister this
# interface to have the fallback behavior from
# https://github.com/zopefoundation/Products.CMFCore/blob/c2b800e6/src/Products/CMFCore/URLTool.py#L75-L77
from Products.CMFCore.interfaces import ISiteRoot
if _components.unregisterUtility(provided=ISiteRoot):
LOG('ERP5Site', 0, 'Unregistered ISiteRoot Utility')
return _components
security.declareProtected(Permissions.View, 'view')
......
......@@ -4,15 +4,15 @@
<metal:block define-macro="master">
<tal:block tal:define="title here/Title;
enctype string:multipart/form-data;
portal context/portal_url/getPortalObject;
portal context/getPortalObject;
global css_list python:['%s/tabber_style.css' % (portal.absolute_url(),)];
global js_list python:['%s/erp5_tabber.js' % (portal.absolute_url(),)]">
<tal:block metal:use-macro="here/main_template/macros/master">
<tal:block metal:fill-slot="main">
<tal:block tal:condition="here/portal_membership/isAnonymousUser">
<tal:block tal:condition="portal/portal_membership/isAnonymousUser">
<tal:block tal:define="dummy python:request.RESPONSE.redirect('%s/login_form' % portal.absolute_url())" />
</tal:block>
<tal:block tal:condition="python:not here.portal_membership.isAnonymousUser()">
<tal:block tal:condition="python:not portal.portal_membership.isAnonymousUser()">
<div class="index_html" style="margin:20px 40px 0 40px; padding:0; text-align:left;">
<div class="document">
<div class="actions">
......@@ -24,7 +24,7 @@
</div>
<p class="clear" />
</div>
<tal:block tal:condition="python: here.getPortalObject().restrictedTraverse('portal_gadgets', None) is not None">
<tal:block tal:condition="python: portal.restrictedTraverse('portal_gadgets', None) is not None">
<tal:block tal:condition="exists:here/ERP5Site_viewHomeAreaRenderer"
tal:replace="structure python: here.ERP5Site_viewHomeAreaRenderer(create_default_pad=True,
make_security_check=True)" />
......
# pylint: disable-all
from Products.PythonScripts.standard import html_quote
from Products.CMFCore.utils import getToolByName
from Products.FCKeditor.utils import fckCreateValidZopeId
# Author : Youenn Broussard - alias youyou (!) on macadames.com ;-)
# modified by Jean-mat 05/03/06 for new xml attributes compliance and charset questions
# 1. Config
# Path to user files relative to the document root.
ConfigUserFilesPath=""
# SECURITY TIP: Uncomment the following line to set a fixed path
# ConfigUserFilesPath = "/UserFiles/"
# SECURITY TIP: Uncomment the 3 following code lines to force the Plone Member Home Folder as fixed path
# You can do it as well with wysiwyg_support templates customization
# it's just more secure
# portal=context.portal_url.getPortalObject()
# portal_url=portal.absolute_url()
# ConfigUserFilesPath = portal.portal_membership.getHomeUrl().replace(portal_url, '') + '/'
# special review_states
# (unpublished states for contents which need to be hidden to local_roles
# not in rolesSeeUnpublishedContent even with View permission )
unpublishedStates=['visible','pending','rejected', 'waitreview']
# special local_roles who can see unpublished contents according to permissions
# by default set to None
rolesSeeUnpublishedContent = None
# you can force the value here
# rolesSeeUnpublishedContent = ['Manager','Reviewer','Owner', 'Contributor']
# if rolesSeeUnpublishedContent is None we try to take it from portal_properties > navtree_properties
if not rolesSeeUnpublishedContent:
try:
props=getToolByName(context,'portal_properties')
if hasattr(props,'navtree_properties'):
props=props.navtree_properties
rolesSeeUnpublishedContent=getattr(props,'rolesSeeUnpublishedContent', ['Manager','Reviewer','Owner'])
except:
rolesSeeUnpublishedContent = ['Manager','Reviewer','Owner']
# Allowed and denied extensions dictionaries
ConfigAllowedExtensions = {"File":None,
"Image":("jpg","gif","jpeg","png"),
"Flash":("swf","fla"),
"Media":("swf",
"fla",
"jpg",
"gif",
"jpeg",
"png",
"avi",
"mpg",
"mpeg",
"mp1",
"mp2",
"mp3",
"mp4",
"wma",
"wmv",
"wav",
"mid",
"midi",
"rmi",
"rm",
"ram",
"rmvb",
"mov",
"qt")}
ConfigDeniedExtensions = {"File":("py",
"cpy",
"pt",
"cpt",
"dtml",
"php",
"asp",
"aspx",
"ascx",
"jsp",
"cfm",
"cfc",
"pl",
"bat",
"exe",
"com",
"dll",
"vbs",
"js",
"reg"),
"Image":None,
"Flash":None,
"Media":None}
# set link by UID for AT content Types
# change value to 0 to disable it
linkbyuid=1
CPS_FOLDER_TYPE=['Workspace','ImageGallery','CPS Proxy Folder','CPS Proxy Folderish Document']
# find Plone Site charset (todo : CPS compliance (how ?))
try:
prop = getToolByName(context, "portal_properties")
charsetSite = prop.site_properties.getProperty("default_charset", "utf-8")
except:
charsetSite ="iso-8859-1"
# 2. utils
def RemoveFromStart(sourceString,charToRemove ):
return sourceString.lstrip(charToRemove)
def utf8Encode(chaine) :
errors="strict"
if charsetSite.lower() in ("utf-8", "utf8"):
return chaine
else:
return unicode(chaine, charsetSite, errors).encode("utf-8", errors)
def utf8Decode(chaine) :
# because browser upload form is in utf-8 we need it
errors="strict"
if charsetSite.lower() in ("utf-8", "utf8"):
return chaine
else:
try:
chaine = unicode(chaine, "utf-8", "strict").encode(charsetSite, "strict")
except:
chaine = chaine.encode(charsetSite, "strict")
return chaine
def ConvertToXmlAttribute( value ):
return utf8Encode(value).replace("\"", "&quot;").replace("&", "&amp;")
# 3. io
def GetUrlFromPath( folderPath ) :
return '%s%s' %(portal_path,folderPath.rstrip("/"))
def RemoveExtension( fileName ):
sprout=fileName.split(".")
return '.'.join(sprout[:len(sprout)-1])
def IsAllowedExt( extension, resourceType ) :
sAllowed = ConfigAllowedExtensions[resourceType]
sDenied = ConfigDeniedExtensions[resourceType]
if (sAllowed is None or extension in sAllowed) and (sDenied is None or extension not in sDenied) :
return 1
else :
return 0
def FindExtension (fileName):
sprout=fileName.split(RemoveExtension(fileName))
return ''.join(sprout).lstrip('.')
# 4. basexml
def CreateXmlHeader( command, resourceType, currentFolder ):
header = ['<?xml version="1.0" encoding="utf-8" ?>']
header.append('\r<Connector command="%s" resourceType=" %s ">'% (command,resourceType))
header.append('\r <CurrentFolder path="%s" url="%s/" />'% (ConvertToXmlAttribute(currentFolder),ConvertToXmlAttribute(GetUrlFromPath(currentFolder))))
return ''.join(header)
def CreateXmlFooter():
return '\r</Connector>'
def xmlString(results, resourceType, foldersOnly):
# traitement xml
xmlFiles=['\r <Files>']
xmlFolders=['\r <Folders>']
for result in results :
titre = result.title_or_id()
if linkbyuid and hasattr(result, 'UID'):
tagLinkbyuid="yes"
uid = result.UID()
else :
tagLinkbyuid="no"
uid=""
if result.meta_type in CPS_FOLDER_TYPE :
try:
xmlFolders.append('\r <Folder name="%s" title="%s" linkbyuid="%s" uid="%s" type="%s" metatype="%s" />'%(ConvertToXmlAttribute(result.id),ConvertToXmlAttribute(titre), tagLinkbyuid, uid, resourceType, ConvertToXmlAttribute(result.meta_type)))
except Exception as e:
pass
else :
tagPhoto= "no"
size=0
try:
size= result.getContent().get_size()
except Exception as e:
pass
try:
xmlFiles.append('\r <File name="%s/preview" size="%s" title="%s" photo="%s" linkbyuid="%s" uid="%s" type="%s" isPA3img="no" isattach="no" attachid="" />'%(ConvertToXmlAttribute(result.getId()),size,ConvertToXmlAttribute(titre), tagPhoto, tagLinkbyuid, uid, resourceType))
except Exception as e:
pass
xmlFiles.append('\r </Files>')
xmlFolders.append('\r </Folders>')
if foldersOnly:
stringXml=''.join(xmlFolders)
else :
stringXml=''.join(xmlFolders)+''.join(xmlFiles)
return stringXml
def CreateXmlErrorNode (errorNumber,errorDescription):
return '\r <Error number="' + errorNumber + '" originalNumber="' + errorNumber + '" originalDescription="' + ConvertToXmlAttribute( errorDescription ) + '" />'
# 5. commands
# Specific CPS , for special folderish (doc flexible ...) change these lines
def GetFoldersAndFiles( resourceType, currentFolder ):
results=[]
user=context.REQUEST['AUTHENTICATED_USER']
types=context.portal_types
all_portal_types = [ctype.content_meta_type for ctype in types.objectValues()]
accepted_values=['CPS Proxy Document',]
if resourceType=="Image" :
accepted_types=[ctype.id for ctype in types.objectValues() if ctype.id in ('Image', )]
elif resourceType=="Flash":
accepted_types=[ctype.id for ctype in types.objectValues() if ctype.id in ('Flash Animation', )]
#elif resourceType not in ('Image', 'Flash') :
# accepted_types=[ctype.id for ctype in types.objectValues()]
else :
accepted_types = [ctype.id for ctype in types.objectValues()]
if currentFolder != "/" :
try:
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
except Exception as e:
obj = context.portal_url.getPortalObject()
else :
obj = context.portal_url.getPortalObject()
for object in obj.objectValues( accepted_values + CPS_FOLDER_TYPE):
mtool = context.portal_membership
checkPerm = mtool.checkPermission
if not checkPerm('View', object):
pass
if object.portal_type in accepted_types or (object.meta_type in CPS_FOLDER_TYPE) :
results.append(object)
results = [ s for s in results if user.has_permission('View', s) ]
return xmlString(results,resourceType,0)
def GetFolders( resourceType, currentFolder ):
results=[]
user=context.REQUEST['AUTHENTICATED_USER']
types=context.portal_types
all_portal_types = [ctype.content_meta_type for ctype in types.objectValues()]
if currentFolder != "/" :
#try:
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
#except Exception,e:
# obj = context.portal_url.getPortalObject()
else :
#obj = context.portal_url.getPortalObject()
return xmlString([],resourceType,1)
#
#if obj.meta_type == 'CPSDefault Site':
# obj=obj.sections
mtool = context.portal_membership
checkPerm = mtool.checkPermission
for object in obj.objectValues(CPS_FOLDER_TYPE):
# filter out objects that cannot be viewed
if not user.has_permission('View', object):
continue
try:
if object.meta_type in CPS_FOLDER_TYPE and object.meta_type in all_portal_types :
#review_state=container.portal_workflow.getInfoFor(object, 'review_state', '')
start_pub=getattr(object,'effective_date',None)
end_pub=getattr(object,'expiration_date',None)
if not ((start_pub and start_pub > DateTime()) or (end_pub and DateTime() > end_pub)):
results.append(object)
elif user.has_role(rolesSeeUnpublishedContent,object) :
results.append(object)
except Exception as e:
pass
results = [ s for s in results if user.has_permission('View', s) ]
return xmlString(results,resourceType,1)
def CreateFolder(currentFolder, folderName ):
user=context.REQUEST['AUTHENTICATED_USER']
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
sErrorNumber=""
# error cases
if not user.has_permission('Add portal content', obj) and not user.has_permission('Modify portal content', obj):
sErrorNumber = "103"
sErrorDescription = "folder creation forbidden"
if not folderName:
sErrorNumber = "102"
sErrorDescription = "invalid folder name"
if not sErrorNumber :
try :
folderTitle=utf8Decode(folderName)
folderName = fckCreateValidZopeId(utf8Encode(folderName))
new_id = obj.invokeFactory(id=folderName, type_name='Folder', title=folderTitle)
sErrorNumber = "0"
sErrorDescription = "success"
except :
sErrorNumber = "103"
sErrorDescription = "folder creation forbidden"
return CreateXmlErrorNode(sErrorNumber,sErrorDescription)
# 6. upload
def UploadFile(resourceType, currentFolder, data, title) :
user=context.REQUEST['AUTHENTICATED_USER']
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
error=""
idObj=""
# define Portal Type to add
if resourceType == 'Flash':
typeToAdd='Flash Animation'
elif resourceType in ('File', 'Flash', 'Media'):
typeToAdd = 'File'
elif resourceType == 'Image' :
typeToAdd='Image'
if not user.has_permission('Add portal content', obj) and not user.has_permission('Modify portal content', obj):
error = "103"
if not data:
#pas de fichier
error= "202"
titre_data=''
filename=utf8Decode(getattr(data,'filename', ''))
titre_data=filename[max(string.rfind(filename, '/'),
string.rfind(filename, '\\'),
string.rfind(filename, ':'),
)+1:]
idObj=fckCreateValidZopeId(utf8Encode(titre_data))
if title :
titre_data=title
if not IsAllowedExt( FindExtension(idObj), resourceType ):
error= "202"
if not error :
error="0"
indice=0
exemple_titre=idObj
while exemple_titre in obj.objectIds():
indice=indice+1
exemple_titre=str(indice) + idObj
if indice!=0:
error= "201"
idObj = exemple_titre
try:
# this method need to be changed for browser refresh
# because it send 302 redirection : we need no http response
request=context.REQUEST
request.form.update({'widget__preview':data,'widget__preview_choice':'change','type_name':typeToAdd,'widget__Title':titre_data, 'cpsdocument_create_button':1,'widget__LanguageSelectorCreation':'fr'})
ti=context.portal_types[typeToAdd]
res = ti.renderCreateObjectDetailed(container=obj, request=request,
validate=1, layout_mode='create',
create_callback='createCPSDocument_cb',
created_callback='cpsdocument_created')
#context.createCPSDocument(context=obj,REQUEST=request)
obj.reindexObject()
except Exception as e :
error = "103"
d= '''
<script type="text/javascript">
window.parent.frames['frmUpload'].OnUploadCompleted(%s,%s) ;
</script>
'''% (error,idObj)
return d
#7. connector
request = context.REQUEST
RESPONSE = request.RESPONSE
dicoRequest = request.form
message_error=""
portal_url=context.portal_url.getPortalObject().absolute_url()
server_url = request.SERVER_URL
portal_path = portal_url.replace(server_url,'')
if ConfigUserFilesPath != "" :
sUserFilesPath = ConfigUserFilesPath
elif 'ServerPath' in dicoRequest:
sUserFilesPath = dicoRequest ['ServerPath']
else :
sUserFilesPath = "/"
if 'CurrentFolder' in dicoRequest:
sCurrentFolder = dicoRequest ['CurrentFolder']
if sUserFilesPath!='/' and sUserFilesPath.rstrip('/') not in sCurrentFolder:
sCurrentFolder = sUserFilesPath
else :
message_error="No CurrentFolder in request"
if 'Command' in dicoRequest:
sCommand = dicoRequest ['Command']
else :
message_error="No Command in request"
if 'Type' in dicoRequest:
sResourceType = dicoRequest ['Type']
else :
message_error="No Type in request"
if 'NewFolderName' in dicoRequest:
sFolderName = dicoRequest ['NewFolderName']
# interception File Upload
if sCommand=='FileUpload' and 'NewFile' in dicoRequest:
sData = dicoRequest ['NewFile']
sTitle = utf8Decode(dicoRequest ['Title'])
chaineHtmlUpload = UploadFile(sResourceType, sCurrentFolder, sData, sTitle)
RESPONSE.setHeader('Content-type', 'text/html; charset=%s' % charsetSite)
return chaineHtmlUpload
else :
# Creation response XML
if not message_error :
RESPONSE.setHeader('Cache-control', 'pre-check=0,post-check=0,must-revalidate,s-maxage=0,max-age=0,no-cache')
RESPONSE.setHeader('Content-type', 'text/xml; charset=utf-8')
xmlHeader = CreateXmlHeader (sCommand, sResourceType, sCurrentFolder)
if sCommand=="GetFolders":
xmlBody = GetFolders (sResourceType, sCurrentFolder)
elif sCommand=="GetFoldersAndFiles":
xmlBody = GetFoldersAndFiles (sResourceType, sCurrentFolder)
elif sCommand=="CreateFolder":
xmlBody = CreateFolder (sCurrentFolder,sFolderName)
xmlFooter = CreateXmlFooter()
return xmlHeader + xmlBody + xmlFooter
# creation response error request
else :
sErrorNumber="218"
sErrorDescription="Browser Request exception : " + message_error
xmlHeader = CreateXmlHeader (sCommand, sResourceType, sCurrentFolder)
xmlFooter = CreateXmlFooter()
return xmlHeader + CreateXmlErrorNode(sErrorNumber,sErrorDescription) + xmlFooter
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="_reconstructor" module="copy_reg"/>
</klass>
<tuple>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
<global name="object" module="__builtin__"/>
<none/>
</tuple>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>Command=\'\',Type=\'\',CurrentFolder=\'\',NewFolderName=\'\'</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>connectorCPS.py</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
......@@ -16,7 +16,7 @@ ConfigUserFilesPath=""
# SECURITY TIP: Uncomment the 3 following code lines to force the Plone Member Home Folder as fixed path
# You can do it as well with wysiwyg_support templates customization
# it's just more secure
# portal=context.portal_url.getPortalObject()
# portal=context.getPortalObject()
# portal_url=portal.absolute_url()
# ConfigUserFilesPath = portal.portal_membership.getHomeUrl().replace(portal_url, '') + '/'
......@@ -269,10 +269,10 @@ def GetFoldersAndFiles( resourceType, currentFolder ):
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
except Exception as e:
obj = context.portal_url.getPortalObject()
obj = context.getPortalObject()
else :
obj = context.portal_url.getPortalObject()
obj = context.getPortalObject()
for object in obj.objectValues():
......@@ -304,10 +304,10 @@ def GetFolders( resourceType, currentFolder ):
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
#except Exception,e:
# obj = context.portal_url.getPortalObject()
# obj = context.getPortalObject()
else :
#obj = context.portal_url.getPortalObject()
#obj = context.getPortalObject()
return xmlString([],resourceType,1)
......@@ -346,7 +346,7 @@ def CreateFolder(currentFolder, folderName ):
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
obj = context.getPortalObject()
sErrorNumber=""
# error cases
......@@ -382,7 +382,7 @@ def UploadFile(resourceType, currentFolder, data, title) :
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
obj = context.getPortalObject()
error=""
idObj=""
......@@ -457,7 +457,7 @@ RESPONSE = request.RESPONSE
dicoRequest = request.form
message_error=""
portal_url=context.portal_url.getPortalObject().absolute_url()
portal_url=context.getPortalObject().absolute_url()
server_url = request.SERVER_URL
portal_path = portal_url.replace(server_url,'')
......
# pylint: disable-all
from Products.PythonScripts.standard import html_quote
from Products.CMFCore.utils import getToolByName
from Products.FCKeditor.utils import fckCreateValidZopeId
# Author : jean-mat Grimaldi - jean-mat@macadames.com
# Thanks to Martin F. Krafft (alias madduck on sourceforge) for some corrections
# Thanks to kupu developpers for UID referencing
# This connector is plone specific
# Some functions need to be adapted for other Zope CMS compatibility
# 1. Config
# Path to user files relative to the document root.
# security tip
ConfigUserFilesPath=""
# dico fck parameters for browsing
fckParams=context.getFck_params()
# special review_states
# (unpublished states for contents which need to be hidden to local_roles
# not in fck prefs rolesSeeUnpublishedContent even with View permission )
unpublishedStates=fckParams['fck_unpublished_states']
# special local_roles who can see unpublished contents according to permissions
# by default set to fck unpublished view roles (fck prefs)
rolesSeeUnpublishedContent = fckParams['fck_unpublished_view_roles']
# PloneArticle based meta_types
pa_meta_types = fckParams['pa_meta_types']
# Allowed and denied extensions dictionaries
ConfigAllowedExtensions = {"File":None,
"Image":("jpg","gif","jpeg","png"),
"Flash":("swf","fla"),
"Media":("swf",
"fla",
"jpg",
"gif",
"jpeg",
"png",
"avi",
"mpg",
"mpeg",
"mp1",
"mp2",
"mp3",
"mp4",
"wma",
"wmv",
"wav",
"mid",
"midi",
"rmi",
"rm",
"ram",
"rmvb",
"mov",
"qt")}
ConfigDeniedExtensions = {"File":("py",
"cpy",
"pt",
"cpt",
"dtml",
"php",
"asp",
"aspx",
"ascx",
"jsp",
"cfm",
"cfc",
"pl",
"bat",
"exe",
"com",
"dll",
"vbs",
"js",
"reg"),
"Image":None,
"Flash":None,
"Media":None}
# set link by UID for AT content Types
linkbyuid=test(fckParams['allow_link_byuid'],1,0)
# check if upload allowed for Links Image and internal links
allow_file_upload=test(fckParams['allow_server_browsing'],test(fckParams['allow_file_upload'],1,0),0)
allow_image_upload=test(fckParams['allow_server_browsing'],test(fckParams['allow_image_upload'],1,0),0)
allow_flash_upload=test(fckParams['allow_server_browsing'],test(fckParams['allow_flash_upload'],1,0),0)
# check for portal_types when uploading internal links, images and files
file_portal_type = test(fckParams['file_portal_type'],fckParams['file_portal_type'],'File')
image_portal_type = test(fckParams['image_portal_type'],fckParams['image_portal_type'],'Image')
flash_portal_type = test(fckParams['flash_portal_type'],fckParams['flash_portal_type'],'File')
# find Plone Site charset
try:
prop = getToolByName(context, "portal_properties")
charsetSite = prop.site_properties.getProperty("default_charset", "utf-8")
except:
charsetSite ="utf-8"
# 2. utils
def utf8Encode(chaine) :
errors="strict"
if charsetSite.lower() in ("utf-8", "utf8"):
return chaine
else:
return unicode(chaine, charsetSite, errors).encode("utf-8", errors)
def utf8Decode(chaine) :
# because browser upload form is in utf-8 we need it
errors="strict"
if charsetSite.lower() in ("utf-8", "utf8"):
return chaine
else:
try:
chaine = unicode(chaine, "utf-8", "strict").encode(charsetSite, "strict")
except:
chaine = chaine.encode(charsetSite, "strict")
return chaine
def ConvertToXmlAttribute( value ):
return utf8Encode(value).replace("\"", "&quot;").replace("'","&rsquo;").replace("&", "&amp;")
# 3. io
def GetUrlFromPath( folderPath ) :
return '%s%s' %(portal_path,folderPath.rstrip("/"))
def RemoveExtension( fileName ):
sprout=fileName.split(".")
return '.'.join(sprout[:len(sprout)-1])
def IsAllowedExt( extension, resourceType ) :
sAllowed = ConfigAllowedExtensions[resourceType]
sDenied = ConfigDeniedExtensions[resourceType]
if (sAllowed is None or extension in sAllowed) and (sDenied is None or extension not in sDenied) :
return 1
else :
return 0
def FindExtension (fileName):
sprout=fileName.split(RemoveExtension(fileName))
return ''.join(sprout).lstrip('.')
# 4. basexml
def CreateXmlHeader( command, resourceType, currentFolder ):
header = ['<?xml version="1.0" encoding="utf-8" ?>']
header.append('\r<Connector command="%s" resourceType=" %s ">'% (command,resourceType))
header.append('\r <CurrentFolder path="%s" url="%s/" />'\
% (ConvertToXmlAttribute(currentFolder),
ConvertToXmlAttribute(GetUrlFromPath(currentFolder))))
return ''.join(header)
def CreateXmlFooter():
return '\r</Connector>'
def xmlString(results, resourceType, foldersOnly, isPA):
user=context.REQUEST['AUTHENTICATED_USER']
# traitement xml
xmlFiles=['\r <Files>']
xmlFolders=['\r <Folders>']
# traitement folderish standard non PloneArticle
if isPA ==0:
for result in results :
titre = result.title_or_id()
if linkbyuid and hasattr(result.aq_explicit, 'UID'):
tagLinkbyuid="yes"
uid = result.UID()
else :
tagLinkbyuid="no"
uid=""
if result.isPrincipiaFolderish or result.meta_type in pa_meta_types :
xmlFolders.append('''
<Folder name="%s"
title="%s"
linkbyuid="%s"
uid="%s"
type="%s"
metatype="%s" />'''%(ConvertToXmlAttribute(result.getId()),
ConvertToXmlAttribute(titre),
tagLinkbyuid, uid,
resourceType,
ConvertToXmlAttribute(result.meta_type)))
else :
if result.meta_type in ('CMF ZPhoto', 'CMF Photo'):
tagPhoto="yes"
else:
tagPhoto= "no"
isAttach = "no"
attachId=""
xmlFiles.append('''
<File name="%s"
size="%s"
title="%s"
photo="%s"
linkbyuid="%s"
uid="%s"
type="%s"
isPA3img="no"
isattach="%s"
attachid="%s" />'''%(ConvertToXmlAttribute(result.getId()),
str(context.getObjSize(result)),
ConvertToXmlAttribute(titre),
tagPhoto,
tagLinkbyuid,
uid,
resourceType,
isAttach,
attachId))
# PloneArticle specific treatment
elif user.has_permission('View', results) :
# find Plone Article version and brains for PA v3
try :
image_brains =results.getImageBrains()
attachment_brains=results.getAttachmentBrains()
versionPA=3
except:
versionPA=2
# Plone Article v3 treatment
if versionPA==3:
atool = context.portal_article
# PloneArticle 3.x images and attachements
# images
for image_brain in image_brains :
image = image_brain.getObject()
image_field = image.getField('image')
image_name = atool.getFieldFilename(image, image_field)
image_id = image.getId()
image_title = image.title_or_id()
image_size = context.plonearticle_format_size(image.get_size())
tagPhoto= "no"
isAttach = "no"
if linkbyuid and hasattr(image.aq_explicit, 'UID'):
tagLinkbyuid="yes"
uid = image.UID()
else:
tagLinkbyuid="no"
uid=""
xmlFiles.append('''
<File name="%s"
size="%s"
title="%s"
photo="%s"
linkbyuid="%s"
uid="%s"
type="%s"
isPA3img="yes"
isattach="%s"
attachid="%s" />'''%(ConvertToXmlAttribute(image_id),
image_size,
ConvertToXmlAttribute(image_title),
tagPhoto,
tagLinkbyuid,
uid,
resourceType,
isAttach,
ConvertToXmlAttribute(image_name)))
# files and other resource types
if resourceType!='Image':
for attach_brain in attachment_brains :
attach = attach_brain.getObject()
attach_field = attach.getField('file')
attach_name = atool.getFieldFilename(attach, attach_field)
attach_id = attach.getId()
attach_title = attach.title_or_id()
attach_size = context.plonearticle_format_size(attach.get_size())
tagPhoto= "no"
isAttach = "no"
if linkbyuid and hasattr(attach.aq_explicit, 'UID'):
tagLinkbyuid="yes"
uid = attach.UID()
else:
tagLinkbyuid="no"
uid=""
xmlFiles.append('''
<File name="%s"
size="%s"
title="%s"
photo="%s"
linkbyuid="%s"
uid="%s"
type="%s"
isPA3img="no"
isattach="%s"
attachid="%s" />'''%(ConvertToXmlAttribute(attach_id),
attach_size,
ConvertToXmlAttribute(attach_title),
tagPhoto,
tagLinkbyuid,
uid,
resourceType,
isAttach,
ConvertToXmlAttribute(attach_name)))
# PloneArticle v2.x
else:
tagLinkbyuid="no"
uid=""
# images
if len(results.listImages())>0:
images = results.listImages()
index=0
for image in images :
titre = image.title_or_id()
# get Id
imageId=results.getImageId(index)
index +=1
# get Size object
try:
imageSize=image.getSize()
except:
imageSize=context.getObjSize(image)
tagPhoto= "no"
isAttach = "no"
attachId = image.getId()
xmlFiles.append('''
<File name="%s"
size="%s"
title="%s"
photo="%s"
linkbyuid="%s"
uid="%s"
type="%s"
isPA3img="no"
isattach="%s"
attachid="%s" />'''%(ConvertToXmlAttribute(imageId),
imageSize,
ConvertToXmlAttribute(titre),
tagPhoto,
tagLinkbyuid,
uid,
resourceType,
isAttach,
ConvertToXmlAttribute(attachId)))
# files and other ressources types
if len(results.listAttachments())>0 and resourceType!='Image':
attachements = results.listAttachments()
index=0
for attachement in attachements :
titre = attachement.title_or_id()
# get Id
attachementId=results.getAttachmentId(index)
index +=1
# get Size object
try:
attachementSize=attachement.getSize()
except:
attachementSize=context.getObjSize(attachement)
tagPhoto= "no"
isAttach = "yes"
attachId=attachement.getFilename()
xmlFiles.append('''
<File name="%s"
size="%s"
title="%s"
photo="%s"
linkbyuid="%s"
uid="%s"
type="%s"
isPA3img="no"
isattach="%s"
attachid="%s" />'''%(ConvertToXmlAttribute(attachementId),
attachementSize,
ConvertToXmlAttribute(titre),
tagPhoto,
tagLinkbyuid,
uid,
resourceType,
isAttach,
ConvertToXmlAttribute(attachId)))
xmlFiles.append('\r </Files>')
xmlFolders.append('\r </Folders>')
if foldersOnly:
stringXml=''.join(xmlFolders)
else :
stringXml=''.join(xmlFolders)+''.join(xmlFiles)
return stringXml
def CreateXmlErrorNode (errorNumber,errorDescription):
return '''
<Error number="%s"
originalNumber="%s"
originalDescription="%s" />'''%(errorNumber,
errorNumber,
ConvertToXmlAttribute(errorDescription))
# 5. commands
# Specific Plone - for others CMS (CPS ...), for special folderish (Plone Article, doc flexible ...) change these lines
def GetFoldersAndFiles( resourceType, currentFolder ):
results=[]
user=context.REQUEST['AUTHENTICATED_USER']
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
# objet folderish
if obj.meta_type not in pa_meta_types:
types=context.portal_types
all_portal_types = [ctype.content_meta_type for ctype in types.objectValues()]
if resourceType=="Image" :
accepted_types=[ctype.content_meta_type for ctype in types.objectValues() if ctype.id in (image_portal_type, 'Photo', 'ZPhoto')]
elif resourceType=="Flash" :
accepted_types=[ctype.content_meta_type for ctype in types.objectValues() if ctype.id == flash_portal_type ]
else :
accepted_types = all_portal_types
for object in obj.objectValues():
if object.meta_type in accepted_types or (object.meta_type in all_portal_types and (object.isPrincipiaFolderish or object.meta_type in pa_meta_types)) :
review_state=container.portal_workflow.getInfoFor(object, 'review_state', '')
start_pub=getattr(object,'effective_date',None)
end_pub=getattr(object,'expiration_date',None)
if review_state not in unpublishedStates and not ((start_pub and start_pub > DateTime()) or (end_pub and DateTime() > end_pub)):
results.append(object)
elif user.has_role(rolesSeeUnpublishedContent,object) :
results.append(object)
results = [ s for s in results if user.has_permission('View', s) ]
return xmlString(results,resourceType,0,0)
# objet Plone article find attachements and images
else:
# oblige d'envoyer l'objet car trop specifique
return xmlString(obj,resourceType,0,1)
def GetFolders( resourceType, currentFolder ):
results=[]
user=context.REQUEST['AUTHENTICATED_USER']
types=context.portal_types
all_portal_types = [ctype.content_meta_type for ctype in types.objectValues()]
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
for object in obj.objectValues():
if object.meta_type in all_portal_types and (object.isPrincipiaFolderish or object.meta_type=='PloneArticle') :
review_state=container.portal_workflow.getInfoFor(object, 'review_state', '')
start_pub=getattr(object,'effective_date',None)
end_pub=getattr(object,'expiration_date',None)
if review_state not in unpublishedStates and not ((start_pub and start_pub > DateTime()) or (end_pub and DateTime() > end_pub)):
results.append(object)
elif user.has_role(rolesSeeUnpublishedContent,object) :
results.append(object)
results = [ s for s in results if user.has_permission('View', s) ]
return xmlString(results,resourceType,1,0)
def CreateFolder(currentFolder, folderName ):
user=context.REQUEST['AUTHENTICATED_USER']
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
sErrorNumber=""
# error cases
if not user.has_permission('Add portal content', obj) and not user.has_permission('Modify portal content', obj):
sErrorNumber = "103"
sErrorDescription = "folder creation forbidden"
if obj.meta_type == 'PloneArticle':
sErrorNumber = "103"
sErrorDescription = "folder creation forbidden"
if not folderName:
sErrorNumber = "102"
sErrorDescription = "invalid folder name"
if not sErrorNumber :
try :
folderTitle=utf8Decode(folderName)
folderName = fckCreateValidZopeId(utf8Encode(folderTitle))
new_id = obj.invokeFactory(id=folderName, type_name='Folder', title=folderTitle)
sErrorNumber = "0"
sErrorDescription = "success"
except :
sErrorNumber = "103"
sErrorDescription = "folder creation forbidden"
return CreateXmlErrorNode(sErrorNumber,sErrorDescription)
# 6. upload
def UploadFile(resourceType, currentFolder, data, title) :
user=context.REQUEST['AUTHENTICATED_USER']
if currentFolder != "/" :
obj = context.restrictedTraverse(currentFolder.lstrip('/'))
else :
obj = context.portal_url.getPortalObject()
error=""
idObj=""
if obj.meta_type != 'PloneArticle':
# define Portal Type to add
if resourceType == 'File':
typeToAdd = file_portal_type
elif resourceType == 'Flash':
typeToAdd = flash_portal_type
elif resourceType == 'Image' :
if obj.meta_type=="CMF ZPhotoSlides":
typeToAdd = 'ZPhoto'
elif obj.meta_type=="Photo Album":
typeToAdd = 'Photo'
elif obj.meta_type=="ATPhotoAlbum":
typeToAdd = 'ATPhoto'
else:
typeToAdd = image_portal_type
if not user.has_permission('Add portal content', obj) and not user.has_permission('Modify portal content', obj):
error = "103"
if resourceType == 'Image' and not allow_image_upload:
error = "103"
if resourceType == 'Flash' and not allow_flash_upload:
error = "103"
if resourceType not in ('Flash','Image') and not allow_file_upload:
error = "103"
if not data:
#pas de fichier
error= "202"
titre_data=''
filename=utf8Decode(getattr(data,'filename', ''))
titre_data=filename[max(string.rfind(filename, '/'),
string.rfind(filename, '\\'),
string.rfind(filename, ':'),
)+1:]
idObj=fckCreateValidZopeId(utf8Encode(titre_data))
if title :
titre_data=title
if not IsAllowedExt( FindExtension(idObj), resourceType ):
error= "202"
if not error :
error="0"
indice=0
exemple_titre=idObj
while exemple_titre in obj.objectIds():
indice=indice+1
exemple_titre=str(indice) + idObj
if indice!=0:
error= "201"
idObj = exemple_titre
try:
obj.invokeFactory(id=idObj, type_name=typeToAdd, title=titre_data )
newFile = getattr(obj, idObj)
newFile.edit(file=data)
obj.reindexObject()
except:
error = "103"
#Plone Article treatment
else :
# find Plone Article version
try :
image_brains = obj.getImageBrains()
attachment_brains = obj.getAttachmentBrains()
versionPA=3
except:
versionPA=2
if not data:
#pas de fichier
error= "1"
customMsg="no file uploaded"
else :
filename=utf8Decode(getattr(data,'filename', ''))
titre_data=filename[max(string.rfind(filename, '/'),
string.rfind(filename, '\\'),
string.rfind(filename, ':'),
)+1:]
# idObj can't be cleaned with PloneArticle attachements
# it's a problem but we do the job
idObj=fckCreateValidZopeId(utf8Encode(titre_data))
if title :
titre_data=title
if resourceType == 'Image' :
# Upload file
if not user.has_permission('Modify portal content', obj):
error = "103"
elif not allow_image_upload:
error = "103"
elif not IsAllowedExt( FindExtension(idObj), resourceType ):
error= "202"
customMsg="Invalid file type"
elif obj.portal_article.checkImageSize(data):
if versionPA==2 :
obj.appendImage(titre_data, data, )
else :
obj.addImage(title=titre_data, description='', image=data)
error="0"
try:
obj.reindexObject()
except:
parent = obj.aq_parent
parent.reindexObject()
else:
error="104"
else:
# Upload file
if not user.has_permission('Modify portal content', obj):
error = "103"
elif not allow_file_upload:
error = "103"
elif not IsAllowedExt( FindExtension(idObj), resourceType ):
error= "202"
customMsg="Invalid file type"
elif obj.portal_article.checkAttachmentSize(data):
if versionPA==2 :
obj.appendAttachment(titre_data, data, )
else :
obj.addAttachment(title=titre_data, description='', file=data)
error="0"
try:
obj.reindexObject()
except:
parent = obj.aq_parent
parent.reindexObject()
else:
error="104"
d= '''
<script type="text/javascript">
window.parent.frames['frmUpload'].OnUploadCompleted(%s,"%s") ;
</script>
'''% (error,idObj)
return d
#7. connector
request = context.REQUEST
RESPONSE = request.RESPONSE
dicoRequest = request.form
message_error=""
portal_url=context.portal_url.getPortalObject().absolute_url()
server_url = request.SERVER_URL
portal_path = portal_url.replace(server_url,'')
if ConfigUserFilesPath != "" :
sUserFilesPath = ConfigUserFilesPath
elif 'ServerPath' in dicoRequest:
sUserFilesPath = dicoRequest ['ServerPath']
else :
sUserFilesPath = "/"
if 'CurrentFolder' in dicoRequest:
sCurrentFolder = dicoRequest ['CurrentFolder']
if sUserFilesPath!='/' and sUserFilesPath.rstrip('/') not in sCurrentFolder:
sCurrentFolder = sUserFilesPath
else :
message_error="No CurrentFolder in request"
if 'Command' in dicoRequest:
sCommand = dicoRequest ['Command']
else :
message_error="No Command in request"
if 'Type' in dicoRequest:
sResourceType = dicoRequest ['Type']
else :
message_error="No Type in request"
if 'NewFolderName' in dicoRequest:
sFolderName = dicoRequest ['NewFolderName']
# interception File Upload
if sCommand=='FileUpload' and 'NewFile' in dicoRequest:
sData = dicoRequest ['NewFile']
sTitle = utf8Decode(dicoRequest ['Title'])
chaineHtmlUpload = UploadFile(sResourceType, sCurrentFolder, sData, sTitle)
RESPONSE.setHeader('Content-type', 'text/html; charset=%s' % charsetSite)
return chaineHtmlUpload
else :
# Creation response XML
if not message_error :
RESPONSE.setHeader('Cache-control','pre-check=0,post-check=0,must-revalidate,s-maxage=0,max-age=0,no-cache')
RESPONSE.setHeader('Content-type', 'text/xml; charset=utf-8')
xmlHeader = CreateXmlHeader (sCommand, sResourceType, sCurrentFolder)
if sCommand=="GetFolders":
xmlBody = GetFolders (sResourceType, sCurrentFolder)
elif sCommand=="GetFoldersAndFiles":
xmlBody = GetFoldersAndFiles (sResourceType, sCurrentFolder)
elif sCommand=="CreateFolder":
xmlBody = CreateFolder (sCurrentFolder,sFolderName)
xmlFooter = CreateXmlFooter()
return xmlHeader + xmlBody + xmlFooter
# creation response error request
else :
sErrorNumber="218"
sErrorDescription="Browser Request exception : " + message_error
xmlHeader = CreateXmlHeader (sCommand, sResourceType, sCurrentFolder)
xmlFooter = CreateXmlFooter()
return xmlHeader + CreateXmlErrorNode(sErrorNumber,sErrorDescription) + xmlFooter
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="_reconstructor" module="copy_reg"/>
</klass>
<tuple>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
<global name="object" module="__builtin__"/>
<none/>
</tuple>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>Command=\'\',Type=\'\',CurrentFolder=\'\',NewFolderName=\'\'</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>connectorPlone.py</string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
......@@ -4,7 +4,7 @@
xmlns:i18n="http://xml.zope.org/namespaces/i18n">
<tal:block metal:define-macro="header_definitions">
<tal:block tal:define="
global portal here/portal_url/getPortalObject;
global portal here/getPortalObject;
global portal_path portal_path | portal/absolute_url;
local_parameter_list local_parameter_list | python: {};
action_context python: portal.restrictedTraverse(request.get('object_path', '?'), here);
......@@ -49,7 +49,7 @@
title title | python:'ERP5';
header_title header_title | nothing;
"
tal:content="python: header_title or '%s | %s' % (title, here.getPortalObject().title_or_id())"
tal:content="python: header_title or '%s | %s' % (title, portal.title_or_id())"
></title>
<link rel="icon" tal:attributes="href python: portal_path + '/favicon.ico'" type="image/x-icon" />
<link rel="shortcut icon" tal:attributes="href python: portal_path + '/favicon.ico'" type="image/x-icon" />
......
......@@ -871,8 +871,7 @@ class ERP5Form(Base, ZMIForm, ZopePageTemplate):
return append
def add_default_field_library():
portal_url = getToolByName(self, 'portal_url')
portal = portal_url.getPortalObject()
portal = self.getPortalObject()
portal_skins = getToolByName(self, 'portal_skins')
default_field_library_path = portal.getProperty(
......
......@@ -1695,7 +1695,7 @@ def makeTreeList(here, form, root_dict, report_path, base_category,
portal_categories = getattr(form, 'portal_categories', None)
portal_domains = getattr(form, 'portal_domains', None)
portal_object = form.portal_url.getPortalObject()
portal_object = form.getPortalObject()
if len(report_path):
base_category = report_path[0]
......
......@@ -135,9 +135,7 @@ ignored_skin_id_set = {
'RelationFieldZuite_CommonTemplate',
'Field_getDescription',
'ERP5XhtmlStyle_redirect',
'connectorCPS.py',
'connectorERP5',
'connectorPlone.py',
'resolveUid',
'IndividualVariation_init',
'QuantityUnitConversion_getQuantityUnitList',
......
......@@ -286,7 +286,7 @@ def createZODBPythonScript(container, script_id, script_params,
.manage_addPythonScript(id = script_id)
script = container._getOb(script_id)
script.ZPythonScript_edit(script_params, script_content)
container.portal_url.getPortalObject().changeSkin(None)
container.getPortalObject().changeSkin(None)
return script
def removeZODBPythonScript(container, script_id):
......@@ -305,7 +305,7 @@ def createZODBFile(container, file_id, file_content_type, file_content):
content_type=file_content_type,
filedata=file_content)
container.portal_url.getPortalObject().changeSkin(None)
container.getPortalObject().changeSkin(None)
return zodb_file
# memcache tool
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment