def sandbox(self, req, form):
        """
        TOOD: Document
        """
        body = """
<div id="projects_%(publicationid)s">

</div>
"""
        return page(title='sandbox', body=body, req=req)
    def sandbox(self, req, form):
        """
        TOOD: Document
        """
        body = """
<div id="projects_%(publicationid)s">

</div>
"""
        return page(title="sandbox", body=body, req=req)
    def edit(self, req, form):
        argd = wash_urlargd(
            form,
            {
                "projectid": (int, -1),
                #'delete': (str, ''),
                "id": (str, ""),
                "a": (str, "edit"),
                #'linkproject': (int, -1),
                #'unlinkproject': (int, -1),
                # style': (str, None),
                #'upload': (str, ''),
                #'dropbox': (str, '')
            },
        )

        _ = gettext_set_language(argd["ln"])

        # Check if user is authorized to deposit publications
        user_info = collect_user_info(req)
        auth_code, auth_message = acc_authorize_action(user_info, "submit", doctype="OpenAIRE")
        if auth_code:
            if user_info["guest"] == "1":
                return redirect_to_url(
                    req,
                    "%s/youraccount/login%s"
                    % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(
                            {"referer": "%s%s" % (CFG_SITE_URL, req.unparsed_uri), "ln": argd["ln"]}, {}
                        ),
                    ),
                )
            else:
                return page(
                    req=req,
                    body=_("You are not authorized to use OpenAIRE deposition."),
                    title=_("Authorization failure"),
                    navmenuid="submit",
                )

        # Validate action
        action = argd["a"]
        if action not in ["edit", "save", "submit", "delete"]:
            abort(404)

        uid = user_info["uid"]
        if not argd["id"]:
            return redirect("/deposit/")

        try:
            pub = OpenAIREPublication(uid, publicationid=argd["id"])
            title = pub.metadata.get("title", "Untitled")
        except ValueError:
            abort(404)

        #
        # Action handling
        #
        if action == "delete":
            pub.delete()
            flash("Upload '%s' was deleted." % title, "info")
            return redirect("/deposit/")
        elif action == "edit":
            ctx = {"pub": pub, "title": title, "recid": pub.metadata.get("__recid__", None)}

            ctx["rendered_form"] = openaire_deposit_templates.tmpl_form(
                pub.metadata["__publicationid__"],
                -1,
                "",  # projects_information
                "",  # publication_information
                "",  # fulltext_information
                form=None,
                metadata_status="empty",
                warnings=None,
                errors=None,
                ln="en",
            )

        # if action == "edit":

        # elif action == "delete":
        #    pass

        # if projectid >= 0:
        #     ## There is a project on which we are working good!
        #     publications = get_all_publications_for_project(
        #         uid, projectid, ln=argd['ln'], style=style)
        #     if argd['publicationid'] in publications:
        #         if argd['addproject'] in all_project_ids:
        #             publications[argd['publicationid']
        #                          ].link_project(argd['linkproject'])
        #         if argd['delproject'] in all_project_ids:
        #             publications[argd['publicationid']
        #                          ].unlink_project(argd['unlinkproject'])
        #     if argd['delete'] and argd['delete'] in publications:
        #         ## there was a request to delete a publication
        #         publications[argd['delete']].delete()
        #         del publications[argd['delete']]

        #     forms = ""
        #     submitted_publications = ""
        #     for index, (publicationid, publication) in enumerate(publications.iteritems()):
        #         if req.method.upper() == 'POST':
        #             publication.merge_form(form, ln=argd['ln'])
        #         if publication.status == 'edited':
        #             publication.check_metadata()
        #             publication.check_projects()
        #             if 'submit_%s' % publicationid in form and not "".join(publication.errors.values()).strip():
        #                 ## i.e. if the button submit for the corresponding publication has been pressed...
        #                 publication.upload_record()
        #         if publication.status in ('initialized', 'edited'):
        #             forms += publication.get_publication_form(projectid)
        #         else:
        #             submitted_publications += publication.get_publication_preview()
        #     body += openaire_deposit_templates.tmpl_add_publication_data_and_submit(projectid, forms, submitted_publications, project_information=upload_to_project_information, ln=argd['ln'])
        #     body += openaire_deposit_templates.tmpl_upload_publications(projectid=upload_to_projectid, project_information=upload_to_project_information, session=get_session(req).sid.encode('utf8'), style=style, ln=argd['ln'])
        # else:

        ctx.update({"myresearch": get_exisiting_publications_for_uid(uid)})

        return render_template(
            "openaire_edit.html", req=req, breadcrumbs=[(_("Home"), ""), (_("Upload"), "deposit"), (title, "")], **ctx
        ).encode("utf8")
    def index(self, req, form):
        """
        Main submission page installed on /deposit (hack in Invenio source) with the
        following features:

          * Two different themes/skins (for portal and for invenio)
          * Upload new file to start a publication submission.
          * Enter metadata for publication(s) related to a project

        URL parameters:
         * style: Theme/skin to use - "invenio" or "portal"
         * projectid: Work on publications for this project
         * delete: Delete file and publication
         * plus: ?
         * upload: Upload new file (without Uploadify backend)
        """
        argd = wash_urlargd(
            form,
            {
                "projectid": (int, -1),
                "delete": (str, ""),
                "publicationid": (str, ""),
                "plus": (int, -1),
                "linkproject": (int, -1),
                "unlinkproject": (int, -1),
                "style": (str, None),
                "upload": (str, ""),
                "dropbox": (str, ""),
            },
        )

        _ = gettext_set_language(argd["ln"])

        # Check if user is authorized to deposit publications
        user_info = collect_user_info(req)
        auth_code, auth_message = acc_authorize_action(user_info, "submit", doctype="OpenAIRE")
        if auth_code:
            if user_info["guest"] == "1":
                return redirect_to_url(
                    req,
                    "%s/youraccount/login%s"
                    % (
                        CFG_SITE_SECURE_URL,
                        make_canonical_urlargd(
                            {"referer": "%s%s" % (CFG_SITE_URL, req.unparsed_uri), "ln": argd["ln"]}, {}
                        ),
                    ),
                )
            else:
                return page(
                    req=req,
                    body=_("You are not authorized to use OpenAIRE deposition."),
                    title=_("Authorization failure"),
                    navmenuid="submit",
                )

        # Get parameters
        projectid = argd["projectid"]
        plus = argd["plus"]
        style = get_openaire_style(req)

        if plus == -1:
            try:
                plus = bool(session_param_get(req, "plus"))
            except KeyError:
                plus = False
                session_param_set(req, "plus", plus)
        else:
            plus = bool(plus)
            session_param_set(req, "plus", plus)

        # Check projectid
        all_project_ids = get_all_projectsids()

        if projectid not in all_project_ids:
            projectid = -1

        uid = user_info["uid"]

        ## Perform file upload (if needed)
        if argd["upload"]:
            if projectid < 0:
                projectid = 0
            try:
                upload_file(form, uid, projectid)
            except UploadError, e:
                return page(req=req, body=unicode(e), title=_("File upload error"), navmenuid="submit")
                        publication.upload_record()
                if publication.status in ('initialized', 'edited'):
                    forms += publication.get_publication_form(projectid)
                else:
                    submitted_publications += publication.get_publication_preview()
            body += openaire_deposit_templates.tmpl_add_publication_data_and_submit(projectid, forms, submitted_publications, project_information=upload_to_project_information, ln=argd['ln'])
            body += openaire_deposit_templates.tmpl_upload_publications(projectid=upload_to_projectid, project_information=upload_to_project_information, session=get_session(req).sid(), style=style, ln=argd['ln'])
        else:
            body += openaire_deposit_templates.tmpl_upload_publications(projectid=upload_to_projectid, project_information=upload_to_project_information, session=get_session(req).sid(), style=style, ln=argd['ln'])
            projects = [get_project_information(uid, projectid_, deletable=False, ln=argd['ln'], style=style, linked=True) for projectid_ in get_exisiting_projectids_for_uid(user_info['uid']) if projectid_ != projectid]
            if projects:
                body += openaire_deposit_templates.tmpl_focus_on_project(
                    existing_projects=projects, ln=argd['ln'])

        title = _('Orphan Repository')
        return page(body=body, title=title, req=req, project_information=get_project_acronym(projectid), navmenuid="submit")

    def uploadifybackend(self, req, form):
        """
        File upload via Uploadify (flash) backend.
        """
        argd = wash_urlargd(
            form, {'session': (str, ''), 'projectid': (int, -1)})
        _ = gettext_set_language(argd['ln'])
        session = argd['session']
        get_session(req=req, sid=session)
        user_info = collect_user_info(req)
        if user_info['guest'] == '1':
            raise ValueError(_("This session is invalid"))
        projectid = argd['projectid']
        if projectid < 0:
    def edit(self, req, form):
        argd = wash_urlargd(
            form,
            {
                'projectid': (int, -1),
                #'delete': (str, ''),
                'id': (str, ''),
                'a': (str, 'edit'),
                #'linkproject': (int, -1),
                #'unlinkproject': (int, -1),
                #style': (str, None),
                #'upload': (str, ''),
                #'dropbox': (str, '')
            })

        _ = gettext_set_language(argd['ln'])

        # Check if user is authorized to deposit publications
        user_info = collect_user_info(req)
        auth_code, auth_message = acc_authorize_action(user_info,
                                                       'submit',
                                                       doctype='OpenAIRE')
        if auth_code:
            if user_info['guest'] == '1':
                return redirect_to_url(
                    req, "%s/youraccount/login%s" %
                    (CFG_SITE_SECURE_URL,
                     make_canonical_urlargd(
                         {
                             'referer': "%s%s" %
                             (CFG_SITE_URL, req.unparsed_uri),
                             "ln": argd['ln']
                         }, {})))
            else:
                return page(
                    req=req,
                    body=_(
                        "You are not authorized to use OpenAIRE deposition."),
                    title=_("Authorization failure"),
                    navmenuid="submit")

        # Validate action
        action = argd['a']
        if action not in ['edit', 'save', 'submit', 'delete']:
            abort(404)

        uid = user_info['uid']
        if not argd['id']:
            return redirect("/deposit/")

        try:
            pub = OpenAIREPublication(uid, publicationid=argd['id'])
            title = pub.metadata.get('title', 'Untitled')
        except ValueError:
            abort(404)

        #
        # Action handling
        #
        if action == 'delete':
            pub.delete()
            flash("Upload '%s' was deleted." % title, 'info')
            return redirect('/deposit/')
        elif action == 'edit':
            ctx = {
                'pub': pub,
                'title': title,
                'recid': pub.metadata.get('__recid__', None),
            }

            ctx['rendered_form'] = openaire_deposit_templates.tmpl_form(
                pub.metadata['__publicationid__'],
                -1,
                "",  # projects_information
                "",  # publication_information
                "",  # fulltext_information
                form=None,
                metadata_status='empty',
                warnings=None,
                errors=None,
                ln='en',
            )

        #if action == "edit":

        #elif action == "delete":
        #    pass

        # if projectid >= 0:
        #     ## There is a project on which we are working good!
        #     publications = get_all_publications_for_project(
        #         uid, projectid, ln=argd['ln'], style=style)
        #     if argd['publicationid'] in publications:
        #         if argd['addproject'] in all_project_ids:
        #             publications[argd['publicationid']
        #                          ].link_project(argd['linkproject'])
        #         if argd['delproject'] in all_project_ids:
        #             publications[argd['publicationid']
        #                          ].unlink_project(argd['unlinkproject'])
        #     if argd['delete'] and argd['delete'] in publications:
        #         ## there was a request to delete a publication
        #         publications[argd['delete']].delete()
        #         del publications[argd['delete']]

        #     forms = ""
        #     submitted_publications = ""
        #     for index, (publicationid, publication) in enumerate(publications.iteritems()):
        #         if req.method.upper() == 'POST':
        #             publication.merge_form(form, ln=argd['ln'])
        #         if publication.status == 'edited':
        #             publication.check_metadata()
        #             publication.check_projects()
        #             if 'submit_%s' % publicationid in form and not "".join(publication.errors.values()).strip():
        #                 ## i.e. if the button submit for the corresponding publication has been pressed...
        #                 publication.upload_record()
        #         if publication.status in ('initialized', 'edited'):
        #             forms += publication.get_publication_form(projectid)
        #         else:
        #             submitted_publications += publication.get_publication_preview()
        #     body += openaire_deposit_templates.tmpl_add_publication_data_and_submit(projectid, forms, submitted_publications, project_information=upload_to_project_information, ln=argd['ln'])
        #     body += openaire_deposit_templates.tmpl_upload_publications(projectid=upload_to_projectid, project_information=upload_to_project_information, session=get_session(req).sid.encode('utf8'), style=style, ln=argd['ln'])
        # else:

        ctx.update({
            'myresearch': get_exisiting_publications_for_uid(uid),
        })

        return render_template("openaire_edit.html",
                               req=req,
                               breadcrumbs=[
                                   (_('Home'), ''),
                                   (_('Upload'), 'deposit'),
                                   (title, ''),
                               ],
                               **ctx).encode('utf8')
class WebInterfaceOpenAIREDepositPages(WebInterfaceDirectory):
    _exports = [
        'sandbox',
        'checkmetadata',
        'ajaxgateway',
        'checksinglefield',
        'getfile',
        'authorships',
        'keywords',
        'portalproxy',
    ]

    def edit(self, req, form):
        argd = wash_urlargd(
            form,
            {
                'projectid': (int, -1),
                #'delete': (str, ''),
                'id': (str, ''),
                'a': (str, 'edit'),
                #'linkproject': (int, -1),
                #'unlinkproject': (int, -1),
                #style': (str, None),
                #'upload': (str, ''),
                #'dropbox': (str, '')
            })

        _ = gettext_set_language(argd['ln'])

        # Check if user is authorized to deposit publications
        user_info = collect_user_info(req)
        auth_code, auth_message = acc_authorize_action(user_info,
                                                       'submit',
                                                       doctype='OpenAIRE')
        if auth_code:
            if user_info['guest'] == '1':
                return redirect_to_url(
                    req, "%s/youraccount/login%s" %
                    (CFG_SITE_SECURE_URL,
                     make_canonical_urlargd(
                         {
                             'referer': "%s%s" %
                             (CFG_SITE_URL, req.unparsed_uri),
                             "ln": argd['ln']
                         }, {})))
            else:
                return page(
                    req=req,
                    body=_(
                        "You are not authorized to use OpenAIRE deposition."),
                    title=_("Authorization failure"),
                    navmenuid="submit")

        # Validate action
        action = argd['a']
        if action not in ['edit', 'save', 'submit', 'delete']:
            abort(404)

        uid = user_info['uid']
        if not argd['id']:
            return redirect("/deposit/")

        try:
            pub = OpenAIREPublication(uid, publicationid=argd['id'])
            title = pub.metadata.get('title', 'Untitled')
        except ValueError:
            abort(404)

        #
        # Action handling
        #
        if action == 'delete':
            pub.delete()
            flash("Upload '%s' was deleted." % title, 'info')
            return redirect('/deposit/')
        elif action == 'edit':
            ctx = {
                'pub': pub,
                'title': title,
                'recid': pub.metadata.get('__recid__', None),
            }

            ctx['rendered_form'] = openaire_deposit_templates.tmpl_form(
                pub.metadata['__publicationid__'],
                -1,
                "",  # projects_information
                "",  # publication_information
                "",  # fulltext_information
                form=None,
                metadata_status='empty',
                warnings=None,
                errors=None,
                ln='en',
            )

        #if action == "edit":

        #elif action == "delete":
        #    pass

        # if projectid >= 0:
        #     ## There is a project on which we are working good!
        #     publications = get_all_publications_for_project(
        #         uid, projectid, ln=argd['ln'], style=style)
        #     if argd['publicationid'] in publications:
        #         if argd['addproject'] in all_project_ids:
        #             publications[argd['publicationid']
        #                          ].link_project(argd['linkproject'])
        #         if argd['delproject'] in all_project_ids:
        #             publications[argd['publicationid']
        #                          ].unlink_project(argd['unlinkproject'])
        #     if argd['delete'] and argd['delete'] in publications:
        #         ## there was a request to delete a publication
        #         publications[argd['delete']].delete()
        #         del publications[argd['delete']]

        #     forms = ""
        #     submitted_publications = ""
        #     for index, (publicationid, publication) in enumerate(publications.iteritems()):
        #         if req.method.upper() == 'POST':
        #             publication.merge_form(form, ln=argd['ln'])
        #         if publication.status == 'edited':
        #             publication.check_metadata()
        #             publication.check_projects()
        #             if 'submit_%s' % publicationid in form and not "".join(publication.errors.values()).strip():
        #                 ## i.e. if the button submit for the corresponding publication has been pressed...
        #                 publication.upload_record()
        #         if publication.status in ('initialized', 'edited'):
        #             forms += publication.get_publication_form(projectid)
        #         else:
        #             submitted_publications += publication.get_publication_preview()
        #     body += openaire_deposit_templates.tmpl_add_publication_data_and_submit(projectid, forms, submitted_publications, project_information=upload_to_project_information, ln=argd['ln'])
        #     body += openaire_deposit_templates.tmpl_upload_publications(projectid=upload_to_projectid, project_information=upload_to_project_information, session=get_session(req).sid.encode('utf8'), style=style, ln=argd['ln'])
        # else:

        ctx.update({
            'myresearch': get_exisiting_publications_for_uid(uid),
        })

        return render_template("openaire_edit.html",
                               req=req,
                               breadcrumbs=[
                                   (_('Home'), ''),
                                   (_('Upload'), 'deposit'),
                                   (title, ''),
                               ],
                               **ctx).encode('utf8')

    def index(self, req, form):
        """
        Main submission page installed on /deposit (hack in Invenio source) with the
        following features:

          * Two different themes/skins (for portal and for invenio)
          * Upload new file to start a publication submission.
          * Enter metadata for publication(s) related to a project

        URL parameters:
         * style: Theme/skin to use - "invenio" or "portal"
         * projectid: Work on publications for this project
         * delete: Delete file and publication
         * plus: ?
         * upload: Upload new file (without Uploadify backend)
        """
        argd = wash_urlargd(
            form, {
                'projectid': (int, -1),
                'delete': (str, ''),
                'publicationid': (str, ''),
                'plus': (int, -1),
                'linkproject': (int, -1),
                'unlinkproject': (int, -1),
                'style': (str, None),
                'upload': (str, ''),
                'dropbox': (str, '')
            })

        _ = gettext_set_language(argd['ln'])

        # Check if user is authorized to deposit publications
        user_info = collect_user_info(req)
        auth_code, auth_message = acc_authorize_action(user_info,
                                                       'submit',
                                                       doctype='OpenAIRE')
        if auth_code:
            if user_info['guest'] == '1':
                return redirect_to_url(
                    req, "%s/youraccount/login%s" %
                    (CFG_SITE_SECURE_URL,
                     make_canonical_urlargd(
                         {
                             'referer': "%s%s" %
                             (CFG_SITE_URL, req.unparsed_uri),
                             "ln": argd['ln']
                         }, {})))
            else:
                return page(
                    req=req,
                    body=_(
                        "You are not authorized to use OpenAIRE deposition."),
                    title=_("Authorization failure"),
                    navmenuid="submit")

        # Get parameters
        projectid = argd['projectid']
        plus = argd['plus']
        style = get_openaire_style(req)

        if plus == -1:
            try:
                plus = bool(session_param_get(req, 'plus'))
            except KeyError:
                plus = False
                session_param_set(req, 'plus', plus)
        else:
            plus = bool(plus)
            session_param_set(req, 'plus', plus)

        # Check projectid
        all_project_ids = get_all_projectsids()

        if projectid not in all_project_ids:
            projectid = -1

        uid = user_info['uid']

        ## Perform file upload (if needed)
        if argd['upload']:
            if projectid < 0:
                projectid = 0
            try:
                upload_file(form, uid, projectid)
            except UploadError, e:
                return page(req=req,
                            body=unicode(e),
                            title=_("File upload error"),
                            navmenuid="submit")
        elif argd['dropbox']:
            if projectid < 0:
                projectid = 0
            try:
                upload_url(form, uid, projectid)
            except UploadError, e:
                return page(req=req,
                            body=unicode(e),
                            title=_("File upload error"),
                            navmenuid="submit")
    def index(self, req, form):
        """
        Main submission page installed on /deposit (hack in Invenio source) with the
        following features:

          * Two different themes/skins (for portal and for invenio)
          * Upload new file to start a publication submission.
          * Enter metadata for publication(s) related to a project

        URL parameters:
         * style: Theme/skin to use - "invenio" or "portal"
         * projectid: Work on publications for this project
         * delete: Delete file and publication
         * plus: ?
         * upload: Upload new file (without Uploadify backend)
        """
        argd = wash_urlargd(
            form, {
                'projectid': (int, -1),
                'delete': (str, ''),
                'publicationid': (str, ''),
                'plus': (int, -1),
                'linkproject': (int, -1),
                'unlinkproject': (int, -1),
                'style': (str, None),
                'upload': (str, ''),
                'dropbox': (str, '')
            })

        _ = gettext_set_language(argd['ln'])

        # Check if user is authorized to deposit publications
        user_info = collect_user_info(req)
        auth_code, auth_message = acc_authorize_action(user_info,
                                                       'submit',
                                                       doctype='OpenAIRE')
        if auth_code:
            if user_info['guest'] == '1':
                return redirect_to_url(
                    req, "%s/youraccount/login%s" %
                    (CFG_SITE_SECURE_URL,
                     make_canonical_urlargd(
                         {
                             'referer': "%s%s" %
                             (CFG_SITE_URL, req.unparsed_uri),
                             "ln": argd['ln']
                         }, {})))
            else:
                return page(
                    req=req,
                    body=_(
                        "You are not authorized to use OpenAIRE deposition."),
                    title=_("Authorization failure"),
                    navmenuid="submit")

        # Get parameters
        projectid = argd['projectid']
        plus = argd['plus']
        style = get_openaire_style(req)

        if plus == -1:
            try:
                plus = bool(session_param_get(req, 'plus'))
            except KeyError:
                plus = False
                session_param_set(req, 'plus', plus)
        else:
            plus = bool(plus)
            session_param_set(req, 'plus', plus)

        # Check projectid
        all_project_ids = get_all_projectsids()

        if projectid not in all_project_ids:
            projectid = -1

        uid = user_info['uid']

        ## Perform file upload (if needed)
        if argd['upload']:
            if projectid < 0:
                projectid = 0
            try:
                upload_file(form, uid, projectid)
            except UploadError, e:
                return page(req=req,
                            body=unicode(e),
                            title=_("File upload error"),
                            navmenuid="submit")