Esempio n. 1
0
    def getCriterionList(self, **kw):
        """
      Returns the list of criteria which are defined by the Predicate.

      Each criterion is returned in a TempBase instance intended to be
      displayed in a ListBox.

      XXX - It would be better to return criteria in a Criterion class
            instance
    """
        # We do not create PersistentMappings first time we *see* Predicate_view.
        # Instead, we create them first time we modify Predicate document.
        if not self.getCriterionPropertyList():
            return []
        if getattr(aq_base(self), "_identity_criterion", None) is None:
            self._identity_criterion = PersistentMapping()
            self._range_criterion = PersistentMapping()
        criterion_dict = {}
        for p in self.getCriterionPropertyList():
            criterion_dict[p] = newTempBase(self, "new_%s" % p)
            criterion_dict[p].identity = self._identity_criterion.get(p, None)
            criterion_dict[p].uid = "new_%s" % p
            criterion_dict[p].property = p
            criterion_dict[p].min = self._range_criterion.get(p, (None, None))[0]
            criterion_dict[p].max = self._range_criterion.get(p, (None, None))[1]
        criterion_list = criterion_dict.values()
        criterion_list.sort()
        return criterion_list
Esempio n. 2
0
def parseTutorial(text):
  from Products.ERP5Type.Document import newTempBase
  from lxml import etree
  parser = etree.HTMLParser(remove_comments=True)
  parser.feed(text)
  root = parser.close()
  table_list = root.xpath('//table[@id="SELENIUM-TEST"]')
  table = table_list[0]

  listbox = []

  i = 0
  # Insert only the content of tbody
  for table in table_list:
    listbox.append(newTempBase(context.getPortalObject(),
                               '',
                               title = "Tested Chapter " + str(i),
                               tag   = 'h1'))
    if len(table) > 0:
      for row in table[-1]:
        if(row.tag.lower() == 'tr'):
          listbox.append(newTempBase(context.getPortalObject(),
                               '',
                               title = row[0][0].text,
                               tag   = 'tr',
                               arg0  = row[0][1].text,
                               arg1  = row[0][2].text))
        else:
          listbox.append(newTempBase(context.getPortalObject(),
                               '',
                               title = row[0][0].text,
                               tag   = 'tr',
                               arg0  = row[0][1].text,
                               arg1  = row[0][2].text))
          

  stack = [html[1]]
  # Let's display everything in the test by removing the style attributes (they're not supposed to have any style attributes at all during the tests)
  while stack:
    element = stack.pop()
    if element.attrib.has_key('style'):
      del element.attrib['style']
    for child in element:
      stack.append(child)
  
  return dict(title = title, text = lxml.html.tostring(html))
Esempio n. 3
0
def createInputLine():
  global portal_object, new_id, l
  new_id += 1
  int_len = 3
  o = newTempBase( portal_object
                 , str(new_id)
                 , uid ='new_%s' % zfill(new_id, int_len)
                 )
  l.append(o)
def generate_error(listbox_line, column_title, error_message):
  global error_value
  global field_error_dict
  # Generate an error which is displayed by the listbox
  error_id = 'listbox_%s_new_%s' % (column_title,\
                                    listbox_line['listbox_key'])
  error = newTempBase(context, error_id)
  error.edit(error_text=error_message)
  field_error_dict[error_id] = error
  error_value = 1
def addLineListByType(id_list, destination_portal_type, line_list):
  for component_id in id_list:
    if getattr(component_tool, component_id, None) is not None:
      continue

    line = newTempBase(context,
                       'tmp_migrate_%s_%s' % (destination_portal_type, component_id),
                       uid=component_id,
                       name=component_id,
                       destination_portal_type=destination_portal_type)

    line_list.append(line)
def report(field_type, message, mapping=None, field_category='', level=None):
  if level and level not in displayed_report:
    return
  detailed_report_append(newTempBase(
    folder=context,
    id='item',
    field_type=field_type,
    field_category=field_category,
    field_message=translateString(
      message,
      mapping=mapping,
    ),
  ))
def createInputLine(d_message):
  global portal_object, new_id, l
  new_id += 1
  int_len = 3
  
  o = newTempBase( portal_object
                 , str(new_id)
                 , uid ='new_%s' % zfill(new_id, int_len)
                 ,  message = str(d_message.getTranslatedMessage())
                 ,  tested_property_id = d_message.getProperty('tested_property')
                 ,  object_title =  d_message.getObject().getTranslatedTitle()
                 ,  prevision_value = d_message.getProperty('prevision_value')
                 ,  decision_value = d_message.getProperty('decision_value')
                 , solver_script_list = d_message.getProperty('solver_script_list'))
  
  l.append(o)
def createTempBase(nr, row):
  def getElementFromArray(array, index):
    return array[index]

  def getElementFromScalar(scalar, index=None):
    return scalar

  column_list = [col for col in context.DataArray_getArrayColumnList() if col[0] != 'index']
  column_iterator = enumerate(column_list)
  if len(column_list) == 1:
    getElement = getElementFromScalar
  else:
    getElement = getElementFromArray
  return newTempBase(context.getPortalObject(),
                     str(id(row)),
                     index = nr,
                     **{col[0]: str(getElement(row, i)) for i, col in column_iterator})
Esempio n. 9
0
  def getCriterionList(self, **kw):
    """
      Returns the list of criteria which are defined by the Predicate.

      Each criterion is returned in a TempBase instance intended to be
      displayed in a ListBox.

      XXX - It would be better to return criteria in a Criterion class
            instance
    """
    if getattr(aq_base(self), '_identity_criterion', None) is None:
      self._identity_criterion = PersistentMapping()
      self._range_criterion = PersistentMapping()
    criterion_dict = {}
    for p in self.getCriterionPropertyList():
      criterion_dict[p] = newTempBase(self, 'new_%s' % p)
      criterion_dict[p].identity = self._identity_criterion.get(p, None)
      criterion_dict[p].uid = 'new_%s' % p
      criterion_dict[p].property = p
      criterion_dict[p].min = self._range_criterion.get(p, (None, None))[0]
      criterion_dict[p].max = self._range_criterion.get(p, (None, None))[1]
    criterion_list = criterion_dict.values()
    criterion_list.sort()
    return criterion_list
    else: # type == 'action'
      wf_item_path = '%s/transitions/%s_actbox_name' % (wf_item.aq_parent.aq_parent.id, wf_item.id)
      wf_item_title = wf_item.actbox_name
    wf_item_description = wf_item.description

    if type == 'transition' and wf_item_path.endswith('_action'):
      if len(term_list) == 1 and \
          term_list[0].getTitle() + ' Action' == wf_item_title and \
          term_list[0].getDescription() == wf_item_description:
        continue
    else:
      if len(term_list) == 1 and \
          term_list[0].getTitle() == wf_item_title and \
          term_list[0].getDescription() == wf_item_description:
        continue

    line = newTempBase(context, 'tmp_glossary_wf_item_%s' %  c)
    line.edit(wf_item_path=wf_item_path,
              wf_item_type=type,
              wf_item_title=wf_item_title,
              wf_item_edit_url = "%s/manage_properties" % wf_item.absolute_url(),
              wf_item_description = wf_item_description,
              reference=reference,
              term_list=term_list
              )
    line.setUid(wf_item_path)
    line_list.append(line)

line_list.sort(key=lambda x:x.wf_item_path)
return line_list
)
max_authentication_failures = portal_preferences.getPreferredMaxAuthenticationFailure(
)
check_time = now - check_duration * one_second

kw = {
    'portal_type': 'Authentication Event',
    'creation_date': Query(creation_date=check_time, range='min'),
    'validation_state': 'confirmed'
}
failure_list = portal.portal_catalog(**kw)
for failure in failure_list:
    login = failure.getDestinationValue()
    if login not in all_blocked_user_login_dict.keys():
        all_blocked_user_login_dict[login] = []
    all_blocked_user_login_dict[login].append(failure)

# leave only ones that are blocked:
for login, failure_list in all_blocked_user_login_dict.items():
    if len(failure_list) >= max_authentication_failures:
        person = login.getParentValue()
        blocked_user_login_list.append(
            newTempBase(
                portal, person.getTitle(), **{
                    'title': person.getTitle(),
                    'count': len(failure_list),
                    'reference': login.getReference(),
                    'url': login.absolute_url()
                }))
return blocked_user_login_list
Esempio n. 12
0
from Products.ERP5Type.Document import newTempBase
from Products.ERP5Type.Utils import sortValueList
result = [
    newTempBase(context, '_', uid="%u.%s" % (i, x['revision']), **x)
    for i, x in enumerate(context.getVcsTool().log(added))
]
return sortValueList(result, **kw)
  prevision_value = divergence.getProperty('prevision_value')
  prevision_title = divergence.getProperty('prevision_title', prevision_value)
  object_relative_url = divergence.getProperty('object_relative_url')
  simulation_movement_url = divergence.getProperty('simulation_movement').getRelativeUrl()
  object = portal_object.restrictedTraverse(object_relative_url)
  if decision_value not in value_list:
    candidate_list.append((decision_title, object_relative_url))
    value_list.append(decision_value)
  if decision_title not in decision_title_list:
    decision_title_list.append(decision_title)
  if prevision_value not in value_list:
    candidate_list.append((prevision_title, simulation_movement_url))
    value_list.append(prevision_value)
  if prevision_title not in prevision_title_list:
    prevision_title_list.append(prevision_title)
  candidate_dict[prop] = [divergence.getTranslatedMessage(), candidate_list, value_list, decision_title_list, prevision_title_list]

for prop, candidate_list in candidate_dict.items():
  uid = 'new_%s' % prop
  object = context

  o = newTempBase(context.getParentValue(), context.getId(), uid, uid=uid,
                  message=candidate_list[0],
                  object_title=object.getTranslatedTitle(),
                  decision_title=', '.join([str(x) for x in candidate_list[3]]),
                  prevision_title=', '.join([str(x) for x in candidate_list[4]]),
                  candidate_list=[(context.Base_translateString('Do nothing'), 'ignore')]+candidate_list[1])
  l.append(o)

return l
Esempio n. 14
0
          tmp_dict['credit'] = - total_price
      else:
        if total_price < 0:
          tmp_dict['debit'] = total_price
        elif total_price >= 0:
          tmp_dict['credit'] = - total_price

    description = delivery.getDescription()
    if description is None:
      description = ''
    tmp_dict['description'] = description
    tmp_dict['start_date'] = inventory.date
    tmp_dict['module_title'] = delivery.getParentValue().getTranslatedTitle()

    # Common to bank account
    acc_dict = inv_account_dict[inventory.payment_uid]
    acc_dict['transaction_list'].append(newTempBase(account, "new_%03i" % i, **tmp_dict))
    i += 1

def sort_date(a,b):
#   result = cmp(a.account_reference,b.account_reference)
#   if result == 0:
  return cmp(a.start_date,b.start_date)
#   return result

for act_info in inv_account_dict.values():
  act_info['transaction_list'].sort(sort_date)
  

return inv_account_dict.values()
Esempio n. 15
0
"""Returns a list of temp base objects"""
from Products.ERP5Type.Document import newTempBase
portal_object = context.getPortalObject()
return [newTempBase(portal_object, str(x), a=x, b=x) for x in xrange(10)]
from erp5.component.module.SubversionClient import SubversionSSLTrustError
from Products.ERP5Type.Document import newTempBase

portal = context.getPortalObject()

# For now we will work only under portal_skins
folder_id = context.getParentValue().getId(
)  # replace aq_parent by getParentValue
# once portal_skins is erp5 object

history_list = []
business_template = None
for bt in portal.portal_templates.contentValues():
    if bt.getInstallationState() != 'installed':
        continue
    if folder_id in bt.getTemplateSkinIdList():
        business_template = bt.getObject()

if business_template is not None:
    repository_path = '%s/SkinTemplateItem/portal_skins/%s/%s.xml' % (
        business_template.getTitle(), folder_id, context.getId())

    vcs_tool = business_template.getVcsTool()
    log_list = vcs_tool.log(repository_path, business_template)
    for log_dict in log_list:
        log_dict['message'] = log_dict['message'].replace('\n', '<br/>')
        temp_object = newTempBase(folder=context, id='1', **log_dict)
        history_list.append(temp_object)

return history_list
Esempio n. 17
0
"""Returns a list of temp base objects"""
from Products.ERP5Type.Document import newTempBase

portal_object = context.getPortalObject()
return [newTempBase(portal_object, str(x), a=x, b=x) for x in xrange(10)]
Esempio n. 18
0
portal_object = context.getPortalObject()
num = 0
result_listbox = []

if active_process_path is None:
    #return []
    active_process_path = context.REQUEST.get('active_process')

active_process_value = context.getPortalObject().restrictedTraverse(
    active_process_path)
result_list = [[x.method_id, x.result]
               for x in active_process_value.getResultList()]

result_list.sort()

for [method_id, result] in result_list:
    safe_id = context.Base_getSafeIdFromString('result %s' % num)
    num += 1
    int_len = 7
    if not result['success']:
        o = newTempBase(portal_object, safe_id)
        o.setUid('new_%s' %
                 zfill(num, int_len))  # XXX There is a security issue here
        o.edit(uid='new_%s' %
               zfill(num, int_len))  # XXX There is a security issue here
        o.edit(**result['object'])
        result_listbox.append(o)

return result_listbox
all_blocked_user_login_dict = {}

now = DateTime()
one_second = 1/24.0/60.0/60.0
check_duration = portal_preferences.getPreferredAuthenticationFailureCheckDuration()
max_authentication_failures = portal_preferences.getPreferredMaxAuthenticationFailure()
check_time = now - check_duration*one_second

kw = {'portal_type': 'Authentication Event',
      'creation_date': Query(creation_date = check_time,
                             range='min'),
      'validation_state' : 'confirmed'}
failure_list = portal.portal_catalog(**kw)
for failure in failure_list:
  login = failure.getDestinationValue()
  if login not in all_blocked_user_login_dict.keys():
    all_blocked_user_login_dict[login] = []
  all_blocked_user_login_dict[login].append(failure)

# leave only ones that are blocked:
for login, failure_list in all_blocked_user_login_dict.items():
  if len(failure_list) >= max_authentication_failures:
    person = login.getParentValue()
    blocked_user_login_list.append(newTempBase(portal,
                                               person.getTitle(),
                                               **{'title': person.getTitle(),
                                                  'count':len(failure_list),
                                                  'reference': login.getReference(),
                                                  'url': login.absolute_url()}))
return blocked_user_login_list
    if decision_title not in decision_title_list:
        decision_title_list.append(decision_title)
    if prevision_value not in value_list:
        candidate_list.append((prevision_title, simulation_movement_url))
        value_list.append(prevision_value)
    if prevision_title not in prevision_title_list:
        prevision_title_list.append(prevision_title)
    candidate_dict[prop] = [
        divergence.getTranslatedMessage(), candidate_list, value_list,
        decision_title_list, prevision_title_list
    ]

for prop, candidate_list in candidate_dict.items():
    uid = 'new_%s' % prop
    object = context

    o = newTempBase(
        context.getParentValue(),
        context.getId(),
        uid,
        uid=uid,
        message=candidate_list[0],
        object_title=object.getTranslatedTitle(),
        decision_title=', '.join([str(x) for x in candidate_list[3]]),
        prevision_title=', '.join([str(x) for x in candidate_list[4]]),
        candidate_list=[(context.Base_translateString('Do nothing'), 'ignore')
                        ] + candidate_list[1])
    l.append(o)

return l
Esempio n. 21
0
    workflow_item_list = portal_workflow.getInfoFor(ob=context,
                                                    name='history',
                                                    wf_id=workflow_id)
    if workflow_item_list != []:
        break

wf_states = portal_workflow[workflow_id].states
wf_transitions = portal_workflow[workflow_id].transitions

next_serial = None
previous_obj = None

for workflow_item in workflow_item_list:
    same_action = 0
    # XXX removing str method generate a strange bug
    o = newTempBase(portal_object, str(i))
    i += 1
    for key, value in workflow_item.items():
        # XXX Compatibility
        for compatibility_name in ['building_', 'installation_']:
            if key.startswith(compatibility_name):
                # Display the workflow state in the state columns
                key = key[len(compatibility_name):]
        if key.endswith('state'):
            key = 'state'
            if display:
                value = wf_states.get(value, marker) and wf_states[value].title
            else:
                value = wf_states.get(value, marker) and wf_states[value].id
        if key == 'action':
            action_name = value
Esempio n. 22
0
]
no_backup_dict = {}
for k in no_backup_list:
    no_backup_dict[k] = 1

install_title = Base_translateString("Install")
upgrade_title = Base_translateString("Upgrade")
backup_title = Base_translateString("Backup And Upgrade")
remove_title = Base_translateString("Remove")
save_and_remove_title = Base_translateString("Backup And Remove")

i = 0
object_list = []
for object_id in keys:
    object_state, object_class = modified_object_list[object_id]
    line = newTempBase(context, "tmp_install_%s" % (str(i)))
    if object_state == "New":
        choice_item_list = [[install_title, "install"]]
    elif object_state.startswith("Modified"):
        if object_class in no_backup_dict:
            choice_item_list = [[upgrade_title, "install"]]
        else:
            choice_item_list = [[backup_title, "backup"]]
    elif object_state.startswith("Removed"):
        if object_class in no_backup_dict:
            choice_item_list = [[remove_title, "remove"]]
        else:
            choice_item_list = [[save_and_remove_title, "save_and_remove"]]
    else:
        choice_item_list = [[install_title, "install"]]
Esempio n. 23
0
def doValidation(person, password):
    # raise so Formulator shows proper message
    result_code_list = person.Person_analyzePassword(password)
    if result_code_list != []:
        translateString = context.Base_translateString
        message = ' '.join(
            [translateString(message_dict[x]) for x in result_code_list])
        raise ValidationError('external_validator_failed',
                              context,
                              error_text=message)
    return 1


user_login = request.get('field_user_login', None)
# find Person object (or authenticated member) and validate it on it (password recovered for an existing account)
person = context.ERP5Site_getAuthenticatedMemberPersonValue(user_login)
if person is not None:
    return doValidation(person, password)

# use a temp object (new account created)
first_name = request.get('field_your_first_name', None)
last_name = request.get('field_your_last_name', None)
kw = {
    'title': '%s %s' % (first_name, last_name),
    'first_name': first_name,
    'last_name': last_name
}
person = newTempBase(portal, kw['title'], **kw)

return doValidation(person, password)
Esempio n. 24
0
    def test_03_PasswordValidity(self):
        """
      Test validity of a password.
    """
        portal = self.getPortal()
        request = self.app.REQUEST

        regular_expression_list = [
            '([a-z]+)',  # english lowercase
            '([A-Z]+)',  # english uppercase
            '([0-9]+)',  # numerals (0-9)
            '([\\\\$\\\\!\\\\#\\\\%]+)'  # (!, $, #, %)
        ]

        self.assertTrue(
            portal.portal_preferences.isAuthenticationPolicyEnabled())

        person = portal.person_module.newContent(portal_type='Person',
                                                 reference='test-03',
                                                 password='******',
                                                 first_name='First',
                                                 last_name='Last')
        preference = portal.portal_catalog.getResultValue(
            portal_type='System Preference',
            title='Authentication',
        )
        self.tic()

        # by default an empty password if nothing set in preferences is OK
        self.assertTrue(person.isPasswordValid(''))

        # Not long enough passwords used
        self._cleanUpPerson(person)
        preference.setPreferredMinPasswordLength(8)
        preference.setPreferredNumberOfLastPasswordToCheck(0)
        self.tic()
        self._clearCache()

        self.assertEqual([-1], person.analyzePassword(''))
        self.assertEqual([-1], person.analyzePassword('1234567'))
        self.assertTrue(person.isPasswordValid('12345678'))

        # not changed in last x days
        self._cleanUpPerson(person)
        preference.setPreferredMinPasswordLifetimeDuration(24)
        preference.setPreferredNumberOfLastPasswordToCheck(3)
        self.tic()
        self._clearCache()

        self.assertTrue(person.isPasswordValid('12345678'))
        person.setPassword('12345678')
        self.tic()

        # if we try to change now we should fail with any password
        self.assertSameSet([-3], person.analyzePassword('87654321'))
        self.assertSameSet(
            [-1, -3], person.analyzePassword('short'))  # multiple failures
        self.assertFalse(person.isPasswordValid('short'))  # multiple failures
        self.assertRaises(ValueError, person.setPassword, '87654321')

        preference.setPreferredMinPasswordLifetimeDuration(
            0)  # remove restriction
        self.tic()
        self._clearCache()
        self.assertTrue(
            person.isPasswordValid('87654321'))  # it's OK to change

        # password not used in previous X passwords
        preference.setPreferredMinPasswordLength(None)  # disable for now
        self._cleanUpPerson(person)
        self._clearCache()
        self.tic()

        person.setPassword('12345678-new')
        self.tic()

        self.assertSameSet(
            [-4], person.analyzePassword('12345678-new')
        )  # if we try to change now we should fail with this EXACT password
        self.assertRaises(ValueError, person.setPassword, '12345678-new')
        self.assertTrue(person.isPasswordValid(
            '12345678_'))  # it's OK with another one not used yet
        for password in ['a', 'b', 'c', 'd', 'e', 'f']:
            # this sleep is not so beautiful, but mysql datetime columns has a
            # precision of one second only, and we use creation_date to order
            # "Password Event" objects. So without this sleep, the test is
            # failing randomly.
            time.sleep(1)
            person.setPassword(password)
            self.tic()
        self._clearCache()
        self.tic()

        self.assertTrue(person.isPasswordValid('12345678-new'))
        self.assertTrue(person.isPasswordValid('a'))
        self.assertTrue(person.isPasswordValid('b'))
        self.assertTrue(person.isPasswordValid('c'))
        # only last 3 (including current one are invalid)
        self.assertSameSet([-4], person.analyzePassword('d'))
        self.assertSameSet([-4], person.analyzePassword('e'))
        self.assertSameSet([-4], person.analyzePassword('f'))

        # if we remove restricted then all password are usable
        preference.setPreferredNumberOfLastPasswordToCheck(None)
        self._clearCache()
        self.tic()

        self.assertTrue(person.isPasswordValid('d'))
        self.assertTrue(person.isPasswordValid('e'))
        self.assertTrue(person.isPasswordValid('f'))

        # if we set only last password to check
        preference.setPreferredNumberOfLastPasswordToCheck(1)
        self._clearCache()
        self.tic()
        self.assertTrue(person.isPasswordValid('c'))
        self.assertTrue(person.isPasswordValid('d'))
        self.assertTrue(person.isPasswordValid('e'))
        self.assertSameSet([-4], person.analyzePassword('f'))

        preference.setPreferredRegularExpressionGroupList(
            regular_expression_list)
        preference.setPreferredMinPasswordLength(7)
        preference.setPreferredNumberOfLastPasswordToCheck(None)
        self._cleanUpPerson(person)
        self._clearCache()
        self.tic()

        four_group_password_list = [
            'abAB#12', 'ghTK61%', '5Tyui1%', 'Y22GJ5iu#'
        ]
        three_group_password_list = [
            'abAB123 ', 'AB123ab', 'XY123yz', 'dufgQ7xL', 'NAfft8h5',
            '0LcAiWtT'
        ]
        two_group_password_list = [
            'XY12345', 'yuiffg1', 'abcdef##', '##$aabce'
        ]
        one_group_password_list = [
            '1234567', 'ABZSDFE', '##!!$$%', 'abzdeffgg'
        ]

        # min 4 out of all groups
        preference.setPreferredMinRegularExpressionGroupNumber(4)
        self._clearCache()
        self.tic()
        for password in four_group_password_list:
            self.assertTrue(person.isPasswordValid(password))
        for password in three_group_password_list + two_group_password_list + one_group_password_list:
            self.assertSameSet([-2], person.analyzePassword(password))

        # min 3 out of all groups
        preference.setPreferredMinRegularExpressionGroupNumber(3)
        self._clearCache()
        self._cleanUpPerson(person)
        self.tic()
        for password in four_group_password_list + three_group_password_list:
            self.assertTrue(person.isPasswordValid(password))
        for password in two_group_password_list + one_group_password_list:
            self.assertSameSet([-2], person.analyzePassword(password))

        # min 2 out of all groups
        preference.setPreferredMinRegularExpressionGroupNumber(2)
        self._clearCache()
        self.tic()
        for password in four_group_password_list + three_group_password_list + two_group_password_list:
            self.assertTrue(person.isPasswordValid(password))
        for password in one_group_password_list:
            self.assertSameSet([-2], person.analyzePassword(password))

        # min 1 out of all groups
        preference.setPreferredMinRegularExpressionGroupNumber(1)
        self._clearCache()
        self.tic()
        for password in four_group_password_list + three_group_password_list + two_group_password_list + one_group_password_list:
            self.assertTrue(person.isPasswordValid(password))

        # not contain the full name of the user
        preference.setPrefferedForceUsernameCheckInPassword(1)
        self._clearCache()
        self.tic()
        self.assertSameSet([-5],
                           person.analyzePassword('abAB#12_%s' %
                                                  person.getFirstName()))
        self.assertSameSet([-5],
                           person.analyzePassword('abAB#12_%s' %
                                                  person.getLastName()))
        preference.setPrefferedForceUsernameCheckInPassword(0)
        self._clearCache()
        self.tic()
        self.assertTrue(
            person.isPasswordValid('abAB#12_%s' % person.getFirstName()))
        self.assertTrue(
            person.isPasswordValid('abAB#12_%s' % person.getLastName()))

        # check on temp objects just passworrd length( i.e. simulating a new user account creation)
        first_name = 'John'
        last_name = 'Doh'
        kw = {
            'title': '%s %s' % (first_name, last_name),
            'first_name': first_name,
            'last_name': last_name
        }
        temp_person = newTempBase(portal, kw['title'], **kw)

        preference.setPreferredMinPasswordLength(10)
        preference.setPreferredRegularExpressionGroupList(None)
        self._clearCache()
        self.tic()
        # in this case which is basically used in new account creation only length of password matters
        self.assertSameSet([-1],
                           temp_person.Person_analyzePassword('onlyNine1'))
        self.assertSameSet([],
                           temp_person.Person_analyzePassword('longEnough1'))

        # make sure re check works on temp as well ( i.e. min 3 out of all groups)
        preference.setPreferredRegularExpressionGroupList(
            regular_expression_list)
        preference.setPreferredMinPasswordLength(7)
        preference.setPreferredMinRegularExpressionGroupNumber(3)
        self._clearCache()
        self.tic()
        for password in four_group_password_list + three_group_password_list:
            self.assertSameSet([],
                               temp_person.Person_analyzePassword(password))
        for password in two_group_password_list + one_group_password_list:
            self.assertSameSet([-2],
                               temp_person.Person_analyzePassword(password))

        # make sure peron's check on username works on temp as well (i.e. not contain the full name of the user)
        preference.setPrefferedForceUsernameCheckInPassword(1)
        self._clearCache()
        self.tic()
        self.assertSameSet([-5],
                           temp_person.Person_analyzePassword('abAB#12_%s' %
                                                              first_name))
        self.assertSameSet([-5],
                           temp_person.Person_analyzePassword('abAB#12_%s' %
                                                              last_name))

        preference.setPrefferedForceUsernameCheckInPassword(0)
        self._clearCache()
        self.tic()
        self.assertSameSet([],
                           temp_person.Person_analyzePassword('abAB#12_%s' %
                                                              first_name))
        self.assertSameSet([],
                           temp_person.Person_analyzePassword('abAB#12_%s' %
                                                              last_name))

        # check Base_isPasswordValid is able to work in Anonymous User fashion
        # but with already create Person object (i.e. recover password case)
        preference.setPrefferedForceUsernameCheckInPassword(1)
        preference.setPreferredMinPasswordLength(7)
        preference.setPreferredMinRegularExpressionGroupNumber(3)
        preference.setPreferredNumberOfLastPasswordToCheck(1)
        self._clearCache()
        self.tic()

        person.setPassword('used_ALREADY_1234')
        self._clearCache()
        self.tic()

        # emulate Anonymous User
        self.logout()
        request.set('field_user_login', person.getReference())
        self.assertRaises(ValidationError, portal.Base_isPasswordValid,
                          'abAB#12_%s' % person.getFirstName(),
                          request)  # contains name
        self.assertRaises(ValidationError, portal.Base_isPasswordValid,
                          'abAB#12_%s' % person.getLastName(),
                          request)  # contains name
        self.assertRaises(ValidationError, portal.Base_isPasswordValid,
                          'abAB#1', request)  # too short
        self.assertRaises(ValidationError, portal.Base_isPasswordValid,
                          'abABCDEFG', request)  # too few groups
        self.assertRaises(ValidationError, portal.Base_isPasswordValid,
                          'used_ALREADY_1234', request)  # already used
        self.assertEqual(1, portal.Base_isPasswordValid('abAB#12_', request))
        self.assertEqual(
            1, portal.Base_isPasswordValid('not_used_ALREADY_1234', request))
Esempio n. 25
0
default_link_url ='setLanePath?form_id=%s&list_selection_name=%s' %(
                                 form_id, selection_name)

# Define date format using user Preferences
date_order = portal.portal_preferences.getPreferredDateOrder()
date_format = dict(ymd='%Y/%m/%d',
                   dmy='%d/%m/%Y',
                   mdy='%m/%d/%Y').get(date_order, '%Y/%m/%d')

category_list = []
if depth == 0:
  # This case show Seven days
  while current_date < bound_stop:
    # Create one Temp Object
    o = newTempBase(portal, id='week', uid='new_%s' % zfill('week',4))
     # Setting Axis Dates start and stop
    o.setProperty('start',current_date)
    o.setProperty('stop', current_date+1)
    o.setProperty('relative_position', int(current_date))

    # Seting delimiter 
    if current_date.day() == 1:
      o.setProperty('delimiter_type', 2)
    elif current_date.day() == 15:
      o.setProperty('delimiter_type', 1)
    else:
      o.setProperty('delimiter_type', 0)

    title = translateString('${day_name} ${date}',
                            mapping=dict(day_name=translateString(current_date.Day()),
from Products.ERP5Type.Document import newTempBase
from Products.ERP5Type.Utils import sortValueList

result = [newTempBase(context, '_', uid=path)
          for path in context.getVcsTool().getConflictedFileList()]
return sortValueList(result, **kw)
Esempio n. 27
0
                                    # Found some delegated list
                                    modified_object_dict[field_path] = (
                                        '0_check_delegated_value', template_id)
                    else:
                        # Do not force proxification of field.
                        # The nice developper probably have a good reason not to do it.
                        modified_object_dict[
                            field_path] = '0_keep_non_proxy_field'

for field_path, proxy_field_list in field_library_dict.items():
    if not proxy_field_list:
        modified_object_dict[field_path] = '0_unused_proxy_field'

i = 0
for key, value in modified_object_dict.items():
    line = newTempBase(context, 'tmp_install_%s' % (str(i)))
    if isinstance(value, tuple):
        value, template_id = value
    else:
        template_id = None
    if value.startswith('0_'):
        choice = []
    else:
        choice = [value]
    line.edit(
        object_id=key,
        template_id=template_id,
        choice=choice,
        choice_item_list=[[action_title_dict[value], value]],
    )
    line.setUid('new_%s' % key)
     previous_total_debit  = getInventoryAssetPrice(omit_asset_decrease=True,
            from_date=period_start_date,
            to_date=initial_balance_from_date,
            **get_inventory_kw) + max(period_openning_balance, 0)
     previous_total_credit = getInventoryAssetPrice(omit_asset_increase=True,
            from_date=period_start_date,
            to_date=initial_balance_from_date,
            **get_inventory_kw) - max(-period_openning_balance, 0)
 
     if previous_total_credit != 0:
       previous_total_credit = - previous_total_credit
   
     # Show the previous balance if not empty
     if previous_total_credit != 0 or previous_total_debit != 0:
       net_balance = previous_total_debit - previous_total_credit
       previous_balance = newTempBase(portal, '_temp_accounting_transaction')
       previous_balance.edit(
           uid='new_000',
           date=initial_balance_from_date,
           simulation_state_title="",
           credit_price=previous_total_credit,
           debit_price=previous_total_debit,
           total_price=net_balance,
           credit=previous_total_credit,
           debit=previous_total_debit,
           total_quantity=net_balance,
           running_total_price=net_balance,
           is_previous_balance=True,
           Movement_getSpecificReference=u'%s' % translateString('Previous Balance'),
           Movement_getExplanationTitle=u'%s' % translateString('Previous Balance'),
           Movement_getExplanationTranslatedPortalType='',
Esempio n. 29
0
# If first_path and second_path exists, get their current revision from ZODB
if first_path not in (None, ''):
  first_object = portal.restrictedTraverse(first_path)
if second_path not in (None, ''):
  second_object = portal.restrictedTraverse(second_path)

# Try to get the objects from the serials.
if first_serial:
  if not first_object:
    first_object = context
  try:
    first_object = first_object.HistoricalRevisions[first_serial]
  except (ConflictError, Unauthorized):
    raise
  except Exception:
    return [newTempBase(portal, context.Base_translateString('Historical revisions are'
                        ' not available, maybe the database has been packed'))]

if second_serial:
  if second_serial == '0.0.0.0':
    # In case the second serial is 0.0.0.0, we should consider the second object as
    # the current version of context
    second_object = context
  else:
    if not second_object:
      second_object = context
    try:
      second_object = second_object.HistoricalRevisions[second_serial]
    except (ConflictError, Unauthorized):
      raise
    except Exception:
      return [newTempBase(portal, context.Base_translateString('Historical revisions are'
Esempio n. 30
0
from Products.ERP5VCS.SubversionClient import SubversionSSLTrustError
from Products.ERP5Type.Document import newTempBase

portal = context.getPortalObject()

# For now we will work only under portal_skins
folder_id = context.getParentValue().getId() # replace aq_parent by getParentValue
                                      # once portal_skins is erp5 object

history_list = []
business_template = None
for bt in portal.portal_templates.searchFolder(installation_state='installed'):
  # if installation_state not in catalog, we have to check manually
  if bt.getInstallationState() != 'installed':
    continue
  if folder_id in bt.getTemplateSkinIdList():
    business_template = bt.getObject()

if business_template is not None:
  repository_path = '%s/SkinTemplateItem/portal_skins/%s/%s.xml' % (
    business_template.getTitle(), folder_id, context.getId())

  vcs_tool = business_template.getVcsTool()
  log_list = vcs_tool.log(repository_path, business_template)
  for log_dict in log_list:
    log_dict['message'] = log_dict['message'].replace('\n', '<br/>')
    temp_object = newTempBase(folder=context, id='1', **log_dict)
    history_list.append(temp_object)

return history_list
result = []

if not getSecurityManager().getUser().has_permission('View History', context):
    raise Unauthorized()


def beautifyChange(change_dict):
    change_list = []
    for property_name, property_value in sorted(change_dict.items()):
        if isinstance(property_value, basestring):
            try:
                unicode(property_value, 'utf-8')
            except UnicodeDecodeError:
                property_value = '(binary)'
        change_list.append('%s:%s' % (property_name, property_value))
    return change_list


try:
    history_size = portal.portal_preferences.getPreferredHtmlStyleZodbHistorySize(
    )
except AttributeError:
    history_size = 50

for dict_ in context.Base_getZODBChangeHistoryList(context, size=history_size):
    tmp = newTempBase(portal, '')
    dict_['changes'] = beautifyChange(dict_.get('changes', {}))
    tmp.edit(**dict_)
    result.append(tmp)
return result
# FIXME: Here we do not want to sum all movement < 0, but sum the balances
#        of all nodes whose which have a < 0 balance...
opening_debit_balance = 0.0
opening_credit_balance = 0.0
closing_debit_balance = 0.0
closing_credit_balance = 0.0
if from_date not in (None, ''):
    opening_debit_balance = getInventory(at_date=from_date,
                                         omit_output=True,
                                         **get_inventory_kw)
    opening_credit_balance = -getInventory(
        at_date=from_date, omit_input=True, **get_inventory_kw)
closing_debit_balance = getInventory(at_date=at_date,
                                     omit_output=True,
                                     **get_inventory_kw)
closing_credit_balance = -getInventory(
    at_date=at_date, omit_input=True, **get_inventory_kw)

list_item = newTempBase(portal, 'xxx')
list_item.setUid('new_000')
list_item.edit(
    **{
        'total_opening_debit_balance': opening_debit_balance,
        'total_closing_debit_balance': closing_debit_balance,
        'total_opening_credit_balance': opening_credit_balance,
        'total_closing_credit_balance': closing_credit_balance
    })

return [list_item]
    return [i.getObject() for i in term_list]


line_list = []
c = 0
portal_type_list = context.GlossaryModule_getAvailablePortalTypeList()
for reference in portal_type_list:
    portal_type = context.getPortalObject().portal_types[reference]
    term_list = get_term_list(reference)
    # if not term_list:
    #  continue

    c += 1
    field_description = portal_type.description
    if len(term_list) == 1 and term_list[0].getDescription() == field_description:
        continue

    line = newTempBase(context, "tmp_glossary_field_%s" % c)
    line.edit(
        field_path=reference,
        field_edit_url="%s/manage_main" % portal_type.absolute_url(),
        field_description=field_description,
        reference=reference,
        term_list=term_list,
    )
    line.setUid(reference)
    line_list.append(line)

line_list.sort(key=lambda x: x.field_path)
return line_list
template_tool = context.getPortalObject().portal_templates

assert bt1.getBuildingState() == "built"
assert bt2.getBuildingState() == "built"

modified_object_list = bt2.preinstall(check_dependencies=0, compare_to=bt1)
keys = modified_object_list.keys()
#keys.sort() # XXX don't care ?
bt1_id = bt1.getId()
bt2_id = bt2.getId()
i = 0
object_list = []
for object_id in keys:
  object_state, object_class = modified_object_list[object_id]
  line = newTempBase(template_tool, 'tmp_install_%s' % str(i)) # template_tool or context?
  line.edit(object_id=object_id, object_state=object_state, object_class=object_class, bt1=bt1_id, bt2=bt2_id)
  line.setUid('new_%s' % object_id)
  if detailed and object_state == "Modified":
    try:
      line.edit(data=bt2.diffObject(line, compare_with=bt1_id))
    except ConflictError:
      raise
    except Exception as e:
      if raise_on_diff_error:
        raise
      line.edit(error=repr(e))
  object_list.append(line)
  i += 1
return object_list
Esempio n. 35
0
from Products.ERP5Type.Document import newTempBase
translateString = context.Base_translateString
portal_status_message = translateString(
    "%s created. You can now add your first chapter." % portal_type)

page = context.newContent(portal_type=portal_type, title=title)

session = context.ERP5RunMyDocs_acquireSession()
session['title'] = title
session['author'] = author
session['author_mail'] = author_mail
session['test_page_path'] = page.getPath()
session['listbox'] = [
    newTempBase(context.getPortalObject(),
                '',
                title=title,
                uid='0',
                int_index=0,
                image_id='',
                slide_type='Master',
                text_content=text_content,
                slide_content=slide_content,
                file=False,
                tested=False)
]

return context.Base_redirect(
    'TestPageModule_viewChapterCreationWizard',
    keep_items=dict(portal_status_message=portal_status_message))
            wf_item_path = '%s/transitions/%s_actbox_name' % (
                wf_item.aq_parent.aq_parent.id, wf_item.id)
            wf_item_title = wf_item.actbox_name
        wf_item_description = wf_item.description

        if type == 'transition' and wf_item_path.endswith('_action'):
            if len(term_list) == 1 and \
                term_list[0].getTitle() + ' Action' == wf_item_title and \
                term_list[0].getDescription() == wf_item_description:
                continue
        else:
            if len(term_list) == 1 and \
                term_list[0].getTitle() == wf_item_title and \
                term_list[0].getDescription() == wf_item_description:
                continue

        line = newTempBase(context, 'tmp_glossary_wf_item_%s' % c)
        line.edit(wf_item_path=wf_item_path,
                  wf_item_type=type,
                  wf_item_title=wf_item_title,
                  wf_item_edit_url="%s/manage_properties" %
                  wf_item.absolute_url(),
                  wf_item_description=wf_item_description,
                  reference=reference,
                  term_list=term_list)
        line.setUid(wf_item_path)
        line_list.append(line)

line_list.sort(key=lambda x: x.wf_item_path)
return line_list
Esempio n. 37
0

# Define date format using user Preferences
date_order = portal.portal_preferences.getPreferredDateOrder()
date_format = dict(ymd='%m/%d %H:00',
                   dmy='%d/%m %H:00',
                   mdy='%m/%d %H:00').get(date_order, '%m/%d %H:00')

category_list = []
if depth == 0:
  current_date = bound_start
 # This zoom will show one day divided in columns that represents 3 hours.
 # 0.125 means 3 hours in DateTime float format
  while current_date < bound_stop:
    # Create one Temp Object
    o = newTempBase(portal, id='year', uid='new_year')
    # Setting Axis Dates start and stop
    o.setProperty('start',current_date)
    o.setProperty('stop', current_date + 0.125)
    o.setProperty('relative_position', int(current_date))

    # Seting delimiter
    if current_date.hour() == 12:
      o.setProperty('delimiter_type', 1)
    else:
      o.setProperty('delimiter_type', 0)

    title = translateString('${day_name} ${date}',
               mapping=dict(day_name=translateString(current_date.Day()),
                            date=current_date.strftime(date_format)))
    o.setProperty('title', title)
            'tested_property') != 'price':
        continue
    decision_value = divergence.getProperty('decision_value')
    decision_title = divergence.getProperty('decision_title', decision_value)
    prevision_value = divergence.getProperty('prevision_value')
    prevision_title = divergence.getProperty('prevision_title',
                                             prevision_value)
    object_relative_url = divergence.getProperty('object_relative_url')
    simulation_movement_url = divergence.getProperty(
        'simulation_movement').getRelativeUrl()
    uid = 'new_%s&%s' % (simulation_movement_url,
                         divergence.getProperty('tested_property'))

    object = portal_object.restrictedTraverse(object_relative_url)
    o = newTempBase(object.getParentValue(),
                    object.getId(),
                    uid=uid,
                    message=str(divergence.getTranslatedMessage()),
                    object_portal_type=object.getTranslatedPortalType(),
                    object_title=object.getTranslatedTitle(),
                    prevision_title=prevision_title,
                    decision_title=decision_title,
                    candidate_list=[
                        (context.Base_translateString('Do nothing'), 'ignore'),
                        (decision_title, 'accept'),
                        (prevision_title, 'adopt'),
                    ])
    l.append(o)

return l
Esempio n. 39
0
context.REQUEST.set('rss_status', status)
if status < 0:
  # some error occured show message to user
  request.set('rss_title', context.Base_translateString(error_mapping_dict[status]))
  return []
else:
  # all good
  rss_title = results.get('title','')
  rss_logo = results.get('logo', None)
  if items is not None:
    rss_title = '%s (%s)' %(rss_title, len(items))
  if rss_logo not in ('', None):
    request.set('rss_logo', rss_logo)
  request.set('rss_link', results.get('link',None))
  request.set('rss_gadget_title', rss_title)

for result in items:
  md5_list.append(result['md5'])
  date = context.Base_getDiffBetweenDateAndNow(result.get('date',None))
  message = newTempBase(context, 'item')
  message.edit(field_title = result.get('title','No title'),
            field_date = date,
            field_content = result.get('content','No content'),
            field_img = result.get('img',''),
            field_others_links = result.get('other_links',''),
            field_link = result.get('link',''),
            field_md5 = result.get('md5',''))
  message_list.append(message)

return message_list
for divergence in divergence_list:
    if divergence.getCollectOrderGroup() != "cell":
        continue
    decision_value = divergence.getProperty("decision_value")
    decision_title = divergence.getProperty("decision_title", decision_value)
    prevision_value = divergence.getProperty("prevision_value")
    prevision_title = divergence.getProperty("prevision_title", prevision_value)
    object_relative_url = divergence.getProperty("object_relative_url")
    simulation_movement_url = divergence.getProperty("simulation_movement").getRelativeUrl()
    uid = "new_%s&%s" % (simulation_movement_url, divergence.getProperty("tested_property"))

    object = portal_object.restrictedTraverse(object_relative_url)
    o = newTempBase(
        object.getParentValue(),
        object.getId(),
        uid=uid,
        message=str(divergence.getTranslatedMessage()),
        object_title=object.getTranslatedTitle(),
        prevision_title=prevision_title,
        decision_title=decision_title,
        candidate_list=[
            (context.Base_translateString("Do nothing"), "ignore"),
            (decision_title, "accept"),
            (prevision_title, "adopt"),
        ],
    )
    l.append(o)

return l
Esempio n. 41
0
"""
  THis script returns a suitable slide list of PDF thumbnails
  for current form selection.
  It's to be used in a listbox.
"""
from Products.ERP5Type.Document import newTempBase

content_information = context.getContentInformation()
page_number = int(content_information.get('Pages', 0))
limit = kw.get('limit', (0, 0))
list_start = int(kw.get('list_start', 0))
list_lines = int(kw.get('list_lines', 0))
size = list_lines or limit[1]

list_end = list_start + size
page_list = range(page_number)

result = []
for i in page_list[list_start:list_end]:
    x = {
        'title': '%s' % i,
        'frame': '%s' % i
    }  # frame is used by listbox render field
    temp_object = newTempBase(context, x['title'], **x)
    result.append(temp_object)
return result
def addReportLine(error, category, message):
    report_line = newTempBase(context, 'item')
    report_line.edit(field_type=error,
                     field_category=category,
                     field_message=message)
    detailed_report_append(report_line)
Esempio n. 43
0
element_list = []
relative_url = context.getRelativeUrl()
counter = 0
if len(annotation_list) > 0 and annotation_list[0] != "":
    for annotation in annotation_list:
        annotation_item = annotation[1:-1].split("},{")
        if len(annotation_item) == 5:
            comment, locator, context_url, author, color = annotation_item
        else:
            comment = "Failed to process: %s" % annotation
            locator, context_url, author, color = "", "", "", ""
        element_list.append(
            newTempBase(context.getPortalObject(),
                        relative_url,
                        title=comment,
                        uid=str(counter),
                        int_index=0,
                        locator=locator,
                        context_url=context_url,
                        color=color,
                        author=author))
        counter += 1

for sorted_element in sort_on:
    # pylint:disable=cell-var-from-loop
    element_list = sorted(element_list,
                          key=lambda x: x.getProperty(sorted_element[0]),
                          reverse=sorted_element[1] == 'descending')

return element_list
    path = line['path'].replace('/%s/' %portal.getId(), '')
    result_set_dict_list.append({'uid': uid,
                                'object_portal_type': line['portal_type'],
                                'object_icon': portal_types[line['portal_type']].getIcon(),
                                'path': path,
                                'title': line['title'],
                                'text': getattr(line, 'text', ''),
                                'modification_date': line['modification_date'],
                                'reference': line['reference'],
                                'category_relative_url': line['category_relative_url'],
                                'owner': line['owner'],
                                'version': line['version'],
                                'language': line['language'],
                                'web_site': web_site.getRelativeUrl()})
  
  # one document can belong to n categories, we need show only one doc
  # and all sections it belongs to
  found_uids = []
  for line in result_set_dict_list:
    uid = line['uid']
    if uid not in found_uids:
      found_uids.append(uid)
      # show only unique sections
      unique_sections = {}
      sections = repeating_uid_category_map[uid]
      for section in sections:
        unique_sections[section['uid']] = section['relative_url']
      line['section_list'] = unique_sections.values()
      result_list.append(line)
  return [newTempBase(portal, x['title'], **x) for x in result_list]
from Products.ERP5Type.Document import newTempBase
contribution_registry = context.portal_contribution_registry

base_list = []
for attachment in context.getAttachmentInformationList():
  # XXX this is for prevent get parts related to body or not related to
  # Attachments
  if attachment['uid'] not in ['part_1', 'part_0']:
    filename  = context.getTitle()
    if attachment.has_key("file_name"):
       filename=attachment["file_name"]
    pt = "File"
    temp_base_id = 'index_'.join([attachment["uid"], str(attachment["index"])])
    base_list.append(newTempBase(context, id=temp_base_id,
                                              uid=temp_base_id,
                                              index= attachment["index"],
                                              file_name=filename,
                                              content_type=pt))

return base_list
Esempio n. 46
0
"""
  THis script returns a suitable slide list of PDF thumbnails
  for current form selection.
  It's to be used in a listbox.
"""
from Products.ERP5Type.Document import newTempBase

content_information = context.getContentInformation()
page_number = int(content_information.get("Pages", 0))
limit = kw.get("limit", (0, 0))
list_start = int(kw.get("list_start", 0))
list_lines = int(kw.get("list_lines", 0))
size = list_lines or limit[1]

list_end = list_start + size
page_list = range(page_number)

result = []
for i in page_list[list_start:list_end]:
    x = {"title": "%s" % i, "frame": "%s" % i}  # frame is used by listbox render field
    temp_object = newTempBase(context, x["title"], **x)
    result.append(temp_object)
return result
from Products.ERP5Type.Document import newTempBase
from string import zfill

portal_object = context.getPortalObject()
num = 0
result_listbox = []

if active_process_path is None:
  #return []
  active_process_path=context.REQUEST.get('active_process')

active_process_value = context.getPortalObject().restrictedTraverse(active_process_path)
result_list = [[x.method_id, x.result] for x in active_process_value.getResultList()]

result_list.sort()

for [method_id, result] in result_list:
  safe_id = context.Base_getSafeIdFromString('result %s' % num)
  num += 1
  int_len = 7
  if not result['success']:
      o = newTempBase(portal_object, safe_id)
      o.setUid(  'new_%s' % zfill(num, int_len)) # XXX There is a security issue here
      o.edit(uid='new_%s' % zfill(num, int_len)) # XXX There is a security issue here
      o.edit(**result['object'])
      result_listbox.append(o)

return result_listbox
Esempio n. 48
0
default_link_url ='setLanePath?form_id=%s&list_selection_name=%s' %(
                                 form_id, selection_name)

# Define date format using user Preferences
date_order = portal.portal_preferences.getPreferredDateOrder()
date_format = dict(ymd='%Y/%m/%d',
                   dmy='%d/%m/%Y',
                   mdy='%m/%d/%Y').get(date_order, '%Y/%m/%d')

category_list = []
if depth == 0:
  # recovering first date displayed, without time:
  while current_date < axis_stop: 
    # Create one Temp Object
    o = newTempBase(portal, id=str(current_date.Day()),
                    uid='new_%s' % zfill('year',4))

     # Setting Axis Dates start and stop
    o.setProperty('start',current_date)
    o.setProperty('stop',current_date+3)
    o.setProperty('relative_position', int(current_date))

    # Seting delimiter 
    if current_date.day() == 15:
      o.setProperty('delimiter_type', 1)
    else:
      o.setProperty('delimiter_type', 0)

    o.setProperty('title', current_date.strftime(date_format))
    tp = '%s %s' % (Message(domain='erp5_ui', message=current_date.Day(), mapping=None), str(current_date))
    o.setProperty('tooltip', tp)
Esempio n. 49
0
from Products.ERP5Type.Document import newTempBase
portal = context.getPortalObject()
result = []

def beautifyChange(change_dict):
  return ["%s:%s" % (k,change_dict[k]) for k in sorted(change_dict.keys())]

try:
  history_size = portal.portal_preferences.getPreferredHtmlStyleZodbHistorySize()
except AttributeError:
  history_size = 50

for dict_ in context.Base_getZODBChangeHistoryList(context, size=history_size):
  tmp = newTempBase(portal, '')
  dict_['changes'] = beautifyChange(dict_.get('changes', {}))
  tmp.edit(**dict_)
  result.append(tmp)
return result
Esempio n. 50
0
  def test_03_PasswordValidity(self):
    """
      Test validity of a password.
    """
    portal = self.getPortal()
    request = self.app.REQUEST

    regular_expression_list = ['([a-z]+)', # english lowercase
                               '([A-Z]+)', # english uppercase
                               '([0-9]+)', # numerals (0-9)
                               '([\\\\$\\\\!\\\\#\\\\%]+)' # (!, $, #, %)
                              ]

    self.assertTrue(portal.portal_preferences.isAuthenticationPolicyEnabled())

    person = portal.person_module.newContent(portal_type = 'Person',
                                             reference = 'test-03',
                                             password = '******',
                                             first_name = 'First',
                                             last_name = 'Last')
    preference = portal.portal_catalog.getResultValue(portal_type = 'System Preference',
                                                      title = 'Authentication',)
    self.tic()

    # by default an empty password if nothing set in preferences is OK
    self.assertTrue(person.isPasswordValid(''))

    # Not long enough passwords used
    self._cleanUpPerson(person)
    preference.setPreferredMinPasswordLength(8)
    preference.setPreferredNumberOfLastPasswordToCheck(0)
    self.tic()
    self._clearCache()

    self.assertEqual([-1], person.analyzePassword(''))
    self.assertEqual([-1], person.analyzePassword('1234567'))
    self.assertTrue(person.isPasswordValid('12345678'))

    # not changed in last x days
    self._cleanUpPerson(person)
    preference.setPreferredMinPasswordLifetimeDuration(24)
    preference.setPreferredNumberOfLastPasswordToCheck(3)
    self.tic()
    self._clearCache()

    self.assertTrue(person.isPasswordValid('12345678'))
    person.setPassword('12345678')
    self.tic()

    # if we try to change now we should fail with any password
    self.assertSameSet([-3], person.analyzePassword('87654321'))
    self.assertSameSet([-1, -3], person.analyzePassword('short')) # multiple failures
    self.assertFalse(person.isPasswordValid('short')) # multiple failures
    self.assertRaises(ValueError, person.setPassword, '87654321')

    preference.setPreferredMinPasswordLifetimeDuration(0) # remove restriction
    self.tic()
    self._clearCache()
    self.assertTrue(person.isPasswordValid('87654321')) # it's OK to change

    # password not used in previous X passwords
    preference.setPreferredMinPasswordLength(None) # disable for now
    self._cleanUpPerson(person)
    self._clearCache()
    self.tic()

    person.setPassword('12345678-new')
    self.tic()

    self.assertSameSet([-4], person.analyzePassword('12345678-new')) # if we try to change now we should fail with this EXACT password
    self.assertRaises(ValueError, person.setPassword, '12345678-new')
    self.assertTrue(person.isPasswordValid('12345678_')) # it's OK with another one not used yet
    for password in ['a','b','c','d', 'e', 'f']:
      # this sleep is not so beautiful, but mysql datetime columns has a
      # precision of one second only, and we use creation_date to order
      # "Password Event" objects. So without this sleep, the test is
      # failing randomly.
      time.sleep(1)
      person.setPassword(password)
      self.tic()
    self._clearCache()
    self.tic()

    self.assertTrue(person.isPasswordValid('12345678-new'))
    self.assertTrue(person.isPasswordValid('a'))
    self.assertTrue(person.isPasswordValid('b'))
    self.assertTrue(person.isPasswordValid('c'))
    # only last 3 (including current one are invalid)
    self.assertSameSet([-4], person.analyzePassword('d'))
    self.assertSameSet([-4], person.analyzePassword('e'))
    self.assertSameSet([-4], person.analyzePassword('f'))

    # if we remove restricted then all password are usable
    preference.setPreferredNumberOfLastPasswordToCheck(None)
    self._clearCache()
    self.tic()

    self.assertTrue(person.isPasswordValid('d'))
    self.assertTrue(person.isPasswordValid('e'))
    self.assertTrue(person.isPasswordValid('f'))

    # if we set only last password to check
    preference.setPreferredNumberOfLastPasswordToCheck(1)
    self._clearCache()
    self.tic()
    self.assertTrue(person.isPasswordValid('c'))
    self.assertTrue(person.isPasswordValid('d'))
    self.assertTrue(person.isPasswordValid('e'))
    self.assertSameSet([-4], person.analyzePassword('f'))

    preference.setPreferredRegularExpressionGroupList(regular_expression_list)
    preference.setPreferredMinPasswordLength(7)
    preference.setPreferredNumberOfLastPasswordToCheck(None)
    self._cleanUpPerson(person)
    self._clearCache()
    self.tic()

    four_group_password_list = ['abAB#12', 'ghTK61%', '5Tyui1%','Y22GJ5iu#' ]
    three_group_password_list = ['abAB123 ', 'AB123ab', 'XY123yz', 'dufgQ7xL', 'NAfft8h5', '0LcAiWtT']
    two_group_password_list = ['XY12345', 'yuiffg1', 'abcdef##', '##$aabce']
    one_group_password_list = ['1234567', 'ABZSDFE', '##!!$$%','abzdeffgg']

    # min 4 out of all groups
    preference.setPreferredMinRegularExpressionGroupNumber(4)
    self._clearCache()
    self.tic()
    for password in four_group_password_list:
      self.assertTrue(person.isPasswordValid(password))
    for password in three_group_password_list+two_group_password_list + one_group_password_list:
      self.assertSameSet([-2], person.analyzePassword(password))

    # min 3 out of all groups
    preference.setPreferredMinRegularExpressionGroupNumber(3)
    self._clearCache()
    self._cleanUpPerson(person)
    self.tic()
    for password in four_group_password_list + three_group_password_list:
      self.assertTrue(person.isPasswordValid(password))
    for password in two_group_password_list + one_group_password_list:
      self.assertSameSet([-2], person.analyzePassword(password))

    # min 2 out of all groups
    preference.setPreferredMinRegularExpressionGroupNumber(2)
    self._clearCache()
    self.tic()
    for password in four_group_password_list + three_group_password_list + two_group_password_list:
      self.assertTrue(person.isPasswordValid(password))
    for password in one_group_password_list:
      self.assertSameSet([-2], person.analyzePassword(password))

    # min 1 out of all groups
    preference.setPreferredMinRegularExpressionGroupNumber(1)
    self._clearCache()
    self.tic()
    for password in four_group_password_list + three_group_password_list + two_group_password_list+one_group_password_list:
      self.assertTrue(person.isPasswordValid(password))

    # not contain the full name of the user
    preference.setPrefferedForceUsernameCheckInPassword(1)
    self._clearCache()
    self.tic()
    self.assertSameSet([-5], person.analyzePassword('abAB#12_%s' %person.getFirstName()))
    self.assertSameSet([-5], person.analyzePassword('abAB#12_%s' %person.getLastName()))
    preference.setPrefferedForceUsernameCheckInPassword(0)
    self._clearCache()
    self.tic()
    self.assertTrue(person.isPasswordValid('abAB#12_%s' %person.getFirstName()))
    self.assertTrue(person.isPasswordValid('abAB#12_%s' %person.getLastName()))

    # check on temp objects just passworrd length( i.e. simulating a new user account creation)
    first_name = 'John'
    last_name = 'Doh'
    kw = {'title': '%s %s' %(first_name, last_name),
          'first_name': first_name,
          'last_name': last_name}
    temp_person = newTempBase(portal, kw['title'], **kw)

    preference.setPreferredMinPasswordLength(10)
    preference.setPreferredRegularExpressionGroupList(None)
    self._clearCache()
    self.tic()
    # in this case which is basically used in new account creation only length of password matters
    self.assertSameSet([-1], temp_person.Person_analyzePassword('onlyNine1'))
    self.assertSameSet([], temp_person.Person_analyzePassword('longEnough1'))

    # make sure re check works on temp as well ( i.e. min 3 out of all groups)
    preference.setPreferredRegularExpressionGroupList(regular_expression_list)
    preference.setPreferredMinPasswordLength(7)
    preference.setPreferredMinRegularExpressionGroupNumber(3)
    self._clearCache()
    self.tic()
    for password in four_group_password_list + three_group_password_list:
      self.assertSameSet([], temp_person.Person_analyzePassword(password))
    for password in two_group_password_list + one_group_password_list:
      self.assertSameSet([-2], temp_person.Person_analyzePassword(password))

    # make sure peron's check on username works on temp as well (i.e. not contain the full name of the user)
    preference.setPrefferedForceUsernameCheckInPassword(1)
    self._clearCache()
    self.tic()
    self.assertSameSet([-5], temp_person.Person_analyzePassword('abAB#12_%s' %first_name))
    self.assertSameSet([-5], temp_person.Person_analyzePassword('abAB#12_%s' %last_name))

    preference.setPrefferedForceUsernameCheckInPassword(0)
    self._clearCache()
    self.tic()
    self.assertSameSet([], temp_person.Person_analyzePassword('abAB#12_%s' %first_name))
    self.assertSameSet([], temp_person.Person_analyzePassword('abAB#12_%s' %last_name))

    # check Base_isPasswordValid is able to work in Anonymous User fashion
    # but with already create Person object (i.e. recover password case)
    preference.setPrefferedForceUsernameCheckInPassword(1)
    preference.setPreferredMinPasswordLength(7)
    preference.setPreferredMinRegularExpressionGroupNumber(3)
    preference.setPreferredNumberOfLastPasswordToCheck(1)
    self._clearCache()
    self.tic()

    person.setPassword('used_ALREADY_1234')
    self._clearCache()
    self.tic()

    # emulate Anonymous User
    self.logout()
    request.set('field_user_login', person.getReference())
    self.assertRaises(ValidationError,  portal.Base_isPasswordValid, 'abAB#12_%s' %person.getFirstName(), request) # contains name
    self.assertRaises(ValidationError,  portal.Base_isPasswordValid, 'abAB#12_%s' %person.getLastName(), request) # contains name
    self.assertRaises(ValidationError,  portal.Base_isPasswordValid, 'abAB#1', request) # too short
    self.assertRaises(ValidationError,  portal.Base_isPasswordValid, 'abABCDEFG', request) # too few groups
    self.assertRaises(ValidationError,  portal.Base_isPasswordValid, 'used_ALREADY_1234', request) # already used
    self.assertEqual(1, portal.Base_isPasswordValid('abAB#12_', request))
    self.assertEqual(1, portal.Base_isPasswordValid('not_used_ALREADY_1234', request))
Esempio n. 51
0
axis_stop = DateTime(year, month, 1)

default_link_url = 'setLanePath?form_id=%s&list_selection_name=%s' % (
    form_id, selection_name)

# Define date format using user Preferences
date_order = portal.portal_preferences.getPreferredDateOrder()
date_format = dict(ymd='%Y/%m/%d', dmy='%d/%m/%Y',
                   mdy='%m/%d/%Y').get(date_order, '%Y/%m/%d')

category_list = []
if depth == 0:
    # recovering first date displayed, without time:
    while current_date < axis_stop:
        # Create one Temp Object
        o = newTempBase(portal, id=str(current_date.Day()), uid='new_year')

        # Setting Axis Dates start and stop
        o.setProperty('start', current_date)
        o.setProperty('stop', current_date + 3)
        o.setProperty('relative_position', int(current_date))

        # Seting delimiter
        if current_date.day() == 15:
            o.setProperty('delimiter_type', 1)
        else:
            o.setProperty('delimiter_type', 0)

        o.setProperty('title', current_date.strftime(date_format))
        tp = '%s %s' % (Message(domain='erp5_ui',
                                message=current_date.Day(),
closing_debit_balance  = 0.0
closing_credit_balance = 0.0
if from_date not in (None, ''):
  opening_debit_balance = getInventory( at_date     = from_date
                                      , omit_output = True
                                      , **get_inventory_kw
                                      )
  opening_credit_balance = - getInventory( at_date    = from_date
                                         , omit_input = True
                                         , **get_inventory_kw
                                         )
closing_debit_balance = getInventory( at_date     = at_date
                                    , omit_output = True
                                    , **get_inventory_kw
                                    )
closing_credit_balance = - getInventory( at_date    = at_date
                                       , omit_input = True
                                       , **get_inventory_kw
                                       )

list_item = newTempBase(portal, 'xxx')
list_item.setUid('new_000')
list_item.edit(** {
    'total_opening_debit_balance' : opening_debit_balance
  , 'total_closing_debit_balance' : closing_debit_balance
  , 'total_opening_credit_balance': opening_credit_balance
  , 'total_closing_credit_balance': closing_credit_balance
  })

return [list_item]
     previous_total_debit  = getInventoryAssetPrice(omit_asset_decrease=True,
            from_date=period_start_date,
            to_date=initial_balance_from_date,
            **get_inventory_kw) + max(period_openning_balance, 0)
     previous_total_credit = getInventoryAssetPrice(omit_asset_increase=True,
            from_date=period_start_date,
            to_date=initial_balance_from_date,
            **get_inventory_kw) - max(-period_openning_balance, 0)
 
     if previous_total_credit != 0:
       previous_total_credit = - previous_total_credit
   
     # Show the previous balance if not empty
     if previous_total_credit != 0 or previous_total_debit != 0:
       net_balance = previous_total_debit - previous_total_credit
       previous_balance = newTempBase(portal, '_temp_accounting_transaction')
       previous_balance.edit(
           uid='new_000',
           date=initial_balance_from_date,
           simulation_state_title="",
           credit_price=previous_total_credit,
           debit_price=previous_total_debit,
           total_price=net_balance,
           credit=previous_total_credit,
           debit=previous_total_debit,
           total_quantity=net_balance,
           running_total_price=net_balance,
           is_previous_balance=True,
           Movement_getSpecificReference=u'%s' % translateString('Previous Balance'),
           Movement_getExplanationTitle=u'%s' % translateString('Previous Balance'),
           Movement_getExplanationTranslatedPortalType='',
for history_name in ['history', 'building_history', 'installation_history']:
  workflow_item_list = portal_workflow.getInfoFor(ob=context, 
                                          name='history', wf_id=workflow_id)
  if workflow_item_list != []:
    break

wf_states = portal_workflow[workflow_id].states
wf_transitions = portal_workflow[workflow_id].transitions

next_serial = None
previous_obj = None

for workflow_item in workflow_item_list:
  same_action = 0
  # XXX removing str method generate a strange bug
  o = newTempBase(portal_object, str(i))
  i += 1
  for key, value in workflow_item.items():
    # XXX Compatibility
    for compatibility_name in ['building_', 'installation_']:
      if key.startswith(compatibility_name):
        # Display the workflow state in the state columns
        key = key[len(compatibility_name):]
    if key.endswith('state'): 
      key = 'state'
      if display:
        value = wf_states.get(value, marker) and wf_states[value].title
      else:
        value = wf_states.get(value, marker) and wf_states[value].id
    if key == 'action':
      action_name = value
cache_stats = context.getPortalObject().portal_caches.getCacheTotalMemorySize()
cache_factory_list_stats = cache_stats['stats']
cache_plugin_id = context.getId()
cache_factory_id = context.getParentValue().getId()
cache_plugin_stats = cache_factory_list_stats[cache_factory_id]
cache_plugin_stats_data = cache_plugin_stats['cp_cache_keys_total_size']

if statistics_criteria == 'total':
  # return just mrmotu usage for cache plugin
  return cache_plugin_stats['total']

result = []
counter = 0
for cache_key,cache_key_memory in cache_plugin_stats_data.items():
  obj = newTempBase(context, 
                    'temp_translation_%d' %counter,
                    cache_key = cache_key,
                    cache_key_memory = cache_key_memory)
  obj.setUid('new_%d' %counter)
  counter += 1
  result.append(obj)

# sort result
if kw.get('sort_on', None) is not None:
  sort_on_attr, sort_on_order = kw['sort_on'][0]
  result.sort(key=lambda x: int(getattr(x, sort_on_attr)))
  if sort_on_order == 'descending':
    result.reverse()

return result
params = portal.portal_selections.getSelectionParamsFor(selection_name, request)

zoom_begin = DateTime(params.get('bound_start', DateTime()))
year = zoom_begin.year() + params.get('bound_variation', 0)
current_date = DateTime(year, 1, 1)

default_link_url ='setLanePath?form_id=%s&list_selection_name=%s' %(
                                 form_id, selection_name)

category_list = []
if depth == 0:
  # getting list of months
  count = 0
  while   count < 12:
    # Create one Temp Object
    o = newTempBase(portal, id='year' ,uid='new_%s' % zfill('year',4))
    # Seting delimiter 
    if current_date.month() in [1, 7]:
      o.setProperty('delimiter_type', 1)
    else:
      o.setProperty('delimiter_type', 0)
    
     # Setting Axis Dates start and stop
    o.setProperty('start',current_date)
    if current_date.month() != 12:
      stop_date = DateTime(current_date.year(),current_date.month() +1,1)
    else:
      stop_date = DateTime(year+1, 1, 1)
    o.setProperty('stop', stop_date)
    
    o.setProperty('relative_position', int(current_date))
Esempio n. 57
0
        result = project_search_dict.get(line_source_project_title, None)
        error_message = None
        if result is None:
            result = portal.portal_catalog(portal_type=('Project',
                                                        'Project Line'),
                                           title=line_source_project_title)
            project_search_dict[line_source_project_title] = result
        if len(result) == 0:
            error_message = "No such project"
        elif len(result) > 1:
            error_message = "Too many matching projects"
        else:
            line_dict['source_project_relative_url'] = result[
                0].getRelativeUrl()
        if error_message:
            error = newTempBase(context, key)
            error.edit(error_text=error_message)
            validation_errors['listbox_source_project_title_new_%s' %
                              key] = error
    listbox.append(line_dict)
    i += 1

context.log('listbox', listbox)
context.Base_updateDialogForm(listbox=listbox, update=1, kw=kw)

if len(validation_errors):
    request.set('field_errors', validation_errors)
    kw['REQUEST'] = request

# if called from the validate action we create tasks
if create and len(validation_errors) == 0: