Пример #1
0
 def listColumnInfos(self):
     (key, reverse) = self._getSorting()
     columns = ( {'key': 'Type',
                  'title': _(u'Type'),
                  'width': '20',
                  'colspan': '2'}
               , {'key': 'getId',
                  'title': _(u'Name'),
                  'width': '360',
                  'colspan': None}
               , {'key': 'modified',
                  'title': _(u'Last Modified'),
                  'width': '180',
                  'colspan': None}
               , {'key': 'position',
                  'title': _(u'Position'),
                  'width': '80',
                  'colspan': None }
               )
     for column in columns:
         if key == column['key'] and not reverse and key != 'position':
             query = make_query(key=column['key'], reverse=1)
         else:
             query = make_query(key=column['key'])
         column['url'] = '%s?%s' % (self._getViewURL(), query)
     return tuple(columns)
Пример #2
0
 def challenge(self, request, response):
   url = self.absolute_url()
   came_from = "%s?%s" % (
     request["ACTUAL_URL"], request.get("QUERY_STRING","")
     )
   idp = self.determine_idp()
   if idp:
     # we know the idp -- perform authentication
     #  Note: we must do a redirect to `authenticate` as it
     #  requires a successful transaction commit.
     #  The current transaction, however, will be aborted
     spsso = self.get_spsso()
     url = "%s/authenticate?%s" % (
       spsso.absolute_url(),
       make_query(idp=idp, ok=came_from, fail=url + "/" + self.failure_view)
       )
   else:
     url = "%s/%s?%s" % (
         url, self.select_idp_view, make_query(came_from=came_from)
       )
   # we hope the protocol chooser will ensure higher up user folders
   #  will still be able to get their chance
   #  otherwise, we will need to override "response._unauthorized"
   #  rather than performing the redirect here ourselves.
   response.redirect(url, lock=True)
   return True
Пример #3
0
 def _getRmByLanguage(self, lang):
     pc = getToolByName(self.context, 'portal_catalog')
     langinfo = _languagelist.copy()
     langinfo[''] = { 'name':   'International',
                      'native': 'int'}
     resultset = list()
     query = self.review_base_query
     q = query.copy()
     if lang:
         q['languageReview'] = [lang]
     else:
         q['languageReview'] = list(
             set(langinfo.keys()).difference(set(self.review_languages)))
     res = pc(q)
     for part in range(6 / len(self.review_languages)):
         resultset.append(
             dict(
                 language=lang or 'int',
                 part=part,
                 langname=langinfo[lang]['native'],
                 results=[dict(authors=self.format_authors(x),
                                 path=x.getPath(),
                                 title=x.getObject().punctuated_title_and_subtitle,
                                 date=self.format_effective_date(x['EffectiveDate'])) for x in res[part*5:part*5+4]],
                 query_str=make_query(q))
             )
     # print "getReviewMonographs", lang, len(res)
     return resultset
Пример #4
0
    def nextURL(self):
        obj = self._added_obj

        message = translate(self.status, self.context)
        if isinstance(message, unicode):
            message = message.encode(self._getBrowserCharset())
        return "%s/%s?%s" % (obj.absolute_url(), self.ti.immediate_view, make_query(portal_status_message=message))
Пример #5
0
 def alternate_link(self):
     query = {
         'location_precision': ['rough'],
         'path': {'query': [ob.context.getPath() for ob in self.objects],
                  'depth': 0}
         }
     return "https://pleiades.stoa.org/search?%s" % make_query(query)
Пример #6
0
    def _setRedirect(self, provider_id, action_path, keys=''):
        provider = getToolByName(self.context, provider_id)
        try:
            target = provider.getActionInfo(action_path, self.context,
                                            check_condition=1)['url']
        except (ValueError, zExceptions_Unauthorized):
            target = self._getPortalURL()

        kw = {}
        if self.status:
            message = translate(self.status, self.context)
            if isinstance(message, unicode):
                message = message.encode(self._getBrowserCharset())
            kw['portal_status_message'] = message
        for k in keys.split(','):
            k = k.strip()
            v = self.request.form.get(k, None)
            # filter out keys without values or with redundant default values
            if v and v != '0':
                kw[k] = v

        query = kw and ('?%s' % make_query(kw)) or ''
        self.request.RESPONSE.redirect('%s%s' % (target, query))

        return ''
Пример #7
0
    def partlinks(self):
        parts = self._standardparts
        customparts = self._customparts
        parts += tuple([part[0] for part in customparts])
        if not parts:
            return []

        url = self.context.absolute_url()
        query = {
            'domain': self.domain,
            'currentmonth': self.request.get('currentmonth', ''),
            'currentyear': self.request.get('currentyear', ''),
        }
        currentpart = self.request.get('currentpart', '')
        if not currentpart:
            currentpart = parts[0]

        partlinks = []
        for part in parts:
            query.update({'currentpart': part})
            partlink = dict()
            title = self.partlinktitles.get(part)
            if not title:
                for cpart in customparts:
                    if cpart[0] == part:
                        title = cpart[1]
                        break
            if not title:
                title = part
            partlink['title'] = title
            partlink['url'] = '%s?%s' % (url, make_query(query))
            partlink['style'] = part == currentpart and 'currentItem' or None
            partlinks.append(partlink)
        return partlinks
Пример #8
0
    def getIssueSearchQueryString(self, criteria=None, **kwargs):
        """Return a query string for an issue query.

        Form of return string:name1=value1&name2=value2
        """
        query = self.buildIssueSearchQuery(criteria, **kwargs)
        return make_query(query)
Пример #9
0
    def __init__(self, context, request):
        super(TimeReports, self).__init__(context, request)

        self.ettool = getToolByName(self.context, 'extropy_timetracker_tool')

        start = self.request.get('startdate', None)
        if not start:
            now = DateTime()
            # Default to showing the current year. During January we still
            # include the last year, as we usually still write bills for that
            # period.
            if now.month() > 1:
                start = '%s-01-01' % now.year()
            else:
                start = '%s-01-01' % (now.year() - 1)

        start = DateTime(start)
        self.start = start.earliestTime()

        end = self.request.get('enddate', None)
        end = end and DateTime(end) or DateTime()
        self.end = end.latestTime()

        self.query_string = make_query(*(
            {key: self.request[key]}
            for key in ('Creator', 'getBudgetCategory', 'startdate', 'enddate')
            if key in self.request))
        self.query_string = self.query_string and '?' + self.query_string
 def _getQueryString(self, **kwargs):
     params = dict()
     for key in self.request.form.keys():
         params[key] = self.request.form[key]
     params.update(kwargs)
     query = make_query(params)
     return query
Пример #11
0
def wrapWithShadow(payment_transaction, person_relative_url):
  web_site = context.getWebSiteValue()

  transaction_date, transaction_id = payment_transaction.PaymentTransaction_getPayzenId()
  if transaction_id is not None:
    message = payment_transaction.Base_translateString("Payment already registered.")
    return web_site.Base_redirect(keep_items={'portal_status_message': message})

  system_event = payment_transaction.PaymentTransaction_createPayzenEvent(
    title='User navigation script for %s' % payment_transaction.getTitle(),
    destination_section=person_relative_url,
  )

  callback_websection = web_site.payzen_callback
  query = make_query(dict(transaction=payment_transaction.getRelativeUrl()))
  system_event.generateManualPaymentPage(
    vads_url_cancel='%s?%s' % (callback_websection.cancel.absolute_url(), query),
    vads_url_error='%s?%s' % (callback_websection.error.absolute_url(), query),
    vads_url_referral='%s?%s' % (callback_websection.referral.absolute_url(), query),
    vads_url_refused='%s?%s' % (callback_websection.refused.absolute_url(), query),
    vads_url_success='%s?%s' % (callback_websection.success.absolute_url(), query),
    vads_url_return='%s?%s' % (getattr(callback_websection, 'return').absolute_url(), query),
  )

  return system_event.contentValues(
    portal_type="Payzen Event Message")[0].getTextContent()
Пример #12
0
 def getHeader(self, path):
   real_path = self.working_copy
   if path != '.':
     real_path = os.path.join(real_path, path)
   return '<a style="font-weight: bold"' \
          ' href="BusinessTemplate_viewVcsShowFile?%s">%s</a>%s' \
          % (make_query(file=path), real_path, self.editPath(path, True))
Пример #13
0
 def makeUrl(self, index):
     batch = self.batches[index]
     query = {self.table.prefix + '-batchStart': batch.start,
              self.table.prefix + '-batchSize': batch.size}
     querystring = make_query(query)
     base = url_query(self.request, omit=query.keys())
     return '%s&%s' % (base, querystring)
Пример #14
0
    def calcReport(self):
        form = self.request.form
        query = self._getBasicQuery()

        if 'Date' not in query:
            query['Date'] = {"query":DateTime() - 8, 'range':'min'}

        ctool = getToolByName(self.context, 'portal_catalog')
        active_projects = ctool(portal_type='Project', review_state='active')
        paths = [p.getPath() for p in active_projects]

        query['path'] = paths
        brains = ctool.searchResults(query)

        allitems = {}
        hours = 0
        for item in brains:
            path = item.getPath().split('/')
            projectid = path[-3]

            if projectid not in allitems:
                allitems[projectid] = [item]
            else:
                allitems[projectid].append(item)
            hours += item.getHours

        q_str = make_query(form)

        return { "brains": allitems, "hours": hours,
                 'csv_url':self.context.absolute_url() + '/time-report.csv?' + q_str}
Пример #15
0
  def commit(self, changelog, added=(), modified=(), removed=()):
    """Commit local changes.
    """
    context = self.aq_parent
    # Pysvn wants unicode objects
    if isinstance(changelog, str):
      changelog = changelog.decode('utf8')

    def getRevisionNumber(revision):
      # get the revision number from a revision,
      # with backward compatibility support
      try:
        return revision.getNumber()
      except AttributeError:
        return revision

    # In order not to commit deleted files in a separate commit,
    # we revert unselected files before committing everything recursively.
    selected_set = set(added)
    selected_set.update(modified)
    selected_set.update(removed)
    assert selected_set, "nothing to commit"
    self.revert('.', recurse=True, exclude_set=selected_set)
    revision = self._getClient().checkin('.', changelog, True)
    return context.REQUEST.RESPONSE.redirect('%s/view?%s' % (
      context.absolute_url_path(),
      make_query(portal_status_message=translateString(
        'Files committed successfully in revision ${revision}',
        mapping=dict(revision=getRevisionNumber(revision))))))
 def topicQueryString(self):
     # BBB: seems ununsed
     topic = self.rootTopic()
     if IATTopic.providedBy(topic):
         return make_query(topic.buildQuery())
     else:
         raise NotImplementedError('No support for %s yet' % topic.portal_type)
Пример #17
0
 def getReviewMonographs(self):
     pc = getToolByName(self.context, 'portal_catalog')
     langinfo = _languagelist.copy()
     langinfo[''] = { 'name':   'International',
                      'native': 'int'}
     query = dict(portal_type=["Review Monograph", "Review Journal"],
         review_state="published",
         sort_on='effective',
         sort_order='reverse', b_size=5)
     resultset = list()
     for lang in REVIEW_LANGUAGES:
         q = query.copy()
         if lang:
             q['languageReview'] = [lang]
         else:
             q['languageReview'] = list(
                 set(langinfo.keys()).difference(set(REVIEW_LANGUAGES)))
         res = pc(q)
         resultset.append(
             dict(
                 language=lang or 'int',
                 langname=langinfo[lang]['native'],
                 results=[dict(authors=self.format_authors(x),
                                 url=x.getURL(),
                                 title=x.getObject().punctuated_title_and_subtitle,
                                 date=self.format_effective_date(x['EffectiveDate'])) for x in res[:5]],
                 query_str=make_query(q))
             )
         # print "getReviewMonographs", lang, len(res)
     return resultset
Пример #18
0
 def get_action_url(self, action):
     form = self.request.form.copy()
     if '-C' in form:
         del form['-C']
     query = make_query(form)
     if query:
         return "%s?%s" % (action, query)
     return action
Пример #19
0
 def alternate_link(self):
     portal_url = getToolByName(self.context, 'portal_url')()
     query = {
         'location_precision': ['rough'],
         'path': {'query': [ob.context.getPath() for ob in self.objects],
                  'depth': 0}
         }
     return "%s/search?%s" % (portal_url, make_query(query))
Пример #20
0
 def makeUrl(self, index):
     batch = self.batches[index]
     baseQuery = dict(self.request.form)
     query = {self.table.prefix + '-batchStart': batch.start,
              self.table.prefix + '-batchSize': batch.size}
     baseQuery.update(query)
     querystring = make_query(baseQuery)
     base = url_query(self.request, omit=baseQuery.keys())
     return '%s&%s' % (base, querystring)
Пример #21
0
 def _getPreviousUrl(self, batch):
     """
     """
     try:
         start_str = batch.previous.first
     except AttributeError:
         start_str = None 
         
     query = make_query(self.request.form, {batch.b_start_str:start_str})
     return "%s?%s" % (self.context.absolute_url(), query)
Пример #22
0
 def _getNextUrl(self, batch):
     """
     """
     try:
         start_str = batch.next.first
     except AttributeError:
         start_str = None 
         
     query = make_query(self.request.form, {batch.b_start_str:start_str})
     return "%s/manage-products?%s" % (self.context.absolute_url(), query)
 def getAllRelatedItemsLink(self):
     portal_state = getMultiAdapter((self.context, self.request), name=u"plone_portal_state")
     portal_url = portal_state.portal_url()
     context = aq_inner(self.context)
     req_items = {}
     # make_query renders tuples literally, so let's make it a list
     req_items["Subject"] = list(context.Subject())
     if not self.data.show_all_types:
         req_items["portal_type"] = list(self.data.allowed_types)
     return "%s/search?%s" % (portal_url, make_query(req_items))
Пример #24
0
    def sortURLSelect(self, sort_on, sort_order):

        #template_id = self.__name__        
        # explicit is better than implicit
        #if template_id == 'view':
        #    template_id = None
            
        qry = make_query(self.request.form, {'sort_on' : sort_on, 
                                             'sort_order' : sort_order})
        #if template_id:
        return "%s?%s" % (self.__name__, qry)
Пример #25
0
 def _get_toggle_link(self, uid):
     expand = self.request.get('expand', [])[:]
     if uid in expand:
         expand.remove(uid)
     else:
         expand.append(uid)
     toggle_link = '%s?%s#%s' % (
         self.context.absolute_url(),
         make_query(expand=expand),
         uid)
     return toggle_link
Пример #26
0
    def _getNavigationURL(self, b_start):
        target = self._getViewURL()
        kw = self._getHiddenVars()

        kw['b_start'] = b_start
        for k, v in kw.items():
            if not v or k == 'portal_status_message':
                del kw[k]

        query = kw and ('?%s' % make_query(kw)) or ''
        return u'%s%s' % (target, query)
Пример #27
0
 def checkUseSSL(self):
     portal = getToolByName(self.context, 'portal_url').getPortalObject()
     if IGetPaidManagementOptions(portal).use_ssl_for_checkout:
         # we need to become https if we are not already
         # unless we are cancelling or on the thank you page
         url = self.request.getURL()
         if not 'https://' in url:
             url = url.replace("http://", "https://")
             self.request.response.redirect('%s?%s' % (
                 url, make_query(self.request.form)))
     return True
Пример #28
0
    def make_link(self, pagenumber=None):
        form = self.request.form
        if self.batchformkeys:
            batchlinkparams = dict([(key, form[key])
                                    for key in self.batchformkeys
                                    if key in form])
        else:
            batchlinkparams = form.copy()

        start = max(pagenumber - 1, 0) * self.batch.pagesize
        return '%s?%s' % (self.request.ACTUAL_URL, make_query(batchlinkparams,
                         {self.batch.b_start_str: start}))
Пример #29
0
 def next_page_url(self, total_results):
     """Get url for the next page of results"""
     next_page_number = self.next_page_number(total_results)
     if not next_page_number:
         return
     new_query = make_query(
         self.request.form.copy(),
         {'page': next_page_number}
     )
     return '{url}?{qs}'.format(
         url=self.request.ACTUAL_URL,
         qs=new_query
     )
Пример #30
0
    def url(self):
        q = {}
        q.update(self.request.form)
        if 'sort_on' in q.keys():
            del q['sort_on']
        if 'sort_order' in q.keys():
            del q['sort_order']
        q['sort_on'] = self.sortkey
        if self.reverse:
            q['sort_order'] = 'reverse'

        base_url = self.request.URL
        return base_url + '?' + make_query(q)
Пример #31
0
def addQuery(request, url, exclude=tuple(), **extras):
    """Adds the incoming GET query to the end of the url
    so that is propagated through the redirect hoops
    """
    formvariables = {}
    for k, v in request.form.items():
        if k not in exclude:
            if isinstance(v, six.text_type):
                formvariables[k] = v.encode('utf-8')
            else:
                formvariables[k] = v
    for k, v in extras.items():
        if isinstance(v, six.text_type):
            formvariables[k] = v.encode('utf-8')
        else:
            formvariables[k] = v
    try:
        if len(formvariables) > 0:
            url += '?' + make_query(formvariables)
    # Again, LinguaPlone did this try/except here so I'm keeping it.
    except UnicodeError:
        pass
    return url
Пример #32
0
    def _setRedirect(self, provider_iface, action_path, keys=''):
        provider = self._getToolByInterfaceName(provider_iface)
        try:
            target = provider.getActionInfo(action_path, self.context)['url']
        except ValueError:
            target = self._getPortalURL()

        kw = {}
        if self.status:
            message = translate(self.status, self.context)
            if isinstance(message, unicode):
                message = message.encode(self._getBrowserCharset())
            kw['portal_status_message'] = message
        for k in keys.split(','):
            k = k.strip()
            v = self.request.form.get(k, None)
            if v:
                kw[k] = v

        query = kw and ('?%s' % make_query(kw)) or ''
        self.request.RESPONSE.redirect('%s%s' % (target, query))

        return ''
Пример #33
0
    def _setRedirect(self, provider_id, action_path, keys=''):
        provider = self._getTool(provider_id)
        try:
            target = provider.getActionInfo(action_path, self.context)['url']
        except ValueError:
            target = self._getPortalURL()

        kw = {}
        message = self.request.other.get('portal_status_message', '')
        if message:
            if isinstance(message, unicode):
                message = message.encode(self._getDefaultCharset())
            kw['portal_status_message'] = message
        for k in keys.split(','):
            k = k.strip()
            v = self.request.form.get(k, None)
            if v:
                kw[k] = v

        query = kw and ('?%s' % make_query(kw)) or ''
        self.request.RESPONSE.redirect('%s%s' % (target, query))

        return True
Пример #34
0
    def getListItemUrl(self, cname_id, selection_index, selection_name):
        """Returns the URL for column `cname_id`. Used by ListBox
    """
        resource = self.getResourceValue()
        if cname_id in (
                'getExplanationText',
                'getExplanation',
        ):
            o = self.getObject()
            if o is not None:
                if not getattr(o, 'isDelivery', 0):
                    explanation = o.getExplanationValue()
                else:
                    # Additional inventory movements are catalogged in stock table
                    # with the inventory's uid. Then they are their own explanation.
                    explanation = o
                if explanation is not None:
                    return explanation.absolute_url()
            return ''
        elif resource is not None:
            if cname_id in ('transformed_resource_title', ):
                return resource.absolute_url()
            # A resource is defined, so try to display the movement list
            form_id = 'Resource_viewMovementHistory'
            query_kw = self.getListItemParamDict(cname_id, selection_index,
                                                 selection_name)
            return '%s/%s?%s&reset=1' % (resource.absolute_url(), form_id,
                                         make_query(**query_kw))

        # default case, if it's a movement, return link to the explanation of this
        # movement.
        document = self.getObject()
        if document.isMovement():
            explanation = document.getExplanationValue()
            if explanation is not None:
                return explanation.absolute_url()
        return ''
Пример #35
0
  def login(self):
    """explicit login request."""
    pu_tool = getToolByName(self, "portal_url")
    r = self.REQUEST; purl = pu_tool()
    if r.get('came_from'):
      came_from = r['came_from']
      r.response.expireCookie('came_from')
    else:
      came_from = r.get("HTTP_REFERER") or purl

    if not pu_tool.isURLInPortal(came_from):
      came_from = purl

    idp = self.determine_idp()
    if idp:
      return self.authn(idp, came_from,
                        self.absolute_url() + "/" + self.failure_view
                        )
    else:
      r.response.redirect("%s/%s?%s" % (
        self.absolute_url(),
        self.select_idp_view,
        make_query(came_from=came_from)
        ))
Пример #36
0
    return message

ignore_layout = int(ignore_layout)
editable_mode = int(editable_mode)
spp = context.getPhysicalPath()
spp = list(spp)
s_url = request["SERVER_URL"]
spp.insert(0, s_url)
#calculate direct the url instead of using absolute_url
new_url = '/'.join(spp)

# for web mode, we should use 'view' instead of passed form_id
# after 'Save & View'.
if context.REQUEST.get('is_web_mode', False) and \
    not editable_mode:
    form_id = 'view'

redirect_url_kw = dict(ignore_layout=ignore_layout,
                       editable_mode=editable_mode,
                       portal_status_message=message)
if selection_index:
    redirect_url_kw.update(selection_index=selection_index,
                           selection_name=selection_name)
redirect_url = '%s/%s?%s' % (context.absolute_url(), form_id,
                             make_query(**redirect_url_kw))

result = request['RESPONSE'].redirect(redirect_url)

if silent_mode: return result, 'redirect'
return result
Пример #37
0
 def makeQuery(self):
     if hasattr(self.request, 'userid'):
         return '?' + make_query(
             {'userid': self.request.form.get('userid')})
     return ''
Пример #38
0
##parameters=member=None, password='******', email='*****@*****.**', **kw
##
from ZTUtils import make_query
from Products.CMFCore.utils import getToolByName
mtool = getToolByName(script, 'portal_membership')
ptool = getToolByName(script, 'portal_properties')
utool = getToolByName(script, 'portal_url')
portal_url = utool()
member_id = member and member.getId() or 'foo'


options = {}

options['member_email'] = '<%s>' % email
options['email_from_name'] = ptool.getProperty('email_from_name')
options['email_from_address'] = '<%s>' % ptool.getProperty(
                                                  'email_from_address')
options['portal_title'] = ptool.title()
options['portal_description'] = ptool.getProperty('description')
options['portal_url'] = '<%s>' % portal_url
options['member_id'] = member_id
options['password'] = password
target = mtool.getActionInfo('user/logged_in')['url']
query = make_query(__ac_name=member_id, __ac_password=password)
options['login_url'] = '<%s?%s>' % (target, query)

return options
Пример #39
0
    def getListItemUrl(self, cname_id, selection_index, selection_name):
        """Returns the URL for column `cname_id`. Used by ListBox
    """
        resource = self.getResourceValue()
        if cname_id in (
                'getExplanationText',
                'getExplanation',
        ):
            o = self.getObject()
            if o is not None:
                if not getattr(o, 'isDelivery', 0):
                    explanation = o.getExplanationValue()
                else:
                    # Additional inventory movements are catalogged in stock table
                    # with the inventory's uid. Then they are their own explanation.
                    explanation = o
                if explanation is not None:
                    return explanation.absolute_url()
            return ''
        elif resource is not None:
            # A resource is defined, so try to display the movement list
            form_id = 'Resource_viewMovementHistory'
            query_kw = {
                'variation_text': self.variation_text,
                'selection_name': selection_name,
                'selection_index': selection_index,
                'domain_name': selection_name,
                "node_uid": self.node_uid
            }
            # Add parameters to query_kw
            query_kw_update = {}

            if cname_id in ('transformed_resource_title', ):
                return resource.absolute_url()
            elif cname_id in ('getCurrentInventory', ):
                query_kw_update = {
                  'simulation_state':
                    list(self.getPortalCurrentInventoryStateList() + \
                    self.getPortalTransitInventoryStateList()),
                  'omit_transit': 1,
                  'transit_simulation_state': list(
                         self.getPortalTransitInventoryStateList())
                }

            elif cname_id in ('getAvailableInventory', ):
                query_kw_update = {
                  'simulation_state': list(self.getPortalCurrentInventoryStateList() + \
                                    self.getPortalTransitInventoryStateList()),
                  'omit_transit': 1,
                  'transit_simulation_state': list(self.getPortalTransitInventoryStateList()),
                  'reserved_kw': {
                    'simulation_state': list(self.getPortalReservedInventoryStateList()),
                    'transit_simulation_state': list(self.getPortalTransitInventoryStateList()),
                    'omit_input': 1
                  }
                }
            elif cname_id in (
                    'getFutureInventory',
                    'inventory',
            ):
                query_kw_update = {
                  'simulation_state': \
                    list(self.getPortalFutureInventoryStateList()) + \
                    list(self.getPortalTransitInventoryStateList()) + \
                    list(self.getPortalReservedInventoryStateList()) + \
                    list(self.getPortalCurrentInventoryStateList())
                }
            elif cname_id in ('getInventoryAtDate', ):
                query_kw_update = {
                  'to_date': self.at_date,
                  'simulation_state': \
                    list(self.getPortalFutureInventoryStateList()) + \
                    list(self.getPortalReservedInventoryStateList())
                }
            query_kw.update(query_kw_update)
            return '%s/%s?%s&reset=1' % (resource.absolute_url(), form_id,
                                         make_query(**query_kw))

        # default case, if it's a movement, return link to the explanation of this
        # movement.
        document = self.getObject()
        if document.isMovement():
            explanation = document.getExplanationValue()
            if explanation is not None:
                return explanation.absolute_url()
        return ''
Пример #40
0
 def __call__(self):
     member = aq_parent(aq_parent(self.context))
     portal_url = getToolByName(self.context, 'portal_url')()
     return "%s/prefs_user_details?%s" % (
         portal_url, make_query(userid=member.getUserId()))
Пример #41
0
    def languages(self):
        context = aq_inner(self.context)
        results = LanguageSelector.languages(self)
        supported_langs = [v['code'] for v in results]
        missing = set([str(c) for c in supported_langs])
        translations = self._translations(missing)
        # We want to preserve the current template / view as used for the
        # current object and also use it for the other languages
        append_path = self._findpath(context.getPhysicalPath(),
                                     self.request.get('PATH_INFO', ''))
        formvariables = get_formvariables(self.request)
        _checkPermission = getSecurityManager().checkPermission

        non_viewable = set()
        for data in results:
            code = str(data['code'])
            data['translated'] = code in translations.keys()
            set_language = '?set_language=%s' % code

            try:
                appendtourl = '/'.join(append_path)
                if self.set_language:
                    appendtourl += '?' + make_query(formvariables,
                                                    dict(set_language=code))
                elif formvariables:
                    appendtourl += '?' + make_query(formvariables)
            except UnicodeError:
                appendtourl = '/'.join(append_path)
                if self.set_language:
                    appendtourl += set_language

            if data['translated']:
                trans, direct, has_view_permission = translations[code]
                if not has_view_permission:
                    # shortcut if the user cannot see the item
                    non_viewable.add((data['code']))
                    continue

                state = getMultiAdapter((trans, self.request),
                                        name='plone_context_state')
                if direct:
                    data['url'] = state.canonical_object_url() + appendtourl
                else:
                    data['url'] = state.canonical_object_url() + set_language
            else:
                has_view_permission = bool(_checkPermission('View', context))
                # Ideally, we should also check the View permission of default
                # items of folderish objects.
                # However, this would be expensive at it would mean that the
                # default item should be loaded as well.
                #
                # IOW, it is a conscious decision to not take in account the
                # use case where a user has View permission a folder but not on
                # its default item.
                if not has_view_permission:
                    non_viewable.add((data['code']))
                    continue

                state = getMultiAdapter((context, self.request),
                                        name='plone_context_state')
                try:
                    data['url'] = state.canonical_object_url() + appendtourl
                except AttributeError:
                    data['url'] = context.absolute_url() + appendtourl

        # filter out non-viewable items
        results = [r for r in results if r['code'] not in non_viewable]
        return results
Пример #42
0
web_page_module = context.web_page_module

# Find the applicable language
language = portal.Localizer.get_selected_language()

# Create a new empty page
web_page = web_page_module.newContent(portal_type='Web Page',
                                      title="New Page of Section %s" % title,
                                      version="1",
                                      language=language)

# Copy categories into new Web Page
category_list = context.getMembershipCriterionCategoryList()
web_page.setCategoryList(web_page.getCategoryList() + category_list)

# Return the new page in the section context
keep_items = dict(editable_mode=1,
                  portal_status_message=translateString(
                      "New Web Page of section ${web_section}.",
                      mapping=dict(web_section=title)))

request_form.update(keep_items)
message = make_query(
    dict([(k, v) for k, v in request_form.items() if k and v is not None]))

redirect_url = '%s/%s/view?%s' % (context.absolute_url(),
                                  web_page.getRelativeUrl(), message)

# return to the new page in the section context
return context.REQUEST.RESPONSE.redirect(redirect_url)
Пример #43
0
    'width': '360',
    'colspan': None
}, {
    'key': 'modified',
    'title': _(u'Last Modified'),
    'width': '180',
    'colspan': None
}, {
    'key': 'position',
    'title': _(u'Position'),
    'width': '80',
    'colspan': None
})
for column in columns:
    if key == column['key'] and not reverse and key != 'position':
        query = make_query(key=column['key'], reverse=1)
    else:
        query = make_query(key=column['key'])
    column['url'] = '%s?%s' % (target, query)

context.filterCookie()
folderfilter = context.REQUEST.get('folderfilter', '')
filter = context.decodeFolderFilter(folderfilter)
items = context.listFolderContents(contentFilter=filter)
items = sequence.sort(items, ((key, 'cmp', reverse and 'desc' or 'asc'), ))
batch_obj = Batch(items, 25, b_start, orphan=0)
items = []
i = 1
for item in batch_obj:
    item_icon = item.getIcon(1)
    item_id = item.getId()
Пример #44
0
            message = context.Base_translateString('Password is expired.')
    else:
        message = context.Base_translateString(
            'Login and/or password is incorrect.')

    url = '%s/login_form?portal_status_message=%s' % (context.absolute_url(),
                                                      message)
    url = came_from and '%s&came_from=%s' % (url, came_from) or url
    RESPONSE.redirect(url)
else:
    # XXX How to warn user that password will expire?
    # is_user_account_password_expired_expire_date = REQUEST.get('is_user_account_password_expired_expire_date', 0)

    # XXX Hardcoded behaviour for JS app.
    # Expect came_from to be an URL template
    person = portal.ERP5Site_getAuthenticatedMemberPersonValue()
    url_parameter = "n.me"
    pattern = '{[&|?]%s}' % url_parameter
    if (person is None):
        came_from = re.sub(pattern, '', came_from)
    else:
        prefix = "&" if "&%s" % url_parameter in came_from else "?"
        came_from = re.sub(
            pattern, '%s%s' %
            (prefix, make_query({url_parameter: person.getRelativeUrl()})),
            came_from)
    # RESPONSE.redirect(came_from or context.getPermanentURL(context));
    RESPONSE.setHeader('Location', came_from
                       or context.getPermanentURL(context))
    RESPONSE.setStatus(303)
Пример #45
0
 def make_link(self, pagenumber):
     batchlinkparams = self.request.form.copy()
     return '%s?%s' % (self.request.ACTUAL_URL,
                       make_query(batchlinkparams,
                                  {'pagenumber': pagenumber}))
Пример #46
0
        if obj is None:
            # this might be a category
            obj = portal.portal_categories.resolveCategory(
                "%s/%s" % (base_category, path))

        if obj is not None and checkPerm("View", obj):
            related_object_list.append(obj)
    if len(related_object_list) == 0:
        url = context.absolute_url()
        message = Base_translateString(
            "You are not authorised to view any related document.")
        relation_found = 0
    else:
        request = portal.REQUEST
        selection_uid_list = [x.getUid() for x in related_object_list]
        kw = {'uid': selection_uid_list}
        portal.portal_selections.setSelectionParamsFor(
            'Base_jumpToRelatedObjectList', kw)
        request.set('object_uid', context.getUid())
        request.set('uids', selection_uid_list)
        return getattr(context, relation_form_id)(uids=selection_uid_list,
                                                  REQUEST=request)

query_params = dict(portal_status_message=message)
if selection_name and not relation_found:
    query_params['selection_name'] = selection_name
    query_params['selection_index'] = selection_index

redirect_url = '%s/%s?%s' % (url, form_id, make_query(query_params))
return context.REQUEST['RESPONSE'].redirect(redirect_url)
Пример #47
0
        # create a new cell
        base_id = 'movement'
        if not container_line.hasCell(base_id=base_id, *cell_key):
          cell = container_line.newCell(
                     base_id=base_id,
                     portal_type="Container Cell",
                     *cell_key
          )
          cell.setCategoryList(cell_key)
          cell.setMappedValuePropertyList(['quantity'])
          cell.setMembershipCriterionCategoryList(cell_key)
          cell.setMembershipCriterionBaseCategoryList(
                                          line_variation_base_category_list)
          cell.edit(quantity=quantity)

# Container must be immediately reindexed, 
# in order to see good packed quantity in fast input form
container.recursiveImmediateReindexObject()

url_params = make_query(selection_name=selection_name, 
                        dialog_category=dialog_category, 
                        form_id=form_id, 
                        cancel_url=cancel_url,
                        portal_status_message='%s container(s) created.' %\
                                                                container_count)

redirect_url = '%s/SalePackingList_fastInputForm?%s' %\
                            (context.absolute_url(), url_params)

context.REQUEST[ 'RESPONSE' ].redirect(redirect_url)
Пример #48
0
   be redundant.
"""
from ZTUtils import make_query
import json

request_form = context.REQUEST.form
request_form.update(kw)
request_form = context.ERP5Site_filterParameterList(request_form)
request_form.update(keep_items)

if form_id == 'view':
    redirect_url = "%s/ERP5Document_getHateoas" % context.absolute_url()
else:
    redirect_url = '%s/%s' % (context.absolute_url(), form_id)

parameters = make_query(
    dict([(k, v) for k, v in request_form.items() if k and v is not None]))
if len(parameters):
    if '?' in redirect_url:
        separator = '&'
    else:
        separator = '?'
    redirect_url = '%s%s%s' % (redirect_url, separator, parameters)

# XXX Allow CORS
response = context.REQUEST.RESPONSE
context.Base_prepareCorsResponse(RESPONSE=response)
# http://en.wikipedia.org/wiki/Post/Redirect/Get
response.setStatus(201)
response.setHeader("X-Location", "urn:jio:get:%s" % context.getRelativeUrl())

result_dict = {
Пример #49
0
import re
from ZTUtils import make_query

portal = context.getPortalObject()

# XXX Hardcoded behaviour for JS app.
# Expect came_from to be an URL template
person = portal.portal_membership.getAuthenticatedMember().getUserValue()
url_parameter = "n.me"
pattern = '{[&|?]%s}' % url_parameter
if (person is None or not portal.portal_membership.checkPermission('View', person)):
  came_from = re.sub(pattern, '', came_from)
else:
  prefix = "&" if "&%s" % url_parameter in came_from else "?"
  came_from = re.sub(pattern, '%s%s' % (prefix, make_query({url_parameter: person.getRelativeUrl()})), came_from)

return came_from
Пример #50
0
if dialog_method != update_method and clean_kw.get('deferred_style', 0):
  clean_kw['deferred_portal_skin'] = clean_kw.get('portal_skin', None)
  # XXX Hardcoded Deferred style name
  clean_kw['portal_skin'] = 'Deferred'
  
  dialog_form = getattr(context, dialog_method)
  page_template = getattr(dialog_form, 'pt', None)
  # If the action form has report_view as it's method, it 
  if page_template != 'report_view':
    # use simple wrapper
    clean_kw['deferred_style_dialog_method'] = dialog_method
    kw['deferred_style_dialog_method'] = dialog_method
    request.set('deferred_style_dialog_method', dialog_method)
    dialog_method = 'Base_activateSimpleView'

url_params_string = make_query(clean_kw)

# XXX: We always redirect in report mode to make sure portal_skin
# parameter is taken into account by SkinTool.
# If url is too long, we do not redirect to avoid crash.
# XXX: 2000 is an arbitrary value resulted from trial and error.
if (not(can_redirect) or len(url_params_string) > 2000):
  if dialog_method != update_method:
    # When we are not executing the update action, we have to change the skin
    # manually,
    if 'portal_skin' in clean_kw:
      new_skin_name = clean_kw['portal_skin']
      context.getPortalObject().portal_skins.changeSkin(new_skin_name)
      request.set('portal_skin', new_skin_name)
      deferred_portal_skin = clean_kw.get('deferred_portal_skin')
      if deferred_portal_skin:
Пример #51
0
 def getExplanationUrl(self, *args, **w):
   return '%s/BudgetLine_viewConsumedBudgetMovementList?%s' % (
                self.url,
                make_query(dict(cell_index=list(self.cell_index), engaged_budget=self.engaged_budget)))
Пример #52
0
request = context.REQUEST

from ZTUtils import make_query
kw = {'portal_skin': 'CSV', 'export_only': export_only}

redirect_url = '%s?%s' % (context.absolute_url() + '/' + form_id,
                          make_query(kw))

return request['RESPONSE'].redirect(redirect_url)
Пример #53
0
 def makeQuery(self):
     userid = self.request.form.get('userid', None)
     if userid is not None:
         return '?{}'.format(make_query({'userid': userid}))
     return ''
Пример #54
0
 def __call__(self):
     member = aq_parent(self.context)
     portal_url = getToolByName(self.context, 'portal_url')()
     return "%s/@@user-information?%s" % (
         portal_url, make_query(userid=member.getUserId()))
Пример #55
0
 def makeQuery(self, **kw):
     return make_query(**kw)
Пример #56
0
  def render(self, field, key, value, REQUEST, render_format='html', render_prefix=None):

    """
      Render a chart.

      render_format   -- If the format is set to html, render the chart
                         as a URL to ourselves with a png render_format

                         If the format is set to 'raw', render the chart
                         as raw XML.

                         If the format is set to an image type (ex. png)
                         render the chart using that format.
    """
    title = field.get_value('title')
    alt = field.get_value('description') or title
    form = field.aq_parent
    if not render_prefix:
      render_prefix = REQUEST.get('render_prefix')
    # Find the applicable context
    here = getattr(form, 'aq_parent', REQUEST)
    # Update the render format based on REQUEST parameters
    render_format = getattr(REQUEST, 'render_format', render_format)
    if render_format == 'html':
      css_class = field.get_value('css_class')
      format = field.get_value('image_format') or 'png'
      query_dict = dict(REQUEST.form.items())
      query_dict.update(render_format=format != 'raw' and format or '',
                        render_prefix=render_prefix,
                        display=field.get_value('image_display'))
      # XXX make_query does not handle tuples properly so listbox should be
      #     not editable (otherwise, REQUEST.form may contain listbox=()).
      url = '%s/%s/%s?%s' % (here.absolute_url(), form.getId(), field.getId(),
                             make_query(query_dict))
      if format in VALID_IMAGE_FORMAT_LIST:
        return '''<div class="OOoChartContent">
          <img class="%s" src="%s" title="%s" alt="%s"/">
          </div>''' % (css_class,
                       url,
                       title,
                       alt)
      elif format == 'raw':
        UrlIconOOo = '%s/misc_/ERP5OOo/OOo.png' % REQUEST['BASEPATH1']
        return '''<div class="OOoChartContent">
          <a href="%s"><img src="%s" alt="OOo"/></a>
          </div>''' % (url,
                       UrlIconOOo)
      elif format == 'pdf':
        UrlIconPdf = '%s/misc_/ERP5Form/PDF.png' % REQUEST['BASEPATH1']
        return '''<div class="OOoChartContent">
          <a href="%s"><img src="%s" alt="PDF" /></a>
          </div>''' % (url,
                       UrlIconPdf)
      else:
        raise NotImplementedError, 'Format: %s not handled' % format

    extra_context = self.getArgumentDict(field, REQUEST)

    method_id = field.get_value('ooo_template')

    # Find the page template
    ooo_template = getattr(here, method_id)

    # Render the chart
    return ooo_template(format=render_format, **extra_context)
Пример #57
0
 def pageurl(self, formvariables, pagenumber=-1):
     """ Makes the url for a given page """
     if pagenumber == -1:
         pagenumber = self.pagenumber
     b_start = pagenumber * (self.pagesize - self.overlap) - self.pagesize
     return make_query(formvariables, {self.b_start_str: b_start})
Пример #58
0
## Valid values for lensVersionStart are 'this' and 'latest'
#versionStart = lensVersionStart == 'this' and version or history[-1].version
#versionStop = lensVersionStop == 'this' and version or None

# new version defaults
versionStart = version  # current
versionStop = 'latest'  # latest

cmpVersion = [int(x) for x in version.split('.')]

try:
    if lensPath == '__new__':
      # go to creation...
      from ZTUtils import make_query
      querystr = make_query(contentId=contentId, namespaceTags=namespaceTags, tags=tags, comment=comment,
                            versionStart=versionStart, versionStop=versionStop, implicit=implicit,
                            approved=approved,
                            returnTo=returnTo)
      context.REQUEST.RESPONSE.redirect('/create_lens?%s' % querystr)
      return "Need to create"
    else:
      lens = context.restrictedTraverse(lensPath)
      if context.portal_factory.isTemporary(lens):
          # make concrete...
          newid = getattr(lens, 'suggestId', lambda: None)() or lens.getId()
          lens = context.portal_factory.doCreate(lens, newid)

    tags = tags.split()
    entry = getattr(lens, contentId, None)
    made = False
    if entry is None:
        lens.invokeFactory(id=contentId, type_name="SelectedContent")
Пример #59
0
##parameters=provider, action_path, **kw
##
from ZTUtils import make_query
from Products.CMFCore.utils import getToolByName

utool = getToolByName(script, 'portal_url')
ptool = getToolByName(script, 'portal_properties')
default_charset = ptool.getProperty('default_charset', None)
portal_url = utool()

try:
    target = provider.getActionInfo(action_path)['url']
except ValueError:
    target = portal_url

message = context.REQUEST.other.get('portal_status_message', '')
if message:
    if isinstance(message, unicode):
        message = message.encode(default_charset)
    kw['portal_status_message'] = message
for k, v in kw.items():
    if not v:
        del kw[k]

query = kw and ('?%s' % make_query(kw)) or ''
context.REQUEST.RESPONSE.redirect('%s%s' % (target, query))

return True
Пример #60
0
 def passive(self, request):
     session = request.SESSION
     if session.get(self.session_auth_key, False):
         session.set(self.session_lock_key, False)
         return {'login': session[self.session_login_key], 'ssiauth': True}
     creds = {}
     config = self._saml2_config()
     scl = Saml2Client(config)
     entityid = config.metadata.keys()[0]
     sp_url = self.saml2_sp_url
     actual_url = request.get("ACTUAL_URL", '')
     if not actual_url.startswith(sp_url):
         # the request was made from within a context we cannot handle
         return None
     actual_url_with_query = '%s?%s' % (actual_url, make_query(
         request.form)) if request.get(
             'REQUEST_METHOD') == 'GET' else actual_url
     # Initiate challenge
     if 'SAMLResponse' not in request.form and not session.get(
             self.session_lock_key, False):
         session.set(self.session_lock_key, True)
         logger.info('ACTUAL_URL: %s' % actual_url)
         (sid, result) = scl.authenticate(
             entityid,
             binding=BINDING_HTTP_REDIRECT,
             is_passive='true',
             requested_authn_context=self._authn_context(),
             service_url_binding=self.saml2_service_url_binding,
         )
         #session.set(self.session_sessid, {sid:''})
         session.set(self.session_storedurl_key, actual_url_with_query)
         headers = dict(result['headers'])
         for k, v in headers.items():
             request.response.setHeader(k, v)
         request.response.redirect(headers['Location'], lock=1)
     # Idp response - protocol binding POST
     if 'SAMLResponse' in request.form and actual_url.strip(
             '/') == sp_url.strip('/'):
         post_env = request.environ.copy()
         post_env['QUERY_STRING'] = ''
         request.stdin.seek(0)
         post = cgi.FieldStorage(
             fp=StringIO(request.stdin.read()),
             environ=post_env,
             keep_blank_values=True,
         )
         storedurl = session.get(self.session_storedurl_key,
                                 actual_url_with_query)
         if session.has_key(self.session_storedurl_key):
             session.delete(self.session_storedurl_key)
         request.response.redirect(storedurl)
         try:
             sessinfo = scl.parse_authn_request_response(
                 post['SAMLResponse'].value, BINDING_HTTP_POST,
                 session.get(self.session_sessid, {}))
         except:
             session.set(self.session_auth_key, False)
             # Saml2 auth failed. Do not ask again.
             return None
         creds = self._setup_local_session(session, scl, sessinfo)
     elif 'SAMLart' in request.form:
         storedurl = session.get(self.session_storedurl_key,
                                 actual_url_with_query)
         if session.has_key(self.session_storedurl_key):
             session.delete(self.session_storedurl_key)
         request.response.redirect(storedurl)
         r = scl.artifact2message(request.form.pop('SAMLart'), 'idpsso')
         logger.info(r.text)
         if r.status_code == 200:
             try:
                 response = scl.parse_artifact_resolve_response(r.text)
                 response.attribute_converters = scl.config.attribute_converters
                 response.assertion = response.assertion[0]
                 response.ava = get_identity(response)
                 creds = self._setup_local_session(session, scl, response)
             except:
                 session.set(self.session_auth_key, False)
                 # Saml2 auth failed. Do not ask again.
                 return None
     return creds