Example #1
0
def updata(self):
    """Convert SiteAccess objects from 1.x to 2.x"""
    _cvt_btr(self.REQUEST['PARENTS'][-1])
    from App.Dialogs import MessageDialog
    return MessageDialog(title='Update Complete', message='Update Complete!',
                         action='./manage_main')
Example #2
0
    def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None):
        """Paste previously copied objects into the current object,
           making folders into chapters and RhaptosModuleEditors into
           ContentPointers (and not destroying their originals).
           Other objects will be as usual.
           Largely copied from OFS.CopySupport.
           If calling manage_pasteObjects from python code, pass
           the result of a previous call to manage_cutObjects or
           manage_copyObjects as the first argument."""
        cp = None
        if cb_copy_data is not None:
            cp = cb_copy_data
        else:
            if REQUEST and REQUEST.has_key('__cp'):
                cp = REQUEST['__cp']
        if cp is None:
            raise CopyError, eNoData

        try:
            cp = _cb_decode(cp)
        except:
            raise CopyError, eInvalid

        oblist = []
        op = cp[0]
        app = self.getPhysicalRoot()
        result = []
        duplicates = []

        for mdata in cp[1]:
            m = Moniker.loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except:
                raise CopyError, eNotFound
            oblist.append(ob)

        for ob in oblist:
            self._verifyObjectPaste(ob)

        if op == 0:
            # Copy operation
            for ob in oblist:
                if not ob.cb_isCopyable():
                    raise CopyError, eNotSupported % ob.getId()
                try:
                    ob._notifyOfCopyTo(self, op=0)
                except:
                    raise CopyError, MessageDialog(title='Copy Error',
                                                   message=sys.exc_info()[1],
                                                   action='manage_main')
                #ob=ob._getCopy(self)
                orig_id = ob.getId()
                id = self._get_id(ob.getId())
                ob, dupes = self._getTransformCopy(ob, op, id, self)  # NEW
                duplicates.extend(dupes)
                if ob:
                    result.append({'id': orig_id, 'new_id': id})
                    #ob._setId(id)
                    #self._setObject(id, ob)
                    #ob = self._getOb(id)
                    ob.manage_afterClone(ob)

            if REQUEST is not None:
                return self.manage_main(self,
                                        REQUEST,
                                        update_menu=1,
                                        cb_dataValid=1)

        if op == 1:
            # Move operation
            for ob in oblist:
                id = ob.getId()
                if not ob.cb_isMoveable():
                    raise CopyError, eNotSupported % id
                try:
                    ob._notifyOfCopyTo(self, op=1)
                except:
                    raise CopyError, MessageDialog(title='Move Error',
                                                   message=sys.exc_info()[1],
                                                   action='manage_main')
                if not sanity_check(self, ob):
                    raise CopyError, 'This object cannot be pasted into itself'

                ### NEW BELOW ###
                if self._transformableType(ob):
                    # do the "copy" procedure
                    orig_id = ob.getId()
                    id = self._get_id(ob.getId())
                    ob, dupes = self._getTransformCopy(ob, op, id)
                    duplicates.extend(dupes)
                    if ob:
                        result.append({'id': orig_id, 'new_id': id})
                        ob.manage_afterClone(ob)
                else:
                    ### NEW ABOVE (below is ++indented compared to original) ###
                    # try to make ownership explicit so that it gets carried
                    # along to the new location if needed.
                    old = ob
                    orig_id = ob.getId()
                    id = self._get_id(ob.getId())
                    ob, dupes = self._getTransformCopy(ob, op, id)
                    duplicates.extend(dupes)
                    if ob:
                        result.append({'id': orig_id, 'new_id': id})
                        ob.manage_afterClone(ob)

                    aq_parent(aq_inner(old))._delObject(id)

            if REQUEST is not None:
                REQUEST['RESPONSE'].setCookie(
                    '__cp',
                    'deleted',
                    path='%s' % cookie_path(REQUEST),
                    expires='Wed, 31-Dec-97 23:59:59 GMT')
                REQUEST['__cp'] = None
                return self.manage_main(self,
                                        REQUEST,
                                        update_menu=1,
                                        cb_dataValid=0)

        if duplicates:
            raise "DuplicateError", duplicates

        return result
Example #3
0
def async_rename(context, success_event, fail_event, **kwargs):
    """ Async rename job
    """
    newids = kwargs.get('new_ids', [])
    newtitles = kwargs.get('new_titles', [])
    paths = kwargs.get('paths', [])
    email = kwargs.get('email', [])
    anno = IAnnotations(context)
    job_id = anno.get('async_move_job')
    context_rel_path = context.absolute_url(1)

    if not newids:
        wrapper = IContextWrapper(context)(error=u'Invalid newid')
        notify(fail_event(wrapper))
        raise ValueError(eNoItemsSpecified)
    wrapper = IContextWrapper(context)(
        folder_move_from=context_rel_path,
        folder_move_to=', '.join(newids),
        folder_move_objects=', '.join(paths),
        asyncmove_email=email,
        email=email
    )
    obdict = {}
    try:
        for i, v in enumerate(newids):
            obdict[v] = newtitles[i]
        notify(AsyncMoveSaveProgress(
                context, operation='initialize', operation_type='Renamed',
                job_id=job_id, oblist_id=[(o, obdict[o]) for o in obdict]))
        _success, failure = renameObjectsByPaths(context, paths,
                                                 newids, newtitles)
        if failure:
            for obj_path in failure:
                foid = obj_path.split('/')[-1]
                if foid in obdict:
                    del obdict[foid]
                notify(AsyncMoveSaveProgress(
                    context,
                    operation='sub_progress',
                    job_id=job_id,
                    obj_id=foid,
                    progress=0.5
                ))
    except Exception, err:
        logger.exception(err)
        wrapper.error = err.message
        wrapper.job_id = job_id
        for oid in obdict:
            notify(AsyncMoveSaveProgress(
                context,
                operation='sub_progress',
                job_id=job_id,
                obj_id=oid,
                progress=.75
            ))

        notify(AsyncMoveSaveProgress(
            context,
            operation='progress',
            job_id=job_id,
            progress=.75
        ))

        notify(fail_event(wrapper))
        raise ValueError(MessageDialog(
            title='Error',
            message=err.message,
            action='manage_main',
        ))
Example #4
0
 def _setId(self, id):
     if id != self.id:
         raise ValueError(MessageDialog(
             title='Invalid Id',
             message='Cannot change the id of a UserFolder',
             action='./manage_main'))
Example #5
0
    def _verifyObjectPaste(self, object, validate_src=1):
        # Verify whether the current user is allowed to paste the
        # passed object into self. This is determined by checking
        # to see if the user could create a new object of the same
        # meta_type of the object passed in and checking that the
        # user actually is allowed to access the passed in object
        # in its existing context.
        #
        # Passing a false value for the validate_src argument will skip
        # checking the passed in object in its existing context. This is
        # mainly useful for situations where the passed in object has no
        # existing context, such as checking an object during an import
        # (the object will not yet have been connected to the acquisition
        # heirarchy).

        if not hasattr(object, 'meta_type'):
            raise CopyError(MessageDialog(
                  title   = 'Not Supported',
                  message = ('The object <em>%s</em> does not support this' \
                             ' operation' % escape(absattr(object.id))),
                  action  = 'manage_main'))

        if not hasattr(self, 'all_meta_types'):
            raise CopyError(MessageDialog(
                  title   = 'Not Supported',
                  message = 'Cannot paste into this object.',
                  action  = 'manage_main'))

        method_name = None
        mt_permission = None
        meta_types = absattr(self.all_meta_types)

        for d in meta_types:
            if d['name'] == object.meta_type:
                method_name = d['action']
                mt_permission = d.get('permission')
                break

        if mt_permission is not None:
            sm = getSecurityManager()

            if sm.checkPermission(mt_permission, self):
                if validate_src:
                    # Ensure the user is allowed to access the object on the
                    # clipboard.
                    try:
                        parent = aq_parent(aq_inner(object))
                    except:
                        parent = None

                    if not sm.validate(None, parent, None, object):
                        raise Unauthorized(absattr(object.id))

                    if validate_src == 2: # moving
                        if not sm.checkPermission(delete_objects, parent):
                            raise Unauthorized('Delete not allowed.')
            else:
                raise CopyError(MessageDialog(
                    title = 'Insufficient Privileges',
                    message = ('You do not possess the %s permission in the '
                               'context of the container into which you are '
                               'pasting, thus you are not able to perform '
                               'this operation.' % mt_permission),
                    action = 'manage_main'))
        else:
            raise CopyError(MessageDialog(
                title = 'Not Supported',
                message = ('The object <em>%s</em> does not support this '
                           'operation.' % escape(absattr(object.id))),
                action = 'manage_main'))
Example #6
0
def unrestricted_move(self, ob):
    """Move an object from one container to another bypassing certain
    checks."""
    orig_id = ob.getId()
    if not ob.cb_isMoveable():
        raise CopyError('Not supported {}'.format(escape(orig_id)))

    try:
        ob._notifyOfCopyTo(self, op=1)
    except ConflictError:
        raise
    except:
        raise CopyError(
            MessageDialog(title="Move Error",
                          message=sys.exc_info()[1],
                          action='manage_main'))

    if not sanity_check(self, ob):
        raise CopyError("This object cannot be pasted into itself")

    orig_container = aq_parent(aq_inner(ob))
    if aq_base(orig_container) is aq_base(self):
        id = orig_id
    else:
        id = self._get_id(orig_id)

    notify(ObjectWillBeMovedEvent(ob, orig_container, orig_id, self, id))

    # try to make ownership explicit so that it gets carried
    # along to the new location if needed.
    ob.manage_changeOwnershipType(explicit=1)

    try:
        orig_container._delObject(orig_id, suppress_events=True)
    except TypeError:
        # BBB: removed in Zope 2.11
        orig_container._delObject(orig_id)
        warnings.warn(
            "%s._delObject without suppress_events is deprecated "
            "and will be removed in Zope 2.11." %
            orig_container.__class__.__name__, DeprecationWarning)
    ob = aq_base(ob)
    ob._setId(id)

    try:
        self._setObject(id, ob, set_owner=0, suppress_events=True)
    except TypeError:
        # BBB: removed in Zope 2.11
        self._setObject(id, ob, set_owner=0)
        warnings.warn(
            "%s._setObject without suppress_events is deprecated "
            "and will be removed in Zope 2.11." % self.__class__.__name__,
            DeprecationWarning)
    ob = self._getOb(id)

    notify(ObjectMovedEvent(ob, orig_container, orig_id, self, id))
    notifyContainerModified(orig_container)
    if aq_base(orig_container) is not aq_base(self):
        notifyContainerModified(self)

    ob._postCopy(self, op=1)
    # try to make ownership implicit if possible
    ob.manage_changeOwnershipType(explicit=0)
Example #7
0
    def manage_renameObject(self, id, new_id, REQUEST=None):
        """Rename a particular sub-object.
        """
        try:
            self._checkId(new_id)
        except:
            raise CopyError(MessageDialog(
                title='Invalid Id',
                message=sys.exc_info()[1],
                action ='manage_main'))

        ob = self._getOb(id)

        if ob.wl_isLocked():
            raise ResourceLockedError('Object "%s" is locked via WebDAV'
                                        % ob.getId())
        if not ob.cb_isMoveable():
            raise CopyError(eNotSupported % escape(id))
        self._verifyObjectPaste(ob)

        try:
            ob._notifyOfCopyTo(self, op=1)
        except ConflictError:
            raise
        except:
            raise CopyError(MessageDialog(
                title="Rename Error",
                message=sys.exc_info()[1],
                action ='manage_main'))

        notify(ObjectWillBeMovedEvent(ob, self, id, self, new_id))

        try:
            self._delObject(id, suppress_events=True)
        except TypeError:
            self._delObject(id)
            warnings.warn(
                "%s._delObject without suppress_events is discouraged." %
                self.__class__.__name__, DeprecationWarning)
        ob = aq_base(ob)
        ob._setId(new_id)

        # Note - because a rename always keeps the same context, we
        # can just leave the ownership info unchanged.
        try:
            self._setObject(new_id, ob, set_owner=0, suppress_events=True)
        except TypeError:
            self._setObject(new_id, ob, set_owner=0)
            warnings.warn(
                "%s._setObject without suppress_events is discouraged." %
                self.__class__.__name__, DeprecationWarning)
        ob = self._getOb(new_id)

        notify(ObjectMovedEvent(ob, self, id, self, new_id))
        notifyContainerModified(self)

        ob._postCopy(self, op=1)

        if REQUEST is not None:
            return self.manage_main(self, REQUEST, update_menu=1)
        return None
Example #8
0
    def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None):
        """Paste previously copied objects into the current object.

        If calling manage_pasteObjects from python code, pass the result of a
        previous call to manage_cutObjects or manage_copyObjects as the first
        argument.

        Also sends IObjectCopiedEvent and IObjectClonedEvent
        or IObjectWillBeMovedEvent and IObjectMovedEvent.
        """
        if cb_copy_data is not None:
            cp = cb_copy_data
        elif REQUEST is not None and REQUEST.has_key('__cp'):
            cp = REQUEST['__cp']
        else:
            cp = None
        if cp is None:
            raise CopyError(eNoData)

        try:
            op, mdatas = _cb_decode(cp)
        except:
            raise CopyError(eInvalid)

        oblist = []
        app = self.getPhysicalRoot()
        for mdata in mdatas:
            m = loadMoniker(mdata)
            try:
                ob = m.bind(app)
            except ConflictError:
                raise
            except:
                raise CopyError(eNotFound)
            self._verifyObjectPaste(ob, validate_src=op+1)
            oblist.append(ob)

        result = []
        if op == 0:
            # Copy operation
            for ob in oblist:
                orig_id = ob.getId()
                if not ob.cb_isCopyable():
                    raise CopyError(eNotSupported % escape(orig_id))

                try:
                    ob._notifyOfCopyTo(self, op=0)
                except ConflictError:
                    raise
                except:
                    raise CopyError(MessageDialog(
                        title="Copy Error",
                        message=sys.exc_info()[1],
                        action='manage_main'))

                id = self._get_id(orig_id)
                result.append({'id': orig_id, 'new_id': id})

                orig_ob = ob
                ob = ob._getCopy(self)
                ob._setId(id)
                notify(ObjectCopiedEvent(ob, orig_ob))

                self._setObject(id, ob)
                ob = self._getOb(id)
                ob.wl_clearLocks()

                ob._postCopy(self, op=0)

                compatibilityCall('manage_afterClone', ob, ob)

                notify(ObjectClonedEvent(ob))

            if REQUEST is not None:
                return self.manage_main(self, REQUEST, update_menu=1,
                                        cb_dataValid=1)

        elif op == 1:
            # Move operation
            for ob in oblist:
                orig_id = ob.getId()
                if not ob.cb_isMoveable():
                    raise CopyError(eNotSupported % escape(orig_id))

                try:
                    ob._notifyOfCopyTo(self, op=1)
                except ConflictError:
                    raise
                except:
                    raise CopyError(MessageDialog(
                        title="Move Error",
                        message=sys.exc_info()[1],
                        action='manage_main'))

                if not sanity_check(self, ob):
                    raise CopyError(
                            "This object cannot be pasted into itself")

                orig_container = aq_parent(aq_inner(ob))
                if aq_base(orig_container) is aq_base(self):
                    id = orig_id
                else:
                    id = self._get_id(orig_id)
                result.append({'id': orig_id, 'new_id': id})

                notify(ObjectWillBeMovedEvent(ob, orig_container, orig_id,
                                              self, id))

                # try to make ownership explicit so that it gets carried
                # along to the new location if needed.
                ob.manage_changeOwnershipType(explicit=1)

                try:
                    orig_container._delObject(orig_id, suppress_events=True)
                except TypeError:
                    orig_container._delObject(orig_id)
                    warnings.warn(
                        "%s._delObject without suppress_events is discouraged."
                        % orig_container.__class__.__name__,
                        DeprecationWarning)
                ob = aq_base(ob)
                ob._setId(id)

                try:
                    self._setObject(id, ob, set_owner=0, suppress_events=True)
                except TypeError:
                    self._setObject(id, ob, set_owner=0)
                    warnings.warn(
                        "%s._setObject without suppress_events is discouraged."
                        % self.__class__.__name__, DeprecationWarning)
                ob = self._getOb(id)

                notify(ObjectMovedEvent(ob, orig_container, orig_id, self, id))
                notifyContainerModified(orig_container)
                if aq_base(orig_container) is not aq_base(self):
                    notifyContainerModified(self)

                ob._postCopy(self, op=1)
                # try to make ownership implicit if possible
                ob.manage_changeOwnershipType(explicit=0)

            if REQUEST is not None:
                REQUEST['RESPONSE'].setCookie('__cp', 'deleted',
                                    path='%s' % cookie_path(REQUEST),
                                    expires='Wed, 31-Dec-97 23:59:59 GMT')
                REQUEST['__cp'] = None
                return self.manage_main(self, REQUEST, update_menu=1,
                                        cb_dataValid=0)

        return result
Example #9
0
<TR>
  <TD VALIGN="TOP">
  </TD>
  <TD VALIGN="TOP">
  <CENTER>
  <INPUT TYPE="SUBMIT" VALUE="   Ok   ">
  </CENTER>
  </TD>
</TR>
</TABLE>
</FORM>
</BODY></HTML>""", target='', action='manage_main', title='Changed')


eNoData=MessageDialog(
        title='No Data',
        message='No clipboard data found.',
        action ='manage_main',)

eInvalid=MessageDialog(
         title='Clipboard Error',
         message='The data in the clipboard could not be read, possibly due ' \
         'to cookie data being truncated by your web browser. Try copying ' \
         'fewer objects.',
         action ='manage_main',)

eNotFound=MessageDialog(
          title='Item Not Found',
          message='One or more items referred to in the clipboard data was ' \
          'not found. The item may have been moved or deleted after you ' \
          'copied it.',
          action ='manage_main',)
Example #10
0
    def manage_edit(self,
                    title: str,
                    data_dir: str,
                    connection_string: str = '',
                    new_database: str = '',
                    check=None,
                    REQUEST=None) -> str:
        """Change connection
        """
        if new_database:
            if os.path.exists(os.path.join(data_dir, new_database)):
                return MessageDialog(
                    title='Edited',
                    message=
                    (f'The database file <code>{new_database}</code> already exists<br>'
                     f'in {data_dir}!'),
                    action='./manage_properties')

            connection_string = new_database

        if data_dir != self.data_dir:  # data_dir is changed
            connection_string = '' or new_database

        if not os.path.exists(data_dir):
            return MessageDialog(
                title='Edited',
                message=(
                    f'The directory <code>{data_dir}</code> does not exist.<br>'
                    'Please create it on the file system.'),
                action='./manage_properties')

        self.data_dir = data_dir

        if connection_string:
            try:
                create_db_file(data_dir=data_dir,
                               connection_string=connection_string)
            except sqlite3_OperationalError as e:
                return MessageDialog(title='Edited',
                                     message=extract_error(e),
                                     action='./manage_properties')

            try:
                check_database(
                    dbpath=os.path.join(data_dir, connection_string))
            except sqlite3_OperationalError as e:
                if self.connection_string == connection_string:
                    self.edit(title, '', check)
                return MessageDialog(title='Edited',
                                     message=extract_error(e),
                                     action='./manage_properties')

        if self.connected():
            self.manage_close_connection()

        self.edit(title, connection_string, check)

        if REQUEST is not None:
            esc_id = escape(self.id)
            return MessageDialog(
                title='Edited',
                message=f'<strong>{esc_id}</strong> has been edited.',
                action='./manage_properties')
Example #11
0
    def manage_sendReminder(self, name, email_from, email_subject,
                            remindertext):
        """ actually send the password reminder """
        try:
            user = self.getUser(name)
        except:
            return MessageDialog(
                            title  ='Illegal value',
                            message='The specified user does not exist',
                            action ='manage_main')
                            
        issuetrackerroot = self.getIssueTrackerRoot()
        
        if not email_from:
            raise "NoEmailFromError", "You must specify a from email address"
        elif not self.webmaster_email:
            self.webmaster_email = email_from

        email_to = user.getEmail()
        if not email_to or email_to and not Utils.ValidEmailAddress(email_to):
            raise "NoEmailToError", "User does not have a valid email address"
            
            
        replacement_key = "<password shown here>"
        if remindertext.find(replacement_key) == -1:
            raise "NoPasswordReplacementError",\
                  "No place to put the password reminder"
                  
        if self.encrypt_passwords:
            # generate a new password and save it
            password = Utils.getRandomString(length=6, loweronly=1)
            user.__ = password
        
        else:
            password = user.__
        
        if not email_subject:
            email_subject = "Issue Tracker password reminder"
        
        remindertext = remindertext.replace(replacement_key, password)
        
        # send it!
        

        if issuetrackerroot:
            # send via the issuetracker
            issuetrackerroot.sendEmail(remindertext, email_to, email_from, 
               email_subject, swallowerrors=False)
        else:
            body = '\r\n'.join(['From: %s'%email_from, 'To: %s'%email_to,
                                'Subject: %s'%email_subject, "", remindertext])
                            
            # Expect a mailhost object. Note that here we're outside the Issuetracker
            try:
                mailhost = self.MailHost
            except:
                try:
                    mailhost = self.SecureMailHost
                except:
                    try:
                        mailhost = self.superValues('MailHost')[0]
                    except IndexError:
                        raise "NoMailHostError", "No 'MailHost' available to send from"
            if hasattr(mailhost, 'secureSend'):
                mailhost.secureSend(remindertext, email_to, email_from, email_subject)
            else:
                mailhost.send(body, email_to, email_from, email_subject)
            
        m = "Password reminder sent to %s" % email_to
        return self.manage_main(self, self.REQUEST, manage_tabs_message=m)