def perform_request_delete(comID=-1, recID=-1, uid=-1, reviews="", ln=CFG_SITE_LANG):
    """
    """
    _ = gettext_set_language(ln)

    from search_engine import record_exists

    warnings = []

    ln = wash_language(ln)
    comID = wash_url_argument(comID, 'int')
    recID = wash_url_argument(recID, 'int')
    uid = wash_url_argument(uid, 'int')
    # parameter reviews is deduced from comID when needed

    if comID is not None and recID is not None and uid is not None:
        if comID <= 0 and recID <= 0 and uid <= 0:
            if comID != -1:
                try:
                    raise InvenioWebCommentWarning(_('Invalid comment ID.'))
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(("WRN_WEBCOMMENT_ADMIN_INVALID_COMID",))
            return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

        if comID > 0 and not recID > 0:
            comment = query_get_comment(comID)

            if comment:
                # Figure out if this is a review or a comment
                c_star_score = 5
                if comment[c_star_score] > 0:
                    reviews = 1
                else:
                    reviews = 0
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                try:
                    raise InvenioWebCommentWarning(_('Comment ID %s does not exist.') % comID)
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(('WRN_WEBCOMMENT_ADMIN_COMID_INEXISTANT', comID))
                return webcomment_templates.tmpl_admin_delete_form(ln, warnings)
Beispiel #2
0
    def add(self, req, form):
        """
        Add a comment (review) to record with id recid where recid>0
        Also works for adding a remark to basket with id recid where recid<-99
        @param ln: languange
        @param recid: record id
        @param action:  'DISPLAY' to display add form
                        'SUBMIT' to submit comment once form is filled
                        'REPLY' to reply to an already existing comment
        @param msg: the body of the comment/review or remark
        @param score: star score of the review
        @param note: title of the review
        @param comid: comment id, needed for replying
        @param editor_type: the type of editor used for submitting the
                            comment: 'textarea', 'ckeditor'.
        @param subscribe: if set, subscribe user to receive email
                          notifications when new comment are added to
                          this discussion
        @return the full html page.
        """
        argd = wash_urlargd(
            form, {
                'action': (str, "DISPLAY"),
                'msg': (str, ""),
                'note': (str, ''),
                'score': (int, 0),
                'comid': (int, 0),
                'editor_type': (str, ""),
                'subscribe': (str, ""),
                'cookie': (str, "")
            })
        _ = gettext_set_language(argd['ln'])

        actions = ['DISPLAY', 'REPLY', 'SUBMIT']
        uid = getUid(req)

        # Is site ready to accept comments?
        if uid == -1 or (not CFG_WEBCOMMENT_ALLOW_COMMENTS
                         and not CFG_WEBCOMMENT_ALLOW_REVIEWS):
            return page_not_authorized(req,
                                       "../comments/add",
                                       navmenuid='search')

        # Is user allowed to post comment?
        user_info = collect_user_info(req)
        (auth_code_1,
         auth_msg_1) = check_user_can_view_comments(user_info, self.recid)
        (auth_code_2,
         auth_msg_2) = check_user_can_send_comments(user_info, self.recid)
        if isGuestUser(uid):
            cookie = mail_cookie_create_authorize_action(
                VIEWRESTRCOLL, {
                    'collection': guess_primary_collection_of_a_record(
                        self.recid)
                })
            # Save user's value in cookie, so that these "POST"
            # parameters are not lost during login process
            msg_cookie = mail_cookie_create_common(
                'comment_msg', {
                    'msg': argd['msg'],
                    'note': argd['note'],
                    'score': argd['score'],
                    'editor_type': argd['editor_type'],
                    'subscribe': argd['subscribe']
                },
                onetime=True)
            target = '/youraccount/login' + \
                make_canonical_urlargd({'action': cookie, 'ln' : argd['ln'], 'referer' : \
                CFG_SITE_SECURE_URL + user_info['uri'] + '&cookie=' + msg_cookie}, {})
            return redirect_to_url(req, target, norobot=True)
        elif (auth_code_1 or auth_code_2):
            return page_not_authorized(req, "../", \
                text = auth_msg_1 + auth_msg_2)

        user_info = collect_user_info(req)
        can_attach_files = False
        (auth_code, auth_msg) = check_user_can_attach_file_to_comments(
            user_info, self.recid)
        if not auth_code and (user_info['email'] != 'guest'):
            can_attach_files = True

        warning_msgs = [
        ]  # list of warning tuples (warning_text, warning_color)
        added_files = {}
        if can_attach_files:
            # User is allowed to attach files. Process the files
            file_too_big = False
            formfields = form.get('commentattachment[]', [])
            if not hasattr(formfields,
                           "__getitem__"):  # A single file was uploaded
                formfields = [formfields]
            for formfield in formfields[:CFG_WEBCOMMENT_MAX_ATTACHED_FILES]:
                if hasattr(formfield, "filename") and formfield.filename:
                    filename = formfield.filename
                    dir_to_open = os.path.join(CFG_TMPDIR, 'webcomment',
                                               str(uid))
                    try:
                        assert (dir_to_open.startswith(CFG_TMPDIR))
                    except AssertionError:
                        register_exception(req=req,
                                           prefix='User #%s tried to upload file to forbidden location: %s' \
                                           % (uid, dir_to_open))

                    if not os.path.exists(dir_to_open):
                        try:
                            os.makedirs(dir_to_open)
                        except:
                            register_exception(req=req, alert_admin=True)

                    ## Before saving the file to disc, wash the filename (in particular
                    ## washing away UNIX and Windows (e.g. DFS) paths):
                    filename = os.path.basename(filename.split('\\')[-1])
                    filename = filename.strip()
                    if filename != "":
                        # Check that file does not already exist
                        n = 1
                        while os.path.exists(
                                os.path.join(dir_to_open, filename)):
                            basedir, name, extension = decompose_file(filename)
                            new_name = propose_next_docname(name)
                            filename = new_name + extension

                        fp = open(os.path.join(dir_to_open, filename), "w")
                        # FIXME: temporary, waiting for wsgi handler to be
                        # fixed. Once done, read chunk by chunk
                        ##                         while formfield.file:
                        ##                             fp.write(formfield.file.read(10240))
                        fp.write(formfield.file.read())
                        fp.close()
                        # Isn't this file too big?
                        file_size = os.path.getsize(
                            os.path.join(dir_to_open, filename))
                        if CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and \
                               file_size > CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE:
                            os.remove(os.path.join(dir_to_open, filename))
                            # One file is too big: record that,
                            # dismiss all uploaded files and re-ask to
                            # upload again
                            file_too_big = True
                            try:
                                raise InvenioWebCommentWarning(
                                    _('The size of file \\"%s\\" (%s) is larger than maximum allowed file size (%s). Select files again.'
                                      ) %
                                    (cgi.escape(filename),
                                     str(file_size / 1024) + 'KB',
                                     str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE /
                                         1024) + 'KB'))
                            except InvenioWebCommentWarning, exc:
                                register_exception(stream='warning')
                                warning_msgs.append((exc.message, ''))
                            #warning_msgs.append(('WRN_WEBCOMMENT_MAX_FILE_SIZE_REACHED', cgi.escape(filename), str(file_size/1024) + 'KB', str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB'))
                        else:
                            added_files[filename] = os.path.join(
                                dir_to_open, filename)

            if file_too_big:
                # One file was too big. Removed all uploaded filed
                for filepath in added_files.items():
                    try:
                        os.remove(filepath)
                    except:
                        # File was already removed or does not exist?
                        pass
                try:
                    raise InvenioWebCommentWarning(_('Comment ID %s does not exist.') % comID)
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(('WRN_WEBCOMMENT_ADMIN_COMID_INEXISTANT', comID))
                return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

        elif recID > 0:
            if record_exists(recID):
                comID = ''
                reviews = wash_url_argument(reviews, 'int')
                return (perform_request_comments(ln=ln, comID=comID, recID=recID, reviews=reviews), None, warnings)
            else:
                try:
                    raise InvenioWebCommentWarning(_('Record ID %s does not exist.') % comID)
                except InvenioWebCommentWarning, exc:
                    register_exception(stream='warning')
                    warnings.append((exc.message, ''))
                #warnings.append(('WRN_WEBCOMMENT_ADMIN_RECID_INEXISTANT', comID))
                return webcomment_templates.tmpl_admin_delete_form(ln, warnings)
        else:
            return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

    else:
        return webcomment_templates.tmpl_admin_delete_form(ln, warnings)

def perform_request_users(ln=CFG_SITE_LANG):
    """
    """
    ln = wash_language(ln)