Beispiel #1
0
def backup_config_file(env, suffix):
    try:
        backup, f = create_unique_file(env.config.filename + suffix)
        f.close()
        shutil.copyfile(env.config.filename, backup)
        env.log.info("Saved backup of configuration file in %s", backup)
    except IOError as e:
        env.log.warn("Couldn't save backup of configuration file (%s)",
                     exception_to_unicode(e))
    def createComment(self, req, data):
        data['invalid'] = 5
        struct = ReviewCommentStruct(None)
        struct.IDParent = req.args.get('IDParent')
        struct.IDFile = req.args.get('IDFile')
        struct.LineNum = req.args.get('LineNum')
        struct.Author = util.get_reporter_id(req)
        struct.Text = req.args.get('Text')
        struct.DateCreate = int(time.time())

        if (struct.IDFile == None or struct.LineNum == None or
            struct.Author == None or struct.Text == None):

            return

        if (struct.IDFile == "" or struct.LineNum == "" or struct.Author == ""):
            return

        if (struct.Text == ""):
            return

        if (struct.IDParent == None or struct.IDParent == ""):
            struct.IDParent = "-1"

        #If there was a file uploaded with the comment, place it in the correct spot
        #The basic parts of this code were taken from the file upload portion of
        #the trac wiki code
	
        if req.args.has_key('FileUp'):
            upload = req.args['FileUp']
            if upload and upload.filename:
                self.path = os.path.join(self.env.path, 'attachments', 'CodeReview', urllib.quote(struct.IDFile))
                self.path = os.path.normpath(self.path) 
                size = 0
                if hasattr(upload.file, 'fileno'):
                    size = os.fstat(upload.file.fileno())[6]
                else:
                    size = upload.file.len
                if size != 0:
                    filename = urllib.unquote(upload.filename)
                    filename = filename.replace('\\', '/').replace(':', '/')
                    filename = os.path.basename(filename)
                    import sys, unicodedata
                    if sys.version_info[0] > 2 or (sys.version_info[0] == 2 and sys.version_info[1] >= 3):
                        filename = unicodedata.normalize('NFC',unicode(filename,'utf-8')).encode('utf-8')
                    attachments_dir = os.path.join(os.path.normpath(self.env.path),'attachments')
                    commonprefix = os.path.commonprefix([attachments_dir, self.path])
                    assert commonprefix == attachments_dir
                    if not os.access(self.path, os.F_OK):
                        os.makedirs(self.path)
                    path, targetfile = util.create_unique_file(os.path.join(self.path,filename))
                    try:
                        shutil.copyfileobj(upload.file, targetfile)
                        struct.AttachmentPath = os.path.basename(path)
                    finally:
                        targetfile.close()
        struct.save(self.env.get_db_cnx())
    def createComment(self, req):
        req.hdf["invalid"] = 5
        struct = ReviewCommentStruct(None)
        struct.IDParent = req.args.get("IDParent")
        struct.IDFile = req.args.get("IDFile")
        struct.LineNum = req.args.get("LineNum")
        struct.Author = util.get_reporter_id(req)
        struct.Text = req.args.get("Text")
        struct.DateCreate = int(time.time())

        if (struct.IDFile == None) or (struct.LineNum == None) or (struct.Author == None) or (struct.Text == None):
            return
        if (struct.IDFile == "") or (struct.LineNum == "") or (struct.Author == ""):
            return
        if struct.Text == "":
            return
        if struct.IDParent == None or struct.IDParent == "":
            struct.IDParent = "-1"

        # If there was a file uploaded with the comment, place it in the correct spot
        # The basic parts of this code were taken from the file upload portion of
        # the trac wiki code

        if req.args.has_key("FileUp"):
            upload = req.args["FileUp"]
            if upload.filename:
                self.path = os.path.join(self.env.path, "attachments", "CodeReview", urllib.quote(struct.IDFile))
                self.path = os.path.normpath(self.path)
                size = 0
                if hasattr(upload.file, "fileno"):
                    size = os.fstat(upload.file.fileno())[6]
                else:
                    size = upload.file.len
                if size != 0:
                    filename = urllib.unquote(upload.filename)
                    filename = filename.replace("\\", "/").replace(":", "/")
                    filename = os.path.basename(filename)
                    import sys, unicodedata

                    if sys.version_info[0] > 2 or (sys.version_info[0] == 2 and sys.version_info[1] >= 3):
                        filename = unicodedata.normalize("NFC", unicode(filename, "utf-8")).encode("utf-8")
                    attachments_dir = os.path.join(os.path.normpath(self.env.path), "attachments")
                    commonprefix = os.path.commonprefix([attachments_dir, self.path])
                    assert commonprefix == attachments_dir
                    if not os.access(self.path, os.F_OK):
                        os.makedirs(self.path)
                    path, targetfile = util.create_unique_file(os.path.join(self.path, filename))
                    try:
                        shutil.copyfileobj(upload.file, targetfile)
                        struct.AttachmentPath = os.path.basename(path)
                    finally:
                        targetfile.close()

        struct.save(self.env.get_db_cnx())
    def insert(self, filename, fileobj, size, t=None, db=None):
        # FIXME: `t` should probably be switched to `datetime` too
        if not db:
            db = self.env.get_db_cnx()
            handle_ta = True
        else:
            handle_ta = False

        self.size = size and int(size) or 0
        timestamp = int(t or time.time())
        self.date = datetime.fromtimestamp(timestamp, utc)

        # Make sure the path to the attachment is inside the environment
        # attachments directory
        attachments_dir = os.path.join(os.path.normpath(self.env.path),
                                       'attachments')
        commonprefix = os.path.commonprefix([attachments_dir, self.path])
        assert commonprefix == attachments_dir

        if not os.access(self.path, os.F_OK):
            os.makedirs(self.path)
        filename = unicode_quote(filename)
        path, targetfile = create_unique_file(os.path.join(self.path,
                                                           filename))
        try:
            # Note: `path` is an unicode string because `self.path` was one.
            # As it contains only quoted chars and numbers, we can use `ascii`
            basename = os.path.basename(path).encode('ascii')
            filename = unicode_unquote(basename)

            cursor = db.cursor()
            cursor.execute("INSERT INTO attachment "
                           "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
                           (self.parent_realm, self.parent_id, filename,
                            self.size, timestamp, self.description,
                            self.author, self.ipnr))
            shutil.copyfileobj(fileobj, targetfile)
            self.resource.id = self.filename = filename

            self.env.log.info('New attachment: %s by %s', self.title,
                              self.author)

            if handle_ta:
                db.commit()

            targetfile.close()

            for listener in AttachmentModule(self.env).change_listeners:
                listener.attachment_added(self)

        finally:
            if not targetfile.closed:
                targetfile.close()
Beispiel #5
0
    def _create_file(self):
        """
        Create a file with a unique name in the thumbnail directory and opens it
        for writing. Doesn't actually write any data to the file.

        @raise: TracError if a file couldn't be created
        @return: 2-tuple: (filename, open writable file descriptor)
        """
        filename = os.path.join(self._img.gallery.thumb_path,
                                urllib.quote(os.path.split(self._img.path)[1]))
        try:
            return create_unique_file(filename)
        except Exception:
            # Couldn't come up with a unique filename, so try adding an MD5 hash
            # to make name unique
            to_hash = self._img.source.gallery_source_name() + '|' + filename
            parts = os.path.splitext(filename)
            hash_hex = md5.new(to_hash).hexdigest()
            filename = "%s.%s.%s" % (parts[0], hash_hex, parts[1])
            #try:
            if 1:
                return create_unique_file(filename)
Beispiel #6
0
    def _create_file(self):
        """
        Create a file with a unique name in the thumbnail directory and opens it
        for writing. Doesn't actually write any data to the file.

        @raise: TracError if a file couldn't be created
        @return: 2-tuple: (filename, open writable file descriptor)
        """
        filename = os.path.join(
            self._img.gallery.thumb_path,
            urllib.quote(os.path.split(self._img.path)[1])
            )
        try:
            return create_unique_file(filename)
        except Exception:
            # Couldn't come up with a unique filename, so try adding an MD5 hash
            # to make name unique
            to_hash = self._img.source.gallery_source_name() + '|' + filename
            parts = os.path.splitext(filename)
            hash_hex = md5.new(to_hash).hexdigest()
            filename = "%s.%s.%s" % (parts[0], hash_hex, parts[1])
            #try:
            if 1:
                return create_unique_file(filename)
Beispiel #7
0
    def insert(self, filename, fileobj, size, t=None, db=None):
        if not db:
            db = self.env.get_db_cnx()
            handle_ta = True
        else:
            handle_ta = False

        self.size = size and int(size) or 0
        self.time = int(t or time.time())

        # Make sure the path to the attachment is inside the environment
        # attachments directory
        attachments_dir = os.path.join(os.path.normpath(self.env.path),
                                       'attachments')
        commonprefix = os.path.commonprefix([attachments_dir, self.path])
        assert commonprefix == attachments_dir

        if not os.access(self.path, os.F_OK):
            os.makedirs(self.path)
        filename = unicode_quote(filename)
        path, targetfile = create_unique_file(os.path.join(
            self.path, filename))
        try:
            # Note: `path` is an unicode string because `self.path` was one.
            # As it contains only quoted chars and numbers, we can use `ascii`
            basename = os.path.basename(path).encode('ascii')
            filename = unicode_unquote(basename)

            cursor = db.cursor()
            cursor.execute(
                "INSERT INTO attachment "
                "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
                (self.parent_type, self.parent_id, filename, self.size,
                 self.time, self.description, self.author, self.ipnr))
            shutil.copyfileobj(fileobj, targetfile)
            self.filename = filename

            self.env.log.info('New attachment: %s by %s', self.title,
                              self.author)

            if handle_ta:
                db.commit()

            for listener in AttachmentModule(self.env).change_listeners:
                listener.attachment_added(self)

        finally:
            targetfile.close()
Beispiel #8
0
    def insert(self, filename, fileobj, size, t=None, db=None):
        if not db:
            db = self.env.get_db_cnx()
            handle_ta = True
        else:
            handle_ta = False

        # Maximum attachment size (in bytes)
        max_size = int(self.env.config.get('attachment', 'max_size'))
        if max_size >= 0 and size > max_size:
            raise TracError('Maximum attachment size: %d bytes' % max_size,
                            'Upload failed')
        self.size = size
        self.time = t or time.time()

        # Make sure the path to the attachment is inside the environment
        # attachments directory
        attachments_dir = os.path.join(os.path.normpath(self.env.path),
                                       'attachments')
        commonprefix = os.path.commonprefix([attachments_dir, self.path])
        assert commonprefix == attachments_dir

        if not os.access(self.path, os.F_OK):
            os.makedirs(self.path)
        filename = urllib.quote(filename)
        try:
            path, targetfile = util.create_unique_file(
                os.path.join(self.path, filename))
            filename = urllib.unquote(os.path.basename(path))

            cursor = db.cursor()
            cursor.execute(
                "INSERT INTO attachment "
                "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
                (self.parent_type, self.parent_id, filename, self.size,
                 self.time, self.description, self.author, self.ipnr))
            shutil.copyfileobj(fileobj, targetfile)
            self.filename = filename

            self.env.log.info('New attachment: %s by %s', self.title,
                              self.author)
            if handle_ta:
                db.commit()
        finally:
            targetfile.close()
Beispiel #9
0
def do_upgrade(env, version, cursor):
    """Automatically enable tracopt.versioncontrol.svn.* components,
    unless they were explicitly disabled or the new svn components are
    already enabled.
    """
    enable = [c for c in _svn_components
              if env.is_component_enabled(_old_path + c) and
              not env.is_component_enabled(_new_path + c)]
    if not enable:
        return
    try:
        backup, f = create_unique_file(env.config.filename
                                       + '.tracopt-svn.bak')
        f.close()
        shutil.copyfile(env.config.filename, backup)
        env.log.info("Saved backup of configuration file in %s", backup)
    except IOError, e:
        env.log.warn("Couldn't save backup of configuration file (%s)",
                     exception_to_unicode(e))
Beispiel #10
0
def do_upgrade(env, version, cursor):
    """Automatically enable tracopt.versioncontrol.svn.* components,
    unless they were explicitly disabled or the new svn components are
    already enabled.
    """
    enable = [
        c for c in _svn_components if env.is_component_enabled(_old_path + c)
        and not env.is_component_enabled(_new_path + c)
    ]
    if not enable:
        return
    try:
        backup, f = create_unique_file(env.config.filename +
                                       '.tracopt-svn.bak')
        f.close()
        shutil.copyfile(env.config.filename, backup)
        env.log.info("Saved backup of configuration file in %s", backup)
    except IOError, e:
        env.log.warn("Couldn't save backup of configuration file (%s)",
                     exception_to_unicode(e))