def process(self):        
     alsoProvides(self.request, IDisableCSRFProtection)
     """ do main work here """
     context = api.content.get(path='/library/ws/resources')
     
     computer_id = self.request.form.get('computerId','')
     print computer_id
     print idnormalizer.normalize(computer_id)
     available = True 
     if int(self.request.form.get('status', -1)) <= 0:
         available = False
     
     brains = api.content.find(context=context, portal_type='polklibrary.type.computeravailability.models.resource', id=idnormalizer.normalize(computer_id))
     if brains:
         obj = brains[0].getObject()
         obj.activated = available
         obj.reindexObject()
         self._data['status'] = 'Updated'
     else:
         obj = api.content.create(
                     type='polklibrary.type.computeravailability.models.resource',
                     title=computer_id,
                     container=context,
                 )
         obj.activated = available
         obj.resources = u"PC"  # Default since most are
         api.content.transition(obj=obj, transition='publish')
         obj.reindexObject()
         self._data['status'] = 'Created'
def church_member_val(context):
    registry = getUtility(IRegistry)
    settings = registry.forInterface(IChurchMemberDGForm, check=False)
    values = []
    result = []
    unique_list = []
    if settings.church_member:
        for val in settings.church_member:
            cmv = unicode(idnormalizer.normalize(val['church_member_values']))
            if cmv not in unique_list:
                unique_list.append(cmv)
                values.append({
                    'value':
                    unicode(idnormalizer.normalize(
                        val['church_member_values'])),
                    'title':
                    val['church_member_values']
                })
            #values.append(SimpleTerm(value=unicode(val['church_member_values']), token=unicode(val['church_member_values']), title=val['church_member_values']))
    if values:
        values.sort(key=lambda k: k['title'])
        result = [
            SimpleTerm(value=v['value'], token=v['value'], title=v['title'])
            for v in values
        ]
    return SimpleVocabulary(result)
Exemplo n.º 3
0
def modifyobject(context, event):
    parent = context.aq_parent
    id = context.getId()
    object_Ids = []
    catalog = getToolByName(context, 'portal_catalog')
    brains = catalog.unrestrictedSearchResults(
        object_provides=ISignature.__identifier__)
    for brain in brains:
        object_Ids.append(brain.id)

    last_name = idnormalizer.normalize(context.last_name)
    first_name = idnormalizer.normalize(context.first_name)
    temp_new_id = last_name + '_' + first_name
    new_id = temp_new_id.replace("-", "")
    test = ''
    if new_id in object_Ids:
        test = filter(lambda name: new_id in name, object_Ids)

        if '-' not in (max(test)):
            new_id = new_id + '-1'
        if '-' in (max(test)):
            new_id = new_id + '-' + str(int(max(test).split('-')[-1]) + 1)
    parent.manage_renameObject(id, new_id)
    new_title = last_name + ' ' + first_name
    context.setTitle(new_title)
    context.reindexObject()
    return
Exemplo n.º 4
0
def create_notary_letters():

    cpt = 1
    containerNotaryLetters = api.content.get(path='/urban/notaryletters')
    for (dirpath, dirnames, filenames) in os.walk(IMPORT_FOLDER_PATH + '/documents'):
        # print(root, dirs, files)
        for notaryletter_file in filenames:
            if '_' in notaryletter_file or '~' in notaryletter_file:
                continue
            print "PROCESSING NOTARY LETTER %i" % cpt
            cpt += 1

            # if cpt > 10:
            #     break
            file_suffix = notaryletter_file.replace(".doc", "").replace(".docx", "").replace(".DOC", "")
            id_notary_letter = idnormalizer.normalize('notary_letter%s' + file_suffix)

            if not (id_notary_letter in containerNotaryLetters.objectIds()):
                object_id = containerNotaryLetters.invokeFactory('NotaryLetter', id=id_notary_letter,
                                                    title="ARCHIVE NOT " + file_suffix,
                                                    reference="ARCHIVE NOT " + file_suffix)

                if object_id:
                    current_letter = api.content.get(path='/urban/notaryletters/' + id_notary_letter)
                    attachment = read_file(os.path.abspath(os.path.join(dirpath, notaryletter_file)))
                    api.content.create(container=current_letter, type='File', id=idnormalizer.normalize("file"+ file_suffix), title=notaryletter_file, file=attachment)
                    # current_letter.invokeFactory('File', id="file_" + id_notary_letter,
                    #                                 title="ARCHIVE NOT" + file_suffix)

                    parcels = get_parcels_from_filename(file_suffix, current_letter)

                    file_name = notaryletter_file
                    document_path = dirpath
                    while True:
                        file_name = file_name[0:len(file_name) - 4] + "_.doc"
                        try:
                            path = path_insensitive(document_path + "/" + file_name)
                            doc = open(path, 'rb')

                        except:
                            # no more _ sequence found : break the infinite loop
                            break
                        doc_content = doc.read()
                        doc.close()

                        api.content.create(container=current_letter, type='File',
                                           id=idnormalizer.normalize("file" + file_name), title=file_name,
                                           file=doc_content)
Exemplo n.º 5
0
    def __call__(self):

        if "form.buttons.save" in self.request.form:

            title = self.request.form.get("form.widgets.title", str(time.time()))
            id = idnormalizer.normalize(title) + "-" + str(int(time.time()))
            description = self.request.form.get("form.widgets.description", "")
            private = self.request.form.get("form.widgets.league_private", [])
            is_private = False
            if len(private) > 0:
                is_private = True
            password = self.request.form.get("form.widgets.league_password", "")
            user = api.user.get_current()
            playername = self.request.form.get("form.widgets.player", user.getProperty("fullname"))

            # Create League
            _createObjectByType(
                "babble.core.models.league",
                self.context,
                id,
                title=title,
                description=description,
                league_private=is_private,
                league_password=password,
                owner=user.getProperty("email"),
            )

            # Create Owner as a Player
            _createObjectByType(
                "babble.core.models.player",
                self.context.get(id),
                idnormalizer.normalize(playername),
                title=playername,
                pick_order=random.randint(1, 200000000),
                owner=user.getProperty("email"),
            )

            return self.request.response.redirect(
                self.context.absolute_url()
                + "/"
                + id
                + "/preventrefresh?goto="
                + self.context.absolute_url()
                + "/"
                + id
            )

        return self.template()
Exemplo n.º 6
0
def _build_option(filter_value, url, current_idx_value, groupby_options):
    idx = groupby_options["index"]
    # Optional modifier to set title from filter value
    display_modifier = groupby_options.get("display_modifier", None)
    # CSS modifier to set class on filter item
    css_modifier = groupby_options.get("css_modifier", None)

    # Set title from filter value with modifications,
    # e.g. uuid to title
    title = filter_value
    if filter_value is not EMPTY_MARKER and callable(display_modifier):
        title = display_modifier(filter_value, idx)
        title = safe_decode(title)

    # Set selected state
    selected = filter_value in current_idx_value
    css_class = "filterItem {0}{1} {2}".format(
        "filter-" + idnormalizer.normalize(filter_value),
        " selected" if selected else "",
        css_modifier(filter_value) if css_modifier else "",
    )

    return {
        "title": title,
        "url": url,
        "value": filter_value,
        "css_class": css_class,
        "count": 1,
        "selected": selected,
    }
    def __iter__(self):
        for item in self.previous:
            pathkey = self.pathkey(*item.keys())[0]
            roleskey = self.roleskey(*item.keys())[0]

            if not pathkey or not roleskey or \
               roleskey not in item:    # not enough info
                yield item; continue

            obj = self.context.unrestrictedTraverse(item[pathkey].lstrip('/'), None)
            if obj is None:             # path doesn't exist
                yield item; continue

            if IRoleManager.providedBy(obj):
                
                if self.options.get('erasebefore'):
                    obj.__ac_local_roles__ = {}
                for principal, roles in item[roleskey].items():
                    if roles:
                        if principal.startswith(u'group_'):
                            principal = idnormalizer.normalize(principal)
                        obj.manage_addLocalRoles(principal, roles)
                obj.reindexObjectSecurity()

            yield item
Exemplo n.º 8
0
 def update(self):
     super(GlobalStatusMessage, self).update()
     self.status = IStatusMessage(self.request)
     messages = self.status.show()
     for m in messages:
         m.id = idnormalizer.normalize(m.message)
     self.messages = messages
Exemplo n.º 9
0
def load_geometers():

    csv_filename = 'blc_geometres.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index) for index, headercell in enumerate(lines.next())])
    cpt = 1
    for geometer in lines:
        print "PROCESSING GEOMETER %i" % cpt
        cpt += 1
        id_geometer = idnormalizer.normalize(('geometer_%s%s' % (geometer[header_indexes['Nom']], geometer[header_indexes['Prenom']])).replace(" ", ""))
        containerGeometers = api.content.get(path='/urban/geometricians')

        if id_geometer not in containerGeometers.objectIds():

            if not (id_geometer in containerGeometers.objectIds()):
                object_id = containerGeometers.invokeFactory('Geometrician', id=id_geometer,
                                                    name1=geometer[header_indexes['Nom']],
                                                    name2=geometer[header_indexes['Prenom']],
                                                    phone=geometer[header_indexes['Telephone']],
                                                    gsm=geometer[header_indexes['Gsm']],
                                                    email=geometer[header_indexes['Email']],
                                                    street=geometer[header_indexes['Rue et Numero']],
                                                    zipcode=geometer[header_indexes['Code postal']],
                                                    city=geometer[header_indexes['Localite']])
Exemplo n.º 10
0
    def my_validator(fs):
        if not fs.id.value:
            project_id = idnormalizer.normalize(fs.name.value)
        else:
            project_id = fs.id.value

        if project_id.lower() in PROJECT_ID_BLACKLIST:
            msg = _('${fs_name_value} is a restricted name! Please choose '
                    'another project name or provide unique ID!',
                    mapping={'fs_name_value': project_id})
            raise ValidationError(msg)

        project = DBSession().query(Project).get(project_id)
        if project and project != fs.model:
            msg = _('${fs_name_value} already exists! Please choose another '
                    'project name or provide unique ID!',
                    mapping={'fs_name_value': project_id})
            raise ValidationError(msg)

        if fs.activated.value == False and project:
            active_contracts = [a for a in project.contracts if a.active]
            if active_contracts:
                msg = _('You cannot deactivate project! It has uncompleted '
                        'contracts!')
                raise ValidationError(msg)
Exemplo n.º 11
0
def load_notaries():

    csv_filename = 'blc_notaires.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index) for index, headercell in enumerate(lines.next())])
    cpt = 1
    for notary in lines:
        print "PROCESSING NOTARY %i" % cpt
        cpt += 1
        id_notary = idnormalizer.normalize(('notary_%s%s' % (notary[header_indexes['Nom']], notary[header_indexes['Prenom']])).replace(" ", ""))
        containerNotaries = api.content.get(path='/urban/notaries')

        if id_notary not in containerNotaries.objectIds():

            if not (id_notary in containerNotaries.objectIds()):
                object_id = containerNotaries.invokeFactory('Notary', id=id_notary,
                                                    name1=notary[header_indexes['Nom']],
                                                    name2=notary[header_indexes['Prenom']],
                                                    phone=notary[header_indexes['Telephone']],
                                                    street='%s %s' % (notary[header_indexes['Adresse1']], notary[header_indexes['Adresse2']]),
                                                    zipcode=notary[header_indexes['Code_postal']],
                                                    city=notary[header_indexes['Ville']])
Exemplo n.º 12
0
def onCourseEdit(context, event):

    # Get the helper for the course (used to initially set the id)
    helper = CourseHelper(context)

    # Calculate a new title and id
    new_title = helper.course_title
    new_id = idnormalizer.normalize(helper.course_number)

    # Get the existing new title and id
    old_id = context.getId()
    old_title = context.title

    # This bool stores if the id/title were changed
    changed = False

    # If the new id is different than the old id, update it. If it already
    # exists, throw an error.
    if new_id != old_id:

        try:
            context.aq_parent.manage_renameObjects(ids=[old_id],
                                                   new_ids=[new_id])
        except CopyError, e:
            raise ValueError(u"The id '%s' is already in use." % new_id)
            return

        changed = True
Exemplo n.º 13
0
def _add_id(structure):
    """ Add a key for the id as the normalized title, if it does not exists. """
    for item in structure:
        item.setdefault('id', idnormalizer.normalize(item['title'], 'es'))
        if '_children' in item:
            item['_children'] = _add_id(item['_children'])
    return structure
Exemplo n.º 14
0
    def import_objects(self, objects):

        good_count = 0
        ignored_count = 0
        for obj in objects:
            params = self.import_object(obj)

            # take care of harvested dct:Indentifier/adms:Identifier
            params.update(handle_identifiers(obj))

            # Special case of isDefiendBy. If not given use rdfabout URI
            attribute = getattr(obj, 'rdfs_isDefinedBy')
            if attribute:
                att_data = str(attribute.first)
            else:
                att_data = str(getattr(obj, 'subject'))

            params['rdfs_isDefinedBy'] = att_data

            # Get a label for the item
            label = str(getattr(obj, 'dc_identifier'))

            # if there is no title use the dc_identifier
            if not params['dct_title']:
                params['dct_title'] = label

            if isinstance(label, dict):
                id = label[self.default_language]
            elif isinstance(label, list):
                id = label[0]
            else:
                id = label
            id = idnormalizer.normalize(id)

            if isinstance(params['dct_title'], dict):
                title = params['dct_title'][self.default_language]
            elif isinstance(params['dct_title'], list):
                title = params['dct_title'][0]
            else:
                title = params['dct_title']

            try:
                # create a license document object
                new_obj = content.create(container=self.context,
                                         type=self.object_dx_class,
                                         id=id,
                                         title=title,
                                         **params)
            # skip already existing licenses
            except BadRequest:
                ignored_count += 1
                continue
            else:
                good_count += 1

            # set adms_identifier to the local URI of the item
            if new_obj.adms_identifier is None:
                new_obj.adms_identifier = new_obj.absolute_url()

        return good_count, ignored_count
Exemplo n.º 15
0
def rename_after_add(obj, event):
    """
    Se asigna el ID a la pregunta, basado en la pregunta propiamente
    """

    id = idnormalizer.normalize(obj.question)
    obj.id = id
Exemplo n.º 16
0
def load_parcellings():

    csv_filename = 'blc_lotissements.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index) for index, headercell in enumerate(lines.next())])
    cpt = 1
    for parcelling in lines:
        print "PROCESSING PARCELLING %i" % cpt
        cpt += 1
        id_parcelling = idnormalizer.normalize(('parcelling%s%s' % (parcelling[header_indexes['Nom du lotisseur']], parcelling[header_indexes['ReferenceRW']].replace("-", "").replace(".", ""))).replace(" ", ""))
        containerParcellings = api.content.get(path='/urban/parcellings')

        if id_parcelling not in containerParcellings.objectIds():

            if not (id_parcelling in containerParcellings.objectIds()):

                object_id = containerParcellings.invokeFactory('ParcellingTerm', id=id_parcelling,
                                                    title='%s %s' % (parcelling[header_indexes['ReferenceRW']], parcelling[header_indexes['Nom du lotisseur']]),
                                                    label=parcelling[header_indexes['Libelle']],
                                                    subdividerName=parcelling[header_indexes['Nom du lotisseur']],
                                                    authorizationDate=parcelling[header_indexes['Date autorisation']],
                                                    DGO4Reference=parcelling[header_indexes['ReferenceRW']],
                                                    numberOfParcels=parcelling[header_indexes['Nombre de lots']])

                parcel = create_parcel(object_id,
                                       parcelling[header_indexes['Parcelle1Section']],
                                       parcelling[header_indexes['Parcelle1Numero']],
                                       parcelling[header_indexes['Parcelle1NumeroSuite']],
                                       parcelling[header_indexes['AdresseLocalite']])
Exemplo n.º 17
0
def load_architects():

    csv_filename = 'blc_architects.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index) for index, headercell in enumerate(lines.next())])
    cpt = 1
    for architect in lines:
        print "PROCESSING ARCHITECT %i" % cpt
        cpt += 1
        id_architect = idnormalizer.normalize(('architect_%s%s' % (architect[header_indexes['Nom']], architect[header_indexes['Prenom']])).replace(" ", ""))
        containerArchitects = api.content.get(path='/urban/architects')

        if id_architect not in containerArchitects.objectIds():

            if not (id_architect in containerArchitects.objectIds()):
                object_id = containerArchitects.invokeFactory('Architect', id=id_architect,
                                                    name1=architect[header_indexes['Nom']],
                                                    name2=architect[header_indexes['Prenom']],
                                                    phone=architect[header_indexes['Telephone']],
                                                    gsm=architect[header_indexes['Gsm']],
                                                    email=architect[header_indexes['Email']],
                                                    street=architect[header_indexes['Rue et Numero']],
                                                    zipcode=architect[header_indexes['Code postal']],
                                                    city=architect[header_indexes['Localite']])
Exemplo n.º 18
0
def ploneify(toPlone, filename=False):

    # Start with Unicode
    ploneString = safe_unicode(toPlone)

    # Replace specific characters that aren't caught by the unicode transform
    for (_f, _t) in [
        # Various dash-y characters
        (u'\u2010', u'-'),
        (u'\u2011', u'-'),
        (u'\u2012', u'-'),
        (u'\u2013', u'-'),
        (u'\u2014', u'-'),
        (u'\u2015', u'-'),
    ]:
        ploneString = ploneString.replace(_f, _t)

    # Convert accented characters to ASCII
    # Ref: https://stackoverflow.com/questions/14118352/how-to-convert-unicode-accented-characters-to-pure-ascii-without-accents
    ploneString = unicodedata.normalize('NFD', ploneString).encode('ascii', 'ignore')

    # Normalize using the system utility
    if filename:
        ploneString = filenamenormalizer.normalize(ploneString, max_length=99999)
        ploneString = re.sub('[-\s]+', '_', ploneString) # Replace whitespace with underscores
    else:
        ploneString = idnormalizer.normalize(ploneString, max_length=99999)

    # Remove leading/trailing dashes
    ploneString = re.sub("-$", "", ploneString)
    ploneString = re.sub("^-", "", ploneString)

    return ploneString
Exemplo n.º 19
0
    def add(self, names):
        data = json_body(self.request)

        title = data.get("title", None)
        if not title:
            raise BadRequest("Property 'title' is required")

        tid = data.get("id", None)
        if not tid:
            tid = idnormalizer.normalize(title).replace("-", "_")

        description = data.get("description", "")

        properties = {"id": tid, "title": title, "description": description}

        # Disable CSRF protection
        if "IDisableCSRFProtection" in dir(plone.protect.interfaces):
            alsoProvides(self.request,
                         plone.protect.interfaces.IDisableCSRFProtection)

        if IPloneRestapiLayer.providedBy(self.request):
            noLongerProvides(self.request, IPloneRestapiLayer)

        context = queryMultiAdapter((self.context, self.request),
                                    name='dexterity-types')
        add_type = queryMultiAdapter((context, self.request), name='add-type')
        fti = add_type.form_instance.create(data=properties)
        add_type.form_instance.add(fti)
        return self.get([
            tid,
        ])
def _add_id(structure):
    """ Add a key for the id as the normalized title, if it does not exists. """
    for item in structure:
        item.setdefault('id', idnormalizer.normalize(item['title'], 'es'))
        if '_children' in item:
            item['_children'] = _add_id(item['_children'])
    return structure
Exemplo n.º 21
0
 def mapTitle(self, line):
     doc_id = self.getData('CADDIV') + self.getData('CADSEC') + self.getData('CADNUM')
     if not doc_id or '?' in doc_id:
         raise NoObjectToCreateException
     # doc_id = document_path.split('\\')[-1]
     doc_id = idnormalizer.normalize(doc_id)
     return doc_id
Exemplo n.º 22
0
def load_parcellings():

    csv_filename = 'blc_lotissements.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index) for index, headercell in enumerate(lines.next())])
    cpt = 1
    for parcelling in lines:
        print "PROCESSING PARCELLING %i" % cpt
        cpt += 1
        id_parcelling = idnormalizer.normalize(('parcelling%s%s' % (parcelling[header_indexes['Nom du lotisseur']], parcelling[header_indexes['ReferenceRW']].replace("-", "").replace(".", ""))).replace(" ", ""))
        containerParcellings = api.content.get(path='/urban/parcellings')

        if id_parcelling not in containerParcellings.objectIds():

            if not (id_parcelling in containerParcellings.objectIds()):

                object_id = containerParcellings.invokeFactory('ParcellingTerm', id=id_parcelling,
                                                    title='%s %s' % (parcelling[header_indexes['ReferenceRW']], parcelling[header_indexes['Nom du lotisseur']]),
                                                    label=parcelling[header_indexes['Libelle']],
                                                    subdividerName=parcelling[header_indexes['Nom du lotisseur']],
                                                    authorizationDate=parcelling[header_indexes['Date autorisation']],
                                                    DGO4Reference=parcelling[header_indexes['ReferenceRW']],
                                                    numberOfParcels=parcelling[header_indexes['Nombre de lots']])

                parcel = create_parcel(object_id,
                                       parcelling[header_indexes['Parcelle1Section']],
                                       parcelling[header_indexes['Parcelle1Numero']],
                                       parcelling[header_indexes['Parcelle1NumeroSuite']],
                                       parcelling[header_indexes['AdresseLocalite']])
Exemplo n.º 23
0
def load_geometers():

    csv_filename = 'blc_geometres.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index)
                           for index, headercell in enumerate(lines.next())])
    cpt = 1
    for geometer in lines:
        print "PROCESSING GEOMETER %i" % cpt
        cpt += 1
        id_geometer = idnormalizer.normalize(
            ('geometer_%s%s' % (geometer[header_indexes['Nom']],
                                geometer[header_indexes['Prenom']])).replace(
                                    " ", ""))
        containerGeometers = api.content.get(path='/urban/geometricians')

        if id_geometer not in containerGeometers.objectIds():

            if not (id_geometer in containerGeometers.objectIds()):
                object_id = containerGeometers.invokeFactory(
                    'Geometrician',
                    id=id_geometer,
                    name1=geometer[header_indexes['Nom']],
                    name2=geometer[header_indexes['Prenom']],
                    phone=geometer[header_indexes['Telephone']],
                    gsm=geometer[header_indexes['Gsm']],
                    email=geometer[header_indexes['Email']],
                    street=geometer[header_indexes['Rue et Numero']],
                    zipcode=geometer[header_indexes['Code postal']],
                    city=geometer[header_indexes['Localite']])
Exemplo n.º 24
0
    def update(self):
        self.navroot_path = getNavigationRoot(self.context)
        self.data = {}

        tab = aq_inner(self.context)

        portal_type = getattr(self.context, 'portal_type', None)

        if hasattr(self.context, 'section') and (portal_type == 'collective.nitf.content' or
                                                 portal_type == 'openmultimedia.contenttypes.gallery'):

            section = self.context.section
            oid = idnormalizer.normalize(section, 'es')
            news_folder = getattr(self.context.portal_url, 'noticias', None)
            if news_folder:
                tab = getattr(news_folder, oid, None)

        #XXX this should be generalized... this hardcoded cases are so so lame.. sorry
        # if  getattr(self.context, 'portal_type', None) == 'collective.polls.poll':
        #     polls_folder = getattr(self.context.portal_url, 'encuestas', None)
        #     if polls_folder:
        #         tab = polls_folder

        if not tab:
            return

        strategy = getMultiAdapter((tab, Assignment(root=self.navroot_path)),
                                   INavtreeStrategy)
        queryBuilder = DropdownQueryBuilder(tab)
        query = queryBuilder()

        if query['path']['query'] != self.navroot_path:
            self.data = buildFolderTree(tab, obj=tab, query=query, strategy=strategy)
Exemplo n.º 25
0
def _createObject(context, event):
    parent = context.aq_parent
    id = context.getId()
    object_Ids = []
    catalog = getToolByName(context, 'portal_catalog')
    brains = catalog.unrestrictedSearchResults(object_provides = IPledgeCampaign.__identifier__)
    for brain in brains:
        object_Ids.append(brain.id)
    
    title = str(idnormalizer.normalize(context.title))
    temp_new_id = title
    new_id = temp_new_id.replace("-","")
    test = ''
    if new_id in object_Ids:
        test = filter(lambda name: new_id in name, object_Ids)
        if '-' not in (max(test)):
            new_id = new_id + '-1'
        if '-' in (max(test)):
            new_id = new_id +'-' +str(int(max(test).split('-')[-1])+1) 

    parent.manage_renameObject(id, new_id )
    new_title = title
    context.setTitle(context.title)

    context.reindexObject()
    return
Exemplo n.º 26
0
def _createObject(context, event):
    parent = context.aq_parent
    id = context.getId()
    object_Ids = []
    catalog = getToolByName(context, 'portal_catalog')
    # brains = catalog.unrestrictedSearchResults(object_provides = ISelfie.__identifier__)

    path = '/'.join(context.aq_parent.getPhysicalPath())
    brains = catalog.unrestrictedSearchResults(path={'query': path, 'depth' : 1})
    for brain in brains:
        object_Ids.append(brain.id)
    

    full_name = str(idnormalizer.normalize(context.full_name))
    test = ''
    num = 0
    if full_name in object_Ids:
        test = filter(lambda name: full_name in name, object_Ids)
        full_name = full_name +'-' + str(len(test))


    parent.manage_renameObject(id, full_name )
    context.setTitle(context.full_name)

    # behavior = IExcludeFromNavigation(context)
    # behavior.exclude_from_nav = True

    context.reindexObject()
    return
Exemplo n.º 27
0
def create_events_from_ics(self):
    filename = '/home/bschreiber/Downloads/adecalendar.ics'
    cal = Calendar.from_ical(open(filename,'rb').read())
    calendar_items = cal.walk()
    pwflow = self.portal_workflow
    events_folder = self.events
    buff = StringIO()
    num_events_created = 0
    for cal_item in calendar_items:
        if cal_item.name == 'VEVENT':
            title = cal_item['SUMMARY'].title()
            description = cal_item['DESCRIPTION'].title()
            organizer = cal_item['ORGANIZER'].title()
            location = cal_item['LOCATION'].title()
            start = cal_item['DTSTART'].dt
            end = cal_item['DTEND'].dt
            ev_id = idnormalizer.normalize(title)
            id_extension = 1
            keep_trying = True
            while keep_trying:
                try:
                    event_id = events_folder.invokeFactory('Event', id=ev_id, title=title)
                    ev_obj = events_folder[event_id]
                    ev_obj.setStartDate(start)
                    ev_obj.setEndDate(end)
                    ev_obj.setLocation(location)
                    ev_obj.setText(description)
                    keep_trying = False
                    num_events_created +=1
                    buff.write('Created event with id '+ev_id+'\n')
                except Exception, e: 
                    ev_id = ev_id[:len(ev_id)-2]+'-'+str(id_extension)
                    id_extension += 1
Exemplo n.º 28
0
def add_field(context, request, data):
    factory = data.get("factory", None)
    title = data.get("title", None)
    description = data.get("description", None)
    required = data.get("required", False)
    name = data.get("id", None)
    if not name:
        name = idnormalizer.normalize(title).replace("-", "_")

    klass = None
    vocabulary = queryUtility(IVocabularyFactory, name="Fields")
    for term in vocabulary(context):
        if factory not in (term.title, term.token):
            continue

        klass = term.value
        break

    if not klass:
        raise BadRequest("Missing/Invalid parameter factory: %s" % factory)

    add = queryMultiAdapter((context, request), name="add-field")
    properties = {
        "title": title,
        "__name__": name,
        "description": description,
        "factory": klass,
        "required": required,
    }

    field = add.form_instance.create(data=properties)
    add.form_instance.add(field)

    return get_info_for_field(context, request, name)
Exemplo n.º 29
0
    def save(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        newsitems = []
        for newsitem in self.request.get('newsitems', []):
            items = catalog(id=newsitem, portal_type='News Item')
            if items:
                newsitems.append(items[0].getObject())
        events = []
        site = getSite()
        adapted = IAnnotations(site).get('external_agenda', {})
        data = adapted.get('general', [])
        for item in data:
            if item['link'] in self.request.get('events', []):
                events.append(item)

        subject = u'Buletina {0}'.format(DateTime().strftime('%Y-%m-%d'))
        date = DateTime().strftime('%Y-%m-%d')
        toLocalizedTime = context.restrictedTraverse('@@plone').toLocalizedTime
        html = self._temp(self.request,
            **dict(newsitems=newsitems,
                events=events,
                subject=subject,
                date=date,
                toLocalizedTime=toLocalizedTime))

        id = idnormalizer.normalize(subject)
        buletin = context.invokeFactory(id=id,
                                        title=subject,
                                        type_name='Newsletter'
                    )
        buletin_object = context.get(buletin)
        buletin_object.text = RichTextValue(html, 'text/html', 'text/html')
        return buletin_object
    def __iter__(self):
        for item in self.previous:
            if not item.get('_data', False):
                yield item; continue
            if item.get('_type', None) != 'LdapUserFolder':
                yield item; continue
            for key in item['_data']:

                
                cn=key.split(',')[0][len('CN='):]
                users = self.acl_users.searchUsers(fullname=cn)
                for user in users:
                    
                    if user.get('dn','').decode(ENCODING) == key:
                        
                        self.acl_users.userFolderEditUser(
                            user['id'], None, item['_data'][key]['roles']
                            )
                        for groupid in item['_data'][key]['groups']:
                            groupid = idnormalizer.normalize(groupid)
                            for mid,  manager in self.group_plugins:
                                try:
                                    if manager\
                                       .addPrincipalToGroup(user['id'],
                                                            groupid):
                                        break
                                except:
                                    pass
Exemplo n.º 31
0
def rename(persona,event):
    parent = persona.aq_parent
    titulo=persona.apellido+' '+persona.nombre
    persona.setTitle(titulo)
    persona.reindexObject()
    id_nueva=idnormalizer.normalize(titulo)
    parent.manage_renameObject(persona.getId(), str(id_nueva)) 
def create_gallery(context):
    """ Create a Gallery with a random number of images on it. The Gallery
    will have a title; a resume (made of 3 sentences); and it will be
    classified with a random section.
    """
    title = generate_sentence(replace_dots=True)
    oid = idnormalizer.normalize(title, 'es')
    try:
        context.invokeFactory('openmultimedia.contenttypes.gallery', id=oid,
                              title=title)
    except:
        logger.info("An error occurred while creating the object '%s'" % oid)
        return

    gallery = context[oid]
    gallery.description = generate_sentences(3)
    gallery.text = RichTextValue(raw=generate_text(1))
    gallery.section = random_section(context)

    logger.debug("Gallery '%s' created in section '%s'" %
                 (title, gallery.section))

    random.seed()
    images = random.randint(4, 10)
    for i in range(images):
        create_image(gallery)

    logger.debug("Images created")

    workflowTool = getToolByName(context, 'portal_workflow')
    workflowTool.doActionFor(gallery, 'publish')

    logger.debug("Gallery published")
def create_poll(context):
    """ Create a Poll with 3 options on it; each option is given a random
    number of votes.
    """
    title = generate_sentence(replace_dots=True)
    oid = idnormalizer.normalize(title, 'es')
    try:
        context.invokeFactory('collective.polls.poll', id=oid, title=title)
    except:
        logger.info("An error occurred while creating the object '%s'" % oid)
        return

    poll = context[oid]
    poll.description = generate_sentences(3)
    options = [generate_sentence(replace_dots=True),
               generate_sentence(replace_dots=True),
               generate_sentence(replace_dots=True)]

    poll.options = set_options(options)

    random.seed()
    votes = random.sample(xrange(1000), 3)

    poll.annotations['option.00'], \
        poll.annotations['option.01'], \
        poll.annotations['option.02'] = votes

    logger.debug("Poll '%s' created" % title)

    workflowTool = getToolByName(context, 'portal_workflow')
    workflowTool.doActionFor(poll, 'open')
    workflowTool.doActionFor(poll, 'close')

    logger.debug("Poll opened and closed")
Exemplo n.º 34
0
def getCountriesVocabulary(self):
    translation_service = getSite().translation_service
    sorted_list = [x for x in COUNTRIES.iteritems()]
    sorted_list.append(('', ''))
    spanish_list = [(x[0], translation_service.translate(x[1], domain='plone', target_language='es')) for x in sorted_list]
    spanish_list.sort(key=lambda x: idn.normalize(x[1]))
    return DisplayList(spanish_list)
Exemplo n.º 35
0
def createFolder(context,
                 title,
                 allowed_types=['Topic', 'Folder', 'Document'],
                 exclude_from_nav=False):
    """Crea una carpeta en el contexto especificado y modifica su política de
    workflows; por omisión, la carpeta contiene colecciones (Topic) y no
    modifica la política de workflow del contenido creado dentro de ella.
    """
    oid = idnormalizer.normalize(title, 'es')
    if not hasattr(context, oid):
        context.invokeFactory('Folder', id=oid, title=title)
        folder = context[oid]
        folder.setConstrainTypesMode(constraintypes.ENABLED)
        folder.setLocallyAllowedTypes(allowed_types)
        folder.setImmediatelyAddableTypes(allowed_types)
        set_workflow_policy(folder)
        if exclude_from_nav:
            folder.setExcludeFromNav(True)
        folder.reindexObject()
    else:
        folder = context[oid]
        folder.setLocallyAllowedTypes(allowed_types)
        folder.setImmediatelyAddableTypes(allowed_types)
        # reindexamos para que el catálogo se entere de los cambios
        folder.reindexObject()
Exemplo n.º 36
0
 def __call__(self, context):
  terms = []
  for term in ['Strategie partecipate e integrate', 'Agricoltura', 'Edilizia e Urbanistica', 
             'Energia', 'Industria', 'Mobilità', 'Rifiuti', 'Territorio e Paesaggio', 'Turismo']:
     token=idnormalizer.normalize(term)
     terms.append(SimpleVocabulary.createTerm(term, token, term))
  return SimpleVocabulary(terms)
Exemplo n.º 37
0
def modifyobject(context, event):
    parent = context.aq_parent
    id = context.getId()
    object_Ids = []
    catalog = getToolByName(context, 'portal_catalog')
    path = '/'.join(context.aq_parent.getPhysicalPath())
    brains = catalog.unrestrictedSearchResults(path={'query': path, 'depth' : 1})
    for brain in brains:
        object_Ids.append(brain.id)
    
    email1 = str(idnormalizer.normalize(context.email1))
    new_id = email1.replace('-','_')
    
    test = ''
    num = 0
    if context.id != new_id:
        if new_id in object_Ids:
            test = filter(lambda name: new_id in name, object_Ids)
            new_id = new_id +'_' + str(len(test))
    
        parent.manage_renameObject(id, new_id )
        context.setTitle(new_id)
    
        #exclude from navigation code
        #behavior = IExcludeFromNavigation(context)
        #behavior.exclude_from_nav = True
    
        context.reindexObject()
    return
Exemplo n.º 38
0
def load_architects():

    csv_filename = 'blc_architects.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index)
                           for index, headercell in enumerate(lines.next())])
    cpt = 1
    for architect in lines:
        print "PROCESSING ARCHITECT %i" % cpt
        cpt += 1
        id_architect = idnormalizer.normalize(
            ('architect_%s%s' % (architect[header_indexes['Nom']],
                                 architect[header_indexes['Prenom']])).replace(
                                     " ", ""))
        containerArchitects = api.content.get(path='/urban/architects')

        if id_architect not in containerArchitects.objectIds():

            if not (id_architect in containerArchitects.objectIds()):
                object_id = containerArchitects.invokeFactory(
                    'Architect',
                    id=id_architect,
                    name1=architect[header_indexes['Nom']],
                    name2=architect[header_indexes['Prenom']],
                    phone=architect[header_indexes['Telephone']],
                    gsm=architect[header_indexes['Gsm']],
                    email=architect[header_indexes['Email']],
                    street=architect[header_indexes['Rue et Numero']],
                    zipcode=architect[header_indexes['Code postal']],
                    city=architect[header_indexes['Localite']])
def _createObj(context, event):
    parent = context.aq_parent
    column = getUtility(IPortletManager, name=u'plone.leftcolumn', context=context)
    manager = getMultiAdapter((context, column,), IPortletAssignmentMapping)
    assignment = burgermenuportlet.Assignment()
    chooser = INameChooser(manager)
    assignment.path = '/'.join(context.getPhysicalPath())
    manager[chooser.chooseName(None, assignment)] = assignment

    id = context.getId()
    object_Ids = []
    catalog = getToolByName(context, 'portal_catalog')
    brains = catalog.unrestrictedSearchResults(object_provides = IPilgrimageApp.__identifier__)
    for brain in brains:
        object_Ids.append(brain.id)
    
    last_name = str(idnormalizer.normalize(context.title))
    temp_new_id = last_name
    new_id = temp_new_id.replace("-","")
    test = ''
    if new_id in object_Ids:
        test = filter(lambda name: new_id in name, object_Ids)
        if '-' not in (max(test)):
            new_id = new_id + '-1'
        if '-' in (max(test)):
            new_id = new_id +'-' +str(int(max(test).split('-')[-1])+1) 

    parent.manage_renameObject(id, new_id )
    new_title = last_name
    context.setTitle(context.title)


    context.reindexObject()
    return
Exemplo n.º 40
0
def load_notaries():

    csv_filename = 'blc_notaires.csv'
    csv_filepath = '{}/{}'.format(IMPORT_FOLDER_PATH, csv_filename)
    csv_file = open(csv_filepath)
    lines = csv.reader(csv_file)

    header_indexes = dict([(headercell.strip(), index)
                           for index, headercell in enumerate(lines.next())])
    cpt = 1
    for notary in lines:
        print "PROCESSING NOTARY %i" % cpt
        cpt += 1
        id_notary = idnormalizer.normalize(
            ('notary_%s%s' % (notary[header_indexes['Nom']],
                              notary[header_indexes['Prenom']])).replace(
                                  " ", ""))
        containerNotaries = api.content.get(path='/urban/notaries')

        if id_notary not in containerNotaries.objectIds():

            if not (id_notary in containerNotaries.objectIds()):
                object_id = containerNotaries.invokeFactory(
                    'Notary',
                    id=id_notary,
                    name1=notary[header_indexes['Nom']],
                    name2=notary[header_indexes['Prenom']],
                    phone=notary[header_indexes['Telephone']],
                    street='%s %s' % (notary[header_indexes['Adresse1']],
                                      notary[header_indexes['Adresse2']]),
                    zipcode=notary[header_indexes['Code_postal']],
                    city=notary[header_indexes['Ville']])
Exemplo n.º 41
0
    def response_import(self, result):
        if not result[
                'CreatedByUser']:  ### edgecase when result['CreatedByUser'] is None
            result['CreatedByUser'] = {u'DisplayName': u''}

        f = DRMKCItem(result)
        import_id = f.Id
        last_modified = DateTime(f.LastModifiedOnDate)
        shortname = idnormalizer.normalize(f.Title, None, 500)
        print(shortname)

        try:
            original = self.container[shortname]
        except KeyError:
            return self.create_obj(f, shortname, import_id)

        annot = getattr(original.aq_inner.aq_self, '__annotations__', {})
        test_id = annot.get('original_import_id')

        if (test_id == import_id) and (last_modified > original.modified()):
            return self.update_obj(f, shortname)
        else:
            if not hasattr(original.aq_inner.aq_self, '__annotations__'):
                original.__annotations__ = PersistentMapping()

            original.__annotations__['original_import_id'] = import_id
            raise NoUpdates
Exemplo n.º 42
0
 def mapTitle(self, line):
     doc_id = self.getData('CADDIV') + self.getData('CADSEC') + self.getData('CADNUM')
     if not doc_id or '?' in doc_id:
         raise NoObjectToCreateException
     # doc_id = document_path.split('\\')[-1]
     doc_id = idnormalizer.normalize(doc_id)
     return doc_id
Exemplo n.º 43
0
def createDocument(context, title):
    """Crea y publica un documento (página) en el contexto dado.
    """
    oid = idnormalizer.normalize(title, 'es')
    if not hasattr(context, oid):
        context.invokeFactory('Document', id=oid, title=title)
        document = context[oid]
        document.reindexObject()
 def get_terms(self, context):
     for item in self.get_items():
         title = item['title']
         token = idnormalizer.normalize(title)
         value = item['name']
         yield SimpleTerm(value=value,
                          token=token,
                          title=title)
Exemplo n.º 45
0
    def participantsWithcolumnOrder(self, attendance=[]):

        participants = self.participants(attendance)
        orderparticipants = {'headers': [], 'rows': []}

        try:
            headers = participants['headers']
            for j in range(0, len(headers)):
                orderparticipants['headers'].append('')

            for header in headers:
                orderparticipants['headers'][self.positionlabelfield(
                    header)] = header

            rows = participants['rows']
            for row in rows:
                orderrow = []
                for j in range(0, len(row)):
                    orderrow.append('')

                orderrow[0] = row[0]  # this column is the UID
                orderrow[1] = row[1]  # this column is the url
                k = 2
                for header in headers:
                    position = self.positionlabelfield(header)
                    orderrow[position + 2] = row[k]
                    k += 1
                orderparticipants['rows'].append(orderrow)

        except Exception:
            return participants

        hotels = {
            u'Los Laureles': 1,
            u'Angel Inn': 2,
            u'Sin Hotel': 3,
        }
        aux_applications = [
            (app, hotels.get(app[10], 4), idnormalizer.normalize(app[7]),
             idnormalizer.normalize(app[3]), idnormalizer.normalize(app[4]))
            for app in orderparticipants['rows']
        ]
        aux_sorted = sorted(aux_applications, key=itemgetter(1, 2, 3, 4))
        orows = [i[0] for i in aux_sorted]
        orderparticipants['rows'] = orows
        return orderparticipants
Exemplo n.º 46
0
 def last_cr4project(obj):
     project_id = idnormalizer.normalize(obj.project_id or obj.project.name, max_length=100)
     last = session.query(CustomerRequest.uid)\
                 .filter_by(project_id=project_id)\
                 .order_by(CustomerRequest.uid.desc()).first()
     if last: new_uid = last.uid + 1
     else: new_uid = 1
     return project_id, new_uid
Exemplo n.º 47
0
 def update(self):
     super(GlobalStatusMessage, self).update()
     self.status = IStatusMessage(self.request)
     messages = self.status.show()
     for m in messages:
         m.id = idnormalizer.normalize(m.message)
     self.messages = messages
     self.closetext = _(u"button_close", default=u"Close")
Exemplo n.º 48
0
 def status_messages(self):
     """
     Returns status messages if any
     """
     messages = IStatusMessage(self.request)
     m = messages.show()
     for item in m:
         item.id = idnormalizer.normalize(item.message)
     return m
Exemplo n.º 49
0
    def test_read(self):
        ePubReader = EPubReader(dummy_epub())
        chapters = ePubReader.getChapters()
        self.assertEqual(len(chapters), 12)
        self.assertEqual(chapters[0]['title'], u'I. Down the Rabbit-Hole')

        title = chapters[0]['title']
        id = idnormalizer.normalize(title)
        self.assertEqual(chapters[0]['id'], id)
Exemplo n.º 50
0
 def churchValues(self):
     registry = getUtility(IRegistry)
     settings = registry.forInterface(IChurchMemberDGForm, check=False)
     contents = {}
     if settings.church_member:
         for val in settings.church_member:
             cmv = unicode(
                 idnormalizer.normalize(val['church_member_values']))
             if cmv not in contents.keys():
                 contents[cmv] = val['church_member_values']
     return contents
Exemplo n.º 51
0
    def createArchitect(name):

        idArchitect = idnormalizer.normalize(name + 'Architect').replace(" ", "")
        containerArchitects = api.content.get(path='/urban/architects')

        if idArchitect not in containerArchitects.objectIds():
            new_id = idArchitect
            new_name1 = name

            if not (new_id in containerArchitects.objectIds()):
                    object_id = containerArchitects.invokeFactory('Architect', id=new_id,
                                                        name1=new_name1)
Exemplo n.º 52
0
    def getBook(self, bookTitle):
        if self.book is not None:
            return self.book

        id = idnormalizer.normalize(bookTitle)
        book = self.bookContainer.get(id, None)
        if book is None:
            book = api.content.create(
                type='Book',
                title=bookTitle,
                container=self.bookContainer,
            )
        return book
Exemplo n.º 53
0
 def __call__(self):
     maschine = self.request.get('maschine')
     contentid = idnormalizer.normalize(maschine)
     mycontext = self.context[contentid]
     c = self.createpdf(contentid)
     c = self.drawpdf(c, mycontext)
     c = self.savepdf(c)
     myfile = open('/tmp/%s.pdf' % contentid, 'r')
     myfile.seek(0)
     RESPONSE = self.request.response
     RESPONSE.setHeader('content-type', 'application/pdf')
     RESPONSE.setHeader('content-disposition', 'attachment; filename=%s.pdf' %contentid)
     return myfile.read()
Exemplo n.º 54
0
    def createGeometrician(name1, name2):

        idGeometrician = idnormalizer.normalize(name1 + name2 + 'Geometrician').replace(" ", "")
        containerGeometricians = api.content.get(path='/urban/geometricians')

        if idGeometrician not in containerGeometricians.objectIds():
            new_id = idGeometrician
            new_name1 = name1
            new_name2 = name2

            if not (new_id in containerGeometricians.objectIds()):
                    object_id = containerGeometricians.invokeFactory('Geometrician', id=new_id,
                                                        name1=new_name1,
                                                        name2=new_name2)
Exemplo n.º 55
0
    def __call__(self, context=None):

        terms = self.vocab_vcge()
        assuntos_vcge = [{
            'value': term.title,
            'title': term.title
        } for term in terms]
        assuntos_vcge.sort()
        vocab = []
        for assunto in assuntos_vcge:
            vocab.append(
                SimpleTerm(value=idnormalizer.normalize(assunto['value'],
                                                        max_length=200),
                           title=assunto['title']))
        return SimpleVocabulary(vocab)
Exemplo n.º 56
0
    def getChapters(self):
        openedFile = self.file.open()
        self.zipFile = zipfile.ZipFile(openedFile)
        contents = self.zipFile.namelist()

        tocFileName = False
        for filename in contents:
            if filename[-4:] == '.ncx':
                tocFileName = filename
                break

        if tocFileName is False:
            logging.error('[ePub reader] No TOC found')
            return []

        tocFile = self.zipFile.open(tocFileName)
        tocContent = tocFile.read()
        tocXML = etree.fromstring(tocContent)

        chaptersXML = tocXML.xpath(
            '//x:navPoint',
            namespaces={'x': 'http://www.daisy.org/z3986/2005/ncx/'})

        chapters = []
        for chapterXML in chaptersXML:
            titleXML = chapterXML.find('{http://www.daisy.org/z3986/2005/ncx/}navLabel')
            title = titleXML.find('{http://www.daisy.org/z3986/2005/ncx/}text').text
            contentXML = chapterXML.find('{http://www.daisy.org/z3986/2005/ncx/}content')
            src = contentXML.get('src')

            chapterFile = self.zipFile.open(src)
            content = chapterFile.read()

            parser = etree.HTMLParser(encoding='utf-8')
            contentHTML = etree.fromstring(content, parser=parser)
            content = ''.join(contentHTML.itertext())

            id = idnormalizer.normalize(title)
            chapters.append({
                'id': id,
                'title': title,
                'content': content,
            })

        openedFile.close()
        return chapters
Exemplo n.º 57
0
 def __call__(self):
     data = {}
     body = self.request.get('BODY')
     if body:
         body_unicode = self.request.get('BODY').decode('utf-8')
         data = json.loads(body_unicode)
         if data:
             contentid = idnormalizer.normalize(data.get('maschine').get('title'))
             mycontext = self.context[data.get('keyword')]
             checkdaten = {}
             checkdaten[data.get('id')] = data.get('optionen')
             notizdaten = {}
             notizdaten[data.get('id')] = data.get('notiz', u'')
             if not mycontext.has_key(contentid):
                 obj = api.content.create(
                     type='Ergebnisdaten',
                     id = contentid,
                     title = data.get('maschine').get('title'),
                     maschnr = data.get('maschine').get('maschnr'),
                     hersteller = data.get('maschine').get('hersteller'),
                     fragebogen = data.get('fragebogen'),
                     history = [data.get('id')],
                     notizen = notizdaten,
                     fortschritt = float(data.get('fortschritt', 0.0)),
                     daten = checkdaten,
                     container=mycontext)
             else:
                 obj = mycontext[contentid]
                 checkdaten = obj.daten
                 checkdaten[data.get('id')] = data.get('optionen')
                 obj.daten = checkdaten
                 history = obj.history
                 if not history:
                     history = []
                 history.append(data.get('id'))
                 obj.history = history
                 notizdaten = obj.notizen
                 if not notizdaten:
                     notizdaten = {}
                 notizdaten[data.get('id')] = data.get('notiz', u'')
                 obj.notizen = notizdaten
                 obj.fortschritt = data.get('fortschritt', 0.0)
     retdict = data
     payload = jsonlib.write(retdict)
     return payload
Exemplo n.º 58
0
def add_fieldset(context, request, data):
    name = data.get("id", None)
    title = data.get("title", None)
    description = data.get("description", None)

    if not name:
        name = idnormalizer.normalize(title).replace("-", "_")

    # Default is reserved
    if name == "default":
        return {}

    add = queryMultiAdapter((context, request), name="add-fieldset")
    properties = {"__name__": name, "label": title, "description": description}
    fieldset = add.form_instance.create(data=properties)
    add.form_instance.add(fieldset)

    return get_info_for_fieldset(context, request, name)
Exemplo n.º 59
0
    def create(self, data):

        id = idnormalizer.normalize(data['title'])
        id += '-' + str(int(time.time()))

        data.pop('pid')
        data['title'] = data['title']
        if data['description']:
            data['description'] = data['description']
        else:
            data['description'] = ''
        data['i18n_domain'] = 'plone'
        data['permissions'] = ('View',)
        data['visible'] = True
        data['url_expr'] = url_expression(data.get('url_expr'))

        action = Action(id, **data)
        return action