Exemplo n.º 1
0
def migrate_special_dirs():
    """Special dirs are found by special system attribute used_as, not the directory name as before.
    """
    home_root = q(Home).one()
    for home_dir in home_root.children:
        logg.info("fixing special dirs in home dir %s (%s)", home_dir.name,
                  home_dir.id)
        lang = getDefaultLanguage()
        special_dirs = [(translate(u"user_trash", lang), u"trash"),
                        (translate(u"user_upload", lang), u"upload")]

        for old, new in special_dirs:
            new_dir = home_dir.children.filter_by(name=new).scalar()
            if not new_dir:
                old_dirrs = home_dir.children.filter_by(name=old).order_by(
                    Node.id).all()
                if not old_dirrs:
                    logg.info("creating missing special dir %s", new)
                    dirr = Directory(new)
                    home_dir.children.append(dirr)
                else:
                    if len(old_dirrs) > 1:
                        logg.warn(
                            "%s special dirs found for %s, using oldest dir",
                            len(old_dirrs), home_dir.name)
                    dirr = old_dirrs[0]
                    dirr.name = new

                dirr.system_attrs[u"used_as"] = new
Exemplo n.º 2
0
def migrate_special_dirs():
    """Special dirs are found by special system attribute used_as, not the directory name as before.
    """
    home_root = q(Home).one()
    for home_dir in home_root.children:
        logg.info("fixing special dirs in home dir %s (%s)", home_dir.name, home_dir.id)
        lang = getDefaultLanguage()
        special_dirs = [
            (translate(u"user_trash", lang), u"trash"),
            (translate(u"user_upload", lang), u"upload")
        ]

        for old, new in special_dirs:
            new_dir = home_dir.children.filter_by(name=new).scalar()
            if not new_dir:
                old_dirrs = home_dir.children.filter_by(name=old).order_by(Node.id).all()
                if not old_dirrs:
                    logg.info("creating missing special dir %s", new)
                    dirr = Directory(new)
                    home_dir.children.append(dirr)
                else:
                    if len(old_dirrs) > 1:
                        logg.warn("%s special dirs found for %s, using oldest dir", len(old_dirrs), home_dir.name)
                    dirr = old_dirrs[0]
                    dirr.name = new

                dirr.system_attrs[u"used_as"] = new
Exemplo n.º 3
0
    def getEditorHTML(self, field, value="", width=400, lock=0, language=None, required=None):

        # field may not be persisted as tree.Node and therefore may not have
        # an attribute "get"
        if hasattr(field, "get"):
            enable_multilang = bool(field.get('multilang'))
        else:
            enable_multilang = False

        if not language:
            language = getDefaultLanguage()

        try:
            field_node_name = field.name
        except:
            field_node_name = None

        context = {
            "lock": lock,
            "value": value,
            "width": width,
            "name": field_node_name,
            "field": field,
            "t": t,
            "ident": str(field.id),
            "current_lang": language,
            "defaultlang": language,  # not the systems default language
            "languages": [],
            "langdict": {language: value},
            "language_snipper": self.language_snipper,
            "value_is_multilang": 'single',
            "multilang_display": 'display: none',
            "enable_multilang": enable_multilang,
            "expand_multilang": False,
            "required": self.is_required(required)
        }

        if enable_multilang:
            languages = config_languages
            lang = [l for l in languages if l != language]

            langdict = self.str2dict(value)
            context.update(
                {
                    "languages": lang,
                    "langdict": langdict,
                    "value_is_multilang": {True: 'multi', False: 'single'}[self.has_language_cutter(value)],
                    "multilang_display": {True: '', False: 'display: none'}[self.has_language_cutter(value)],
                })

            if enable_multilang and self.has_language_cutter(value):
                context["expand_multilang"] = True
            else:
                context["expand_multilang"] = False

        return tal.getTAL("metadata/memo.html",
                          context,
                          macro="editorfield",
                          language=language)
Exemplo n.º 4
0
    def getEditorHTML(self,
                      field,
                      value="",
                      width=40,
                      lock=0,
                      language=None,
                      required=None):
        check_context()

        try:
            fieldname = field.name
        except:
            fieldname = None

        try:
            warning = [
                t[1] for t in self.labels[language]
                if t[0] == 'upload_notarget_warning'
            ][0]
        except:
            logg.exception(
                "exception in getEditorHTML, using default language")
            warning = [
                t[1] for t in self.labels[getDefaultLanguage()]
                if t[0] == 'upload_notarget_warning'
            ][0]

        context = {
            "lock": lock,
            "value": value,
            "width": width,
            "name": field.getName(),
            "field": field,
            "language": language,
            "warning": warning,
            "system_lock": 0,
            "required": self.is_required(required)
        }

        if lock:
            context['system_lock'] = 1

        try:
            if field.get("system.lock"):
                context['system_lock'] = 1
        except:
            pass

        s = tal.getTAL("metadata/upload.html",
                       context,
                       macro="editorfield",
                       language=language)
        if field.getName():
            s = s.replace("____FIELDNAME____", "%s" % field.getName())
        elif fieldname:
            s = s.replace("____FIELDNAME____", "%s" % fieldname)
        else:
            logg.warn("metadata: m_upload: no fieldname found")
        return s
Exemplo n.º 5
0
 def tableRowButtons(self, node):
     if node.get("system.key") == node.get("key"):
         # user has permission -> use users language
         return tal.getTAL(
             "workflow/workflow.html",
             {"node": node, "wfstep": self, "lang": node.get("system.wflanguage")},
             macro="workflow_buttons",
             language=node.get("system.wflanguage"),
         )
     else:
         # use standard language of request
         return tal.getTAL(
             "workflow/workflow.html",
             {"node": node, "wfstep": self, "lang": getDefaultLanguage()},
             macro="workflow_buttons",
             language=getDefaultLanguage(),
         )
Exemplo n.º 6
0
    def getLabel(self, lang=getDefaultLanguage()):

        # try language-specific name first
        lang_value = self.get(u'{}.name'.format(lang))
        if lang_value:
            return self.get(u'{}.name'.format(lang))

        # always return the name if the requested lang matches the default language
        if self.name and lang == getDefaultLanguage():
            return self.name

        label = self.get(u"label")

        # still no label found, use name
        if not label:
            label = self.name

        return label
Exemplo n.º 7
0
    def getLabel(self, lang=getDefaultLanguage()):

        # try language-specific name first
        lang_value = self.get(u'{}.name'.format(lang))
        if lang_value:
            return self.get(u'{}.name'.format(lang))

        # always return the name if the requested lang matches the default language
        if self.name and lang == getDefaultLanguage():
            return self.name

        label = self.get(u"label")

        # still no label found, use name
        if not label:
            label = self.name

        return label
Exemplo n.º 8
0
 def tableRowButtons(self, node):
     if node.get('system.key') == node.get('key'):
         # user has permission -> use users language
         return tal.getTAL("workflow/workflow.html", {
             'node': node,
             'wfstep': self,
             'lang': node.get('system.wflanguage')
         },
                           macro="workflow_buttons",
                           language=node.get('system.wflanguage'))
     else:
         # use standard language of request
         return tal.getTAL("workflow/workflow.html", {
             'node': node,
             'wfstep': self,
             'lang': getDefaultLanguage()
         },
                           macro="workflow_buttons",
                           language=getDefaultLanguage())
Exemplo n.º 9
0
def getSpecialDir(user, type):
    nodename = ""
    if type == "upload":
        nodename = translate("user_upload", getDefaultLanguage())
    elif type == "import":
        nodename = translate("user_import", getDefaultLanguage())
    elif type == "faulty":
        nodename = translate("user_faulty", getDefaultLanguage())
    elif type == "trash":
        nodename = translate("user_trash", getDefaultLanguage())
    else:
        return None

    userdir = getHomeDir(user)

    for c in userdir.getChildren():
        if c.name == nodename:
            return c
    # create new directory
    return userdir.addChild(tree.Node(name=nodename, type="directory"))
Exemplo n.º 10
0
def getSpecialDir(user, type):
    nodename = ""
    if type == "upload":
        nodename = translate("user_upload", getDefaultLanguage())
    elif type == "import":
        nodename = translate("user_import", getDefaultLanguage())
    elif type == "faulty":
        nodename = translate("user_faulty", getDefaultLanguage())
    elif type == "trash":
        nodename = translate("user_trash", getDefaultLanguage())
    else:
        return None

    userdir = getHomeDir(user)

    for c in userdir.getChildren():
        if c.name == nodename:
            return c
    # create new directory
    return userdir.addChild(tree.Node(name=nodename, type="directory"))
Exemplo n.º 11
0
 def tableRowButtons(self, node):
     if node.get('system.key') == node.get('key'):
         # user has permission -> use users language
         return tal.getTAL("workflow/workflow.html",
                           {'node': node,
                            'wfstep': self,
                            'lang': node.get('system.wflanguage')},
                           macro="workflow_buttons",
                           language=node.get('system.wflanguage'))
     else:
         # use standard language of request
         return tal.getTAL("workflow/workflow.html", {'node': node, 'wfstep': self, 'lang':
                                                      getDefaultLanguage()}, macro="workflow_buttons", language=getDefaultLanguage())
Exemplo n.º 12
0
    def getEditorHTML(self, field, value="", width=40, lock=0, language=None, required=None):
        check_context()

        try:
            fieldid = field.id
        except:
            fieldid = None

        try:
            fieldname = field.name
        except:
            fieldname = None

        try:
            warning = [t[1] for t in self.labels[language] if t[0] == 'upload_notarget_warning'][0]
        except:
            warning = [t[1] for t in self.labels[getDefaultLanguage()] if t[0] == 'upload_notarget_warning'][0]

        context = {
            "lock": lock,
            "value": value,
            "width": width,
            "name": field.getName(),
            "field": field,
            "language": language,
            "warning": warning,
            "system_lock": 0,
            "required": self.is_required(required)
        }

        if lock:
            context['system_lock'] = 1

        try:
            if field.get("system.lock"):
                context['system_lock'] = 1
        except:
            pass

        s = tal.getTAL("metadata/upload.html", context, macro="editorfield", language=language)
        if field.getName():
            s = s.replace("____FIELDNAME____", "%s" % field.getName())
        elif fieldname:
            s = s.replace("____FIELDNAME____", "%s" % fieldname)
        else:
            logging.getLogger('backend').warning("metadata: m_upload: no fieldname found")
        return s
Exemplo n.º 13
0
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
from collections import OrderedDict

from mediatumtal import tal
from core.transition import httpstatus
from core.metatype import Metatype

from core.translation import getDefaultLanguage

from contenttypes.default import languages as config_languages
import re

max_lang_length = max([len(lang) for lang in config_languages])
config_default_language = getDefaultLanguage()


class m_htmlmemo(Metatype):

    additional_attrs = ['multilang']

    CUTTER_TEMPLATE = "---%s---"
    # CUTTER_PATTERN = re.compile(r"^---(?P<lang>\w{2,5})---$")
    CUTTER_PATTERN_STRING = (r"^%s$" % CUTTER_TEMPLATE) % (
        "(?P<lang>\w{2,%d})" % max_lang_length)
    CUTTER_PATTERN = re.compile(CUTTER_PATTERN_STRING, re.MULTILINE)
    DEFAULT_LANGUAGE_CUTTER = CUTTER_TEMPLATE % config_default_language

    def has_language_cutter(self, s):
        return bool(self.CUTTER_PATTERN.search(s))
Exemplo n.º 14
0
def _handle_edit_metadata(req, mask, nodes):
    # check and save items
    user = current_user
    userdir = user.home_dir
    flag_nodename_changed = -1
    form = req.form

    for node in nodes:
        if not node.has_write_access() or node is userdir:
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    if not hasattr(mask, "i_am_not_a_mask"):
        if form.get('generate_new_version'):
            # Create new node version
            comment = u'({})\n{}'.format(t(req, "document_new_version_comment"), form.get('version_comment', ''))

            for node in nodes:
                with node.new_tagged_version(comment=comment, user=user):
                    mask.update_node(node, req, user)
        else:
            # XXX: why check here?
            # if nodes:
            old_nodename = nodes[0].name

            for node in nodes:
                mask.update_node(node, req, user)

            db.session.commit()

            # XXX: why check here?
            # if nodes:
            new_nodename = nodes[0].name
            if ( len(nodes) == 1 or old_nodename != new_nodename) and isinstance(nodes[0], Container):
                # for updates of node label in editor tree
                flag_nodename_changed = ustr(nodes[0].id)

    else:
        for field in mask.metaFields():
            logg.debug("in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %s, field.id: %s, field.name: %s, mask: %s, maskname: %s",
                __name__, funcname(), field, field.id, field.name, mask, mask.name)
            field_name = field.name
            if field_name == 'nodename' and mask.name == 'settings':
                if '__nodename' in form:
                    field_name = '__nodename'  # no multilang here !
                elif getDefaultLanguage() + '__nodename' in form:
                    # no multilang here !
                    field_name = getDefaultLanguage() + '__nodename'
                value = form.get(field_name, None)
                if value:
                    if value != node.name:
                        flag_nodename_changed = ustr(node.id)
                    for node in nodes:
                        node.name = value
            value = form.get(field_name, None)
            if value is not None:
                for node in nodes:
                    node.set(field.name, value)
            else:
                node.set(field.getName(), "")
        db.session.commit()

    return flag_nodename_changed
Exemplo n.º 15
0
def getContent(req, ids):

    reload(su)

    language = lang(req)
    user = users.getUserFromRequest(req)
    username = user.getName()
    #access = acl.AccessData(user=user)
    access = acl.AccessData(req=req)

    if "schedule" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    errors = []
    error = ''

    if "action" in req.params.keys():
        action = req.params.get("action")
        if action.startswith("get_fields_for_"):
            schedule_func = req.params.get(
                "action").replace("get_fields_for_", "")
            fields = su.fc_dict[schedule_func].getMetafields(lang(req))
            fieldDicts = su.fc_dict[schedule_func].getMetafieldDicts(lang(req))

            field_errors = []
            for i, field in enumerate(fields):
                field_errors.append(False)

            d = {
                'fields': fields,
                'fieldDicts': fieldDicts,
                'currentField': fields[0],
                'field_errors': field_errors,
                'currentFunction': schedule_func,
                'explain_func': su.fc_dict[schedule_func].getExplanation(language)
            }

            req.writeTAL("web/edit/modules/schedule.html", d,
                         macro="schedule_func_show_fields_and_explanation")
            return ""

        elif action.startswith("load_schedule_"):
            schedule_id = action.replace("load_schedule_", "")
            try:
                schedule = tree.getNode(schedule_id)
            except:
                errors.append("edit_schedule_no_such_node_error")
                return "no such schedule error"

            if not schedule.type == "schedule" and access and access.hasWriteAccess(schedule):
                return "schedule access error"

            schedule_func = schedule.get("function")
            if schedule_func:
                fields = su.fc_dict[schedule_func].getMetafields(lang(req))
                fieldDicts = su.fc_dict[
                    schedule_func].getMetafieldDicts(lang(req))
                d['explain_func'] = su.fc_dict[
                    schedule_func].getExplanation(language)
            else:
                fields = []
                fieldDicts = []
                d['explain_func'] = ""

            field_errors = []
            for i, field in enumerate(fields):
                field_errors.append(False)

            has_evaluation_errors = False
            for i, dfield in enumerate(fieldDicts):
                field_name = dfield['field_name']
                field_value = schedule.get(field_name)
                dfield['value'] = field_value
                field_validator_func = dfield['field_validator_func']
                if field_validator_func and not field_validator_func(field_value):
                    dfield['evaluation_error'] = True
                    has_evaluation_errors = True
                else:
                    dfield['evaluation_error'] = False

            if has_evaluation_errors:
                error = "\n<br/>\n".join([error, t(language,
                                                   'edit_schedule_field_validation_error')])

            d = {
                'fields': fields,
                'fieldDicts': fieldDicts,
                'currentField': fields[0],
                'field_errors': field_errors,
                'currentFunction': schedule_func,
            }

            req.writeTAL("web/edit/modules/schedule.html", d,
                         macro="schedule_func_show_fields_and_explanation")
            return ""

        elif action == "delete_node_from_schedule":

            node_id = req.params.get('node_id', None)

            if node_id:
                pass
            else:
                errors.append("edit_schedule_unexpected_no_such_node")

            schedule_id = req.params.get('schedule_id', None)
            if schedule_id:
                try:
                    schedule = tree.getNode(schedule_id)
                except:
                    errors.append(
                        "edit_schedule_unexpected_no_such_schedule_node")
            else:
                errors.append("edit_schedule_unexpected_no_such_schedule_node")

            delete_errors = su.deleteNodeIDsFromSchedule(
                [node_id], schedule_id, access=access)

            if not delete_errors:
                msg = "user '%s' removed node %s from schedule '%s' (%s)" % (
                    username, node_id, schedule.name, schedule_id)
                logging.getLogger("backend").info(msg)
            else:
                error_msg = ", ".join([t(language, e) for e in delete_errors])
                msg = "user '%s' tried to remove node %s from schedule '%s' (%s): %s" % (
                    username, node_id, schedule.name, schedule_id, error_msg)
                logging.getLogger("backend").error(msg)

            errors += delete_errors

            s = {}
            s['errors'] = errors
            s['delete_errors'] = delete_errors

            s['delete_table_rows'] = ['sid_%s' % schedule_id]

            res_msg = req.params.get(
                "jsoncallback") + "(%s)" % json.dumps(s, indent=4)
            req.write(res_msg)
            return ""

        elif action == "delete_schedule":
            schedule_id = req.params.get('schedule_id', None)
            if schedule_id:
                try:
                    schedule = tree.getNode(schedule_id)
                except:
                    errors.append(
                        "edit_schedule_unexpected_no_such_schedule_node")
            else:
                errors.append("edit_schedule_unexpected_no_such_schedule_node")

            delete_errors = su.deleteSchedule(schedule_id, access=access)

            if not delete_errors:
                msg = "user '%s' removed schedule %s (%s)" % (
                    username, schedule.name, schedule_id)
                logging.getLogger("backend").info(msg)
            else:
                error_msg = ", ".join([t(language, e) for e in delete_errors])
                msg = "user '%s' tried to remove schedule '%s' (%s): %s" % (
                    username, schedule.name, schedule_id, error_msg)
                logging.getLogger("backend").error(msg)

            errors += delete_errors

            s = {}
            s['errors'] = errors
            s['delete_errors'] = delete_errors
            s['delete_table_rows'] = ['sid_%s' % schedule_id]

            res_msg = req.params.get(
                "jsoncallback") + "(%s)" % json.dumps(s, indent=4)
            req.write(res_msg)
            return ""

        elif action == "load_table_nid2schedules":

            nid2schedules, schedule2nids, nid2active_schedules = su.getSchedulesForIds(
                ids, access=access, language=language)

            nid2schedules_attrs = {}
            for nid in nid2schedules:
                nid2schedules_attrs[nid] = [
                    [s.id, s.name, s.get("single_trigger")] for s in nid2schedules[nid]['schedule_list']]

            d = {}
            d['nid2schedules'] = nid2schedules
            d['nid2active_schedules'] = nid2active_schedules
            d['errors'] = ['testerror1', 'testerror1']
            d['date'] = datetime.now().isoformat()
            d['isActive'] = su.isActive

            req.writeTAL(
                "web/edit/modules/schedule.html", d, macro="table_nid2schedules")
            return ""

        elif action == "load_table_schedule2nids":

            nid2schedules, schedule2nids, nid2active_schedules = su.getSchedulesForIds(
                ids, access=access, language=language)

            nid2schedules_attrs = {}
            for nid in nid2schedules:
                nid2schedules_attrs[nid] = [
                    [s.id, s.name, s.get("single_trigger")] for s in nid2schedules[nid]['schedule_list']]

            d = {}
            d['nid2schedules'] = nid2schedules
            d['schedule2nids'] = schedule2nids
            d['nid2active_schedules'] = nid2active_schedules
            d['errors'] = ['testerror1', 'testerror1']
            d['date'] = datetime.now().isoformat()
            d['isActive'] = su.isActive

            req.writeTAL(
                "web/edit/modules/schedule.html", d, macro="table_schedule2nids")
            return ""

    nid2schedules, schedule2nids, nid2active_schedules = su.getSchedulesForIds(
        ids, access=access, language=language)

    datetime_str = req.params.get("datetime", "").strip()
    datetime_error = False
    has_evaluation_errors = False

    if datetime_str:
        patter = "^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$"
        if not re.match(patter, datetime_str):
            error = t(
                language, "edit_schedule_input_datetime_format_error") % datetime_str
            datetime_error = True
        else:
            try:
                parser_test_result = datetime.strptime(
                    datetime_str, "%Y-%m-%dT%H:%M")  # "%Y-%m-%dT%H:%M:%S.%f"
            except:
                parser_test_result = None
                error = t(
                    language, "edit_schedule_input_datetime_format_error") % datetime_str
                datetime_error = True
            if parser_test_result and datetime_str <= datetime.now().isoformat():
                error = t(
                    language, "edit_schedule_input_datetime_already_past_error") % datetime_str
                datetime_error = True
    elif "submit" in req.params:
        error = t(
            language, "edit_schedule_input_datetime_format_error") % datetime_str
        datetime_error = True

    schedule_id = req.params.get("schedule_id", "")
    if schedule_id:
        schedule = tree.getNode(schedule_id)
        if access and not access.hasWriteAccess(schedule):
            errors.append("edit_schedule_no_access_error")
            schedule = None
            current_function = req.params.get('schedule_function', '')
        else:
            current_function = schedule.get("function")
    else:
        schedule = None
        current_function = req.params.get('schedule_function', '')

    if "submit" in req.params or "submit_run_now" in req.params:
        current_function = req.params.get('schedule_function', '')
        if current_function in su.fc_dict:
            field_descriptors = su.fc_dict[
                current_function].getFieldDescriptors()
            field_errors = []
        else:
            # should not happen
            msg = "-> unexpected error: 'non-existant schedule function' requested in module %s: :s" % (
                str(__file__), str(inspect.currentframe().f_lineno))
            print msg
            logging.getLogger("backend").error(msg)

    d = {
        "id": req.params.get("id")
    }

    # nodes list is used to display icons in upper part of page
    # additional nodes should not / will not be shown there
    nodes = []
    for nid in ids:
        node = tree.getNode(nid)
        nodes.append(node)

    d['nodes'] = nodes

    if current_function in su.fc_dict:
        fields = su.fc_dict[current_function].getMetafields(lang(req))
        fieldDicts = su.fc_dict[current_function].getMetafieldDicts(lang(req))
        d['explain_func'] = su.fc_dict[
            current_function].getExplanation(language)
    else:
        fields = []
        fieldDicts = []
        d['explain_func'] = ""

    if not "submit_run_now" in req.params:
        has_evaluation_errors = datetime_error

    if schedule and not "submit" in req.params and not "submit_run_now" in req.params:
        for i, dfield in enumerate(fieldDicts):
            field_name = dfield['field_name']
            field_value = schedule.get(field_name)
            dfield['value'] = field_value
            field_validator_func = dfield['field_validator_func']
            if field_validator_func and not field_validator_func(field_value):
                dfield['evaluation_error'] = True
                has_evaluation_errors = True
            else:
                dfield['evaluation_error'] = False
    else:
        for i, dfield in enumerate(fieldDicts):
            field_name = dfield['field_name']
            # m_* classes from metadata/ are not multilingual for schedules
            # their getEditorHTML methods are used to display schedule node
            # attributes
            field_value = req.params.get(
                getDefaultLanguage() + '__' + field_name, '')
            dfield['value'] = field_value
            field_validator_func = dfield['field_validator_func']
            if field_validator_func and not field_validator_func(field_value):
                dfield['evaluation_error'] = True
                has_evaluation_errors = True
            else:
                dfield['evaluation_error'] = False

    additional_nodes_str = req.params.get("additional_nodes", "")
    additional_nodes_error = False
    additional_nodes_bad_ids = []

    try:
        additional_nodes_id_list = [
            str(int(nid.strip())) for nid in additional_nodes_str.strip().split(";") if nid.strip()]
    except:
        has_evaluation_errors = True
        additional_nodes_error = True
        additional_nodes_id_list = []
        errors.append(
            "edit_schedule_additional_nodes_list_not_semikolon_separated_list_of_integers")

    if not additional_nodes_error:
        collections_root = tree.getRoot("collections")
        for nid in additional_nodes_id_list:
            n = None
            try:
                n = tree.getNode(nid)
            except tree.NoSuchNodeError as e:
                has_evaluation_errors = True
                additional_nodes_error = True
                if nid not in additional_nodes_bad_ids:
                    additional_nodes_bad_ids.append(nid)
            if n and (not isDescendantOf(n, collections_root) or not access.hasWriteAccess(n)):
                # to do? discussion: override collections rectriction for
                # admins ?
                has_evaluation_errors = True
                additional_nodes_error = True
                if nid not in additional_nodes_bad_ids:
                    additional_nodes_bad_ids.append(nid)

    if additional_nodes_bad_ids:
        has_evaluation_errors = True
        additional_nodes_error = True
        errors.append(t(language, "edit_schedule_additional_nodes_bad_ids") +
                      (";".join(additional_nodes_bad_ids)))

    if has_evaluation_errors:
        errors.append('edit_schedule_field_validation_error')
        error = "\n<br/>\n".join(map(lambda x:
                                     t(language, x), [error] + errors))

    d['fields'] = fields
    d['fieldDicts'] = fieldDicts
    d['field_errors'] = [False] * len(fields)
    d['currentField'] = None
    d['currentFunction'] = current_function

    d['error'] = error

    d['fc_dict'] = su.filter_access(su.fc_dict, access)

    d['input_datetime'] = datetime_str
    d['input_datetime_error'] = datetime_error

    d['nid2schedules'] = nid2schedules
    d['schedule2nids'] = schedule2nids
    d['nid2active_schedules'] = nid2active_schedules

    d['loaded_schedule'] = schedule

    if schedule:
        d['loaded_schedule_id'] = str(schedule.id)
    else:
        d['loaded_schedule_id'] = None

    d['mklink'] = su.mklink

    d['language'] = language
    d['t'] = t
    d['isActive'] = su.isActive

    d['result'] = ''

    d['created_new_schedule'] = False

    d['additional_nodes'] = additional_nodes_str
    d['additional_nodes_error'] = additional_nodes_error

    d['submitbutton_run_now_label'] = t(
        language, 'edit_schedule_submit_run_now_button')
    d['edit_schedule_submit_run_now_button_confirm'] = t(
        language, 'edit_schedule_submit_run_now_button_confirm')
    d['edit_schedule_delete_schedule_confirm'] = t(
        language, 'edit_schedule_delete_schedule_confirm')

    if has_evaluation_errors and not ('submit_run_now' in req.params):
        return req.getTAL("web/edit/modules/schedule.html", d, macro="schedule_popup")

    new_schedule = None
    if (not schedule and "submit" in req.params) or "submit_run_now" in req.params:

        new_schedule_name = user.name + \
            "_created_at_" + datetime.now().isoformat()
        new_schedule = tree.Node(new_schedule_name, 'schedule')

        username = user.getName()
        new_schedule.setAccess("write", "{user %s}" % username)

        if not "submit_run_now" in req.params:
            schedules = tree.getRoot("schedules")
            schedules.addChild(new_schedule)

            msg = "user '%s' created new schedule '%s' (%s), trigger='%s', function='%s', nodelist='%s'" % (
                username, new_schedule.name, str(new_schedule.id), datetime_str, d['currentFunction'], new_schedule.get('nodelist'))
            logging.getLogger("backend").info(msg)

            d['result'] = t(
                language, 'edit_schedule_result_new_schedule_created')
            d['created_new_schedule'] = True
        else:
            msg = "user '%s' created temporary schedule '%s' (%s), trigger='%s', function='%s', nodelist='%s'" % (
                username, new_schedule.name, str(new_schedule.id), datetime_str, d['currentFunction'], new_schedule.get('nodelist'))
            logging.getLogger("backend").info(msg)

            d['result'] = t(
                language, 'edit_schedule_result_temporary_schedule_created')
            d['created_temporary_schedule'] = True

    elif (schedule) and ("submit" in req.params):
        new_schedule = schedule
        msg = "user '%s' is editing schedule '%s' (%s), trigger='%s', function='%s', nodelist='%s'" % (
            username, new_schedule.name, str(new_schedule.id), datetime_str, d['currentFunction'], new_schedule.get('nodelist'))
        logging.getLogger("backend").info(msg)
        new_schedule.set("system.edited", datetime.now().isoformat())

        d['result'] = t(
            language, 'edit_schedule_result_existing_schedule_edited')

    if new_schedule:
        for i, dfield in enumerate(fieldDicts):
            field_name = dfield['field_name']
            field_value = dfield['value']
            new_schedule.set(field_name, field_value)

        ids_plus_additional_nodes = ids
        for nid in additional_nodes_id_list:
            if nid not in ids_plus_additional_nodes:
                ids_plus_additional_nodes.append(nid)

        new_schedule.set('function', d['currentFunction'])
        new_schedule.set('nodelist', ",".join(ids_plus_additional_nodes))
        new_schedule.set('single_trigger', datetime_str)

        if datetime.now().isoformat() < datetime_str:
            new_schedule.set('single_trigger_status', '')

        if "submit_run_now" in req.params:
            new_schedule.set("single_trigger", datetime.now().isoformat())
            has_fired, has_error, TT = su.handle_single_trigger(
                new_schedule, datetime.now().isoformat(), su.OUT)
            if has_error:
                _error1 = d['error']
                _error2 = "<br/>\n".join(map(lambda x:
                                             (t(language, str(x))), TT))
                _error = "<br/>\n".join([_error1, _error2])
                d['error'] = _error

    return req.getTAL("web/edit/modules/schedule.html", d, macro="schedule_popup")
Exemplo n.º 16
0
def buildHomeDirName(username):
    """
    make a string for naming the home directory in the browsing tree in the editor
    """
    return translate("user_directory",
                     getDefaultLanguage()) + " (" + username + ")"
Exemplo n.º 17
0
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
from collections import OrderedDict
from mediatumtal import tal
from core.transition import httpstatus
from core.metatype import Metatype, charmap
from core.translation import t, getDefaultLanguage

from contenttypes.default import languages as config_languages
import re

max_lang_length = max([len(lang) for lang in config_languages])
config_default_language = getDefaultLanguage()


class m_memo(Metatype):

    additional_attrs = ['multilang']

    CUTTER_TEMPLATE = "---%s---"
    # CUTTER_PATTERN = re.compile(r"^---(?P<lang>\w{2,5})---$")
    CUTTER_PATTERN_STRING = (r"^%s$" % CUTTER_TEMPLATE) % ("(?P<lang>\w{2,%d})" % max_lang_length)
    CUTTER_PATTERN = re.compile(CUTTER_PATTERN_STRING, re.MULTILINE)
    DEFAULT_LANGUAGE_CUTTER = CUTTER_TEMPLATE % config_default_language

    def has_language_cutter(self, s):
        return bool(self.CUTTER_PATTERN.search(s))
Exemplo n.º 18
0
    def updateNode(self, nodes, req):
        default_language = translation.getDefaultLanguage()
        for node in nodes:
            for item in self.getMaskFields():
                field = item.getField()
                if field and field.getContentType() == "metafield" and req.params.get(field.getName(), "").find("?") != 0:
                    t = getMetadataType(field.get("type"))
                    if field.getName() in req.params.keys():
                        value = t.format_request_value_for_db(field, req.params, field.getName())
                        language = translation.lang(req)
                        node.set(field.getName(), value)
                    elif field.getFieldtype() == "check":
                        node.set(field.getName(), 0)

                    else:
                        # if multilingual textfields were used, their names are
                        # saved in form en__Name, de__Name, de-AU__Name, en-US__Name etc.
                        for item in req.params.keys():
                            langPos = item.find('__')
                            if langPos != -1 and item[langPos + 2:] == field.getName():
                                # cut the language identifier (en__, fr__, etc)
                                if (req.params.get(str(field.id) + '_show_multilang', '') == 'multi'
                                        and hasattr(t, "language_update")):
                                    value_old = node.get(field.getName())
                                    value_new = req.params.get(item)
                                    value = t.language_update(value_old, value_new, item[:langPos])
                                    node.set(field.getName(), value)
                                elif req.params.get(str(field.id) + '_show_multilang', '') == 'single':
                                    if item[0:langPos] == translation.lang(req):
                                        new_value = req.params.get(item)
                                        node.set(field.getName(), new_value)
                                elif (req.params.get(str(field.id) + '_show_multilang', '') == 'multi'
                                      and not hasattr(t, "language_update")):
                                    value = t.format_request_value_for_db(field, req.params, item)
                                    oldValue = node.get(field.getName())
                                    position = oldValue.find(item[:langPos] + t.joiner)
                                    if position != -1:
                                        # there is already a value for this language
                                        newValue = (oldValue[:position + langPos + len(t.joiner)]
                                                    + value
                                                    + oldValue[oldValue.find(t.joiner,
                                                                             position + langPos + len(t.joiner)):])
                                        node.set(field.getName(), newValue)
                                    else:  # there is no value for this language yet
                                        if oldValue.find(t.joiner) == -1:
                                            # there are no values at all yet
                                            node.set(field.getName(), item[:langPos] + t.joiner + value + t.joiner)
                                        else:
                                            # there are some values for other languages, but not for the current
                                            node.set(field.getName(), oldValue + item[:langPos] + t.joiner + value + t.joiner)

                    ''' raise event for metafield-type '''
                    if hasattr(t, "event_metafield_changed"):
                        t.event_metafield_changed(node, field)
            ''' raise event for node '''
            if hasattr(node, "event_metadata_changed"):
                node.event_metadata_changed()
            if node.get('updatetime') < str(now()):
                node.set("updatetime", str(format_date()))

        return nodes
Exemplo n.º 19
0
def renameHomeDir(user, newusername):
    if (existsHomeDir(user)):
        getHomeDir(user).setName(
            translate("user_directory", getDefaultLanguage()) + " (" + newusername + ")")
Exemplo n.º 20
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)

    if "metadata" in users.getHideMenusForUser(user):
        print "error 1"
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    access = AccessData(req)
    faultydir = users.getFaultyDir(user)
    metatypes = []
    nodes = []
    masklist = []
    err = 0

    # flag indicating change of node.name (fancytree node may have to be updated)
    # keep as integer
    # negative -> no change
    # else -> id of changed node
    flag_nodename_changed = -1

    for id in ids:
        node = tree.getNode(id)
        if not access.hasWriteAccess(node):
            print "error 2"
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        schema = node.getSchema()
        if schema not in metatypes:
            metatypes.append(schema)
        if len(nodes) == 0 or nodes[0].getSchema() == schema:
            nodes += [node]

    idstr = ",".join(ids)
    action = req.params.get('action', '').strip()

    logger.info("%s in editor metadata (action=%r): %r" %
                (user.getName(), action, [[n.id, n.name, n.type]for n in nodes]))

    for m in node.getType().getMasks(type="edit"):
        if access.hasReadAccess(m):
            masklist.append(m)

    if hasattr(node, "metaFields"):

        class SystemMask:

            def __init__(self, name, description, fields):
                self.name, self.description, self.fields = name, description, fields

            def getName(self):
                return self.name

            def getDescription(self):
                return self.description

            def getDefaultMask(self):
                return False

            def metaFields(self, lang=None):
                return self.fields

            def i_am_not_a_mask():
                pass
        masklist = [SystemMask(
            "settings", t(req, "settings"), node.metaFields(lang(req)))] + masklist

    default = None
    for m in masklist:
        if m.getDefaultMask():
            default = m
            break
    if not default and len(masklist):
        default = masklist[0]

    maskname = req.params.get("mask", node.get("edit.lastmask") or "editmask")
    if maskname == "":
        maskname = default.getName()

    mask = None
    for m in masklist:
        if maskname == m.getName():
            mask = m
            break

    if not mask and default:
        mask = default
        maskname = default.getName()

    for n in nodes:
        n.set("edit.lastmask", maskname)

    if not mask:
        return req.getTAL("web/edit/modules/metadata.html", {}, macro="no_mask")

    # context default for TAL interpreter
    ctx = {}
    ctx["user"] = user
    ctx["access"] = access
    ctx["metatypes"] = metatypes
    ctx["idstr"] = idstr
    ctx["node"] = nodes[0]  # ?
    ctx["flag_nodename_changed"] = flag_nodename_changed
    ctx["nodes"] = nodes
    ctx["masklist"] = masklist
    ctx["maskname"] = maskname
    ctx["language"] = lang(req)
    ctx["t"] = t

    if action == 'restore':
        vid = req.params.get('vid', '0')
        node = nodes[0].getActiveVersion()
        if (vid != '0' and vid != node.id):
            n = tree.getNode(vid)
            # Not active version
            if n.next_nid != '0':

                next = tree.getNode(n.next_nid)
                if next.prev_nid != '0':
                    next.removeChild(tree.getNode(next.prev_nid))
                next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    prev.setNextID(n.next_nid)
                    n.removeChild(prev)
                    next.addChild(prev)
                node.setNextID(n.id)

                n.setPrevID(node.id)
                n.setNextID('0')

                for pid in db.getParents(node.id):
                    parentNode = tree.getNode(pid)
                    parentNode.addChild(n)
                    parentNode.removeChild(node)
                n.addChild(node)

                nodes = [n]
                ids = [n.id]

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {'url': '?id=' + n.id + '&tab=metadata', 'pid':
                        None, 'flag_nodename_changed': flag_nodename_changed}

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if action == 'delete':
        vid = req.params.get('vid', '0')
        if (vid != '0'):
            node = nodes[0].getActiveVersion()
            n = tree.getNode(vid)

            if (vid != node.id):
                n.set("deleted", "true")
                for pid in db.getParents(n.id):
                    parentNode = tree.getNode(pid)
                    parentNode.removeChild(n)
                for cid in db.getChildren(n.id):
                    n.removeChild(tree.getNode(cid))
                if n.next_nid != '0' and n.prev_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    _next.addChild(tree.getNode(n.prev_nid))

                if n.next_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    if n.prev_nid != '0':
                        _next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    _prev = tree.getNode(n.prev_nid)
                    if n.next_nid != '0':
                        _prev.setNextID(n.next_nid)
            else:
                pids = db.getParents(n.id)

                # Active version
                prev = None
                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    while prev.prev_nid != None and prev.prev_nid != '0' and prev.get("deleted") == "true":
                        prev = tree.getNode(prev.prev_nid)

                if prev != None and prev.get("deleted") != "true":
                    prev.setNextID('0')
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.addChild(prev)
                    nodes = [prev]
                    ids = [prev.id]
                    n.set("deleted", "true")
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    for cid in db.getChildren(n.id):
                        n.removeChild(tree.getNode(cid))

                    if n.next_nid != '0' and n.prev_nid != '0':
                        _next = tree.getNode(n.next_nid)
                        _next.addChild(tree.getNode(n.prev_nid))

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + prev.id + '&tab=metadata', 'pid':
                            None, 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")
                else:
                    # Version 0
                    # Move node to trash
                    trashdir = users.getTrashDir(user)
                    trashdir.addChild(n)
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + pids[0] + '&tab=content', 'pid': pids[
                        0], 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if "edit_metadata" in req.params:
        # check and save items
        userdir = users.getHomeDir(users.getUserFromRequest(req))

        for node in nodes:
            if not access.hasWriteAccess(node) or node.id == userdir.id:
                print "error 3"
                req.setStatus(httpstatus.HTTP_FORBIDDEN)
                return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        logging.getLogger('usertracing').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').debug(pf(req.params))

        for node in nodes:
            node.set("updateuser", user.getName())
            if node.get('updatetime') < str(now()):
                node.set("updatetime", str(format_date()))

        if not hasattr(mask, "i_am_not_a_mask"):
            if (req.params.get('generate_new_version')):
                # Create new node version
                _ids = []
                _nodes = []
                for node in nodes:
                    n = node.createNewVersion(user)
                    n.set("system.version.comment", '(' + t(req, "document_new_version_comment") +
                          ')\n' + req.params.get('version_comment', ''))

                    # add all existing attributes to the new version node
                    for attr, value in node.items():
                        # do not overwrite existing attributes
                        # do not copy system attributes
                        if n.get(attr) != "" or attr.startswith("system."):
                            pass
                        else:
                            n.set(attr, value)

                    _nodes.append(n)
                    _ids.append(n.id)

                ids = _ids
                idstr = ",".join(ids)
                nodes = _nodes
                nodes = mask.updateNode(nodes, req)

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {
                    'url': '?id=' + nodes[0].id + '&tab=metadata',
                    'pid': None,
                }

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(
                    nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                ret += req.getTAL("web/edit/modules/metadata.html",
                                  data, macro="redirect")
            else:
                if nodes:
                    old_nodename = nodes[0].name
                nodes = mask.updateNode(nodes, req)
                if nodes:
                    new_nodename = nodes[0].name
                    if (old_nodename != new_nodename) and hasattr(nodes[0], 'isContainer') and nodes[0].isContainer():
                        # for updates of node label in editor tree
                        flag_nodename_changed = str(node.id)

        else:
            for field in mask.metaFields():
                msg = "in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %r, field.id: %r, field.name: %r, mask: %r, maskname: %r" % (
                    __name__, funcname(), field, field.id, field.getName(), mask, maskname)
                logger.debug(msg)
                field_name = field.getName()
                if field_name == 'nodename' and maskname == 'settings':
                    if '__nodename' in req.params:
                        field_name = '__nodename'  # no multilang here !
                    elif getDefaultLanguage() + '__nodename' in req.params:
                        # no multilang here !
                        field_name = getDefaultLanguage() + '__nodename'
                    value = req.params.get(field_name, None)
                    if value:
                        if value != node.name:
                            flag_nodename_changed = str(node.id)
                        for node in nodes:
                            node.setName(value)
                value = req.params.get(field_name, None)
                if value is not None:
                    for node in nodes:
                        node.set(field.getName(), value)
                else:
                    node.set(field.getName(), "")

    if "edit_metadata" in req.params or node.get("faulty") == "true":
        if not hasattr(mask, "i_am_not_a_mask"):
            req.params["errorlist"] = mask.validate(nodes)

    node_versions = nodes[0].getVersionList()
    update_date, creation_date = get_datelists(nodes)

    data = {}
    data["versions"] = node_versions
    data["creation_date"] = creation_date
    data["update_date"] = update_date
    data["err"] = err

    _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
    data["maskform"] = _maskform
    data["fields"] = _fields

    data.update(ctx)
    data["flag_nodename_changed"] = flag_nodename_changed

    ret += req.getTAL("web/edit/modules/metadata.html",
                      data, macro="edit_metadata")
    return ret
Exemplo n.º 21
0
    def getEditorHTML(self,
                      field,
                      value="",
                      width=400,
                      lock=0,
                      language=None,
                      required=None):

        # field may not be persisted as tree.Node and therefore may not have
        # an attribute "get"
        if hasattr(field, "get"):
            enable_multilang = bool(field.get('multilang'))
        else:
            enable_multilang = False

        if not language:
            language = getDefaultLanguage()

        try:
            field_node_name = field.name
        except:
            field_node_name = None

        context = {
            "lock": lock,
            "value": value,
            "width": width,
            "name": field_node_name,
            "field": field,
            "ident": str(field.id),
            "current_lang": language,
            "defaultlang": language,  # not the systems default language
            "languages": [],
            "langdict": {
                language: value
            },
            "language_snipper": self.language_snipper,
            "value_is_multilang": 'single',
            "multilang_display": 'display: none',
            "enable_multilang": enable_multilang,
            "expand_multilang": False,
            "required": self.is_required(required)
        }

        if enable_multilang:
            lang = [l for l in config_languages if l != language]
            context.update({
                "languages": lang,
                "langdict": self.str2dict(value),
                "value_is_multilang": {
                    True: 'multi',
                    False: 'single'
                }[self.has_language_cutter(value)],
                "multilang_display": {
                    True: '',
                    False: 'display: none'
                }[self.has_language_cutter(value)],
            })

            if enable_multilang and self.has_language_cutter(value):
                context["expand_multilang"] = True
            else:
                context["expand_multilang"] = False

        s = tal.getTAL("metadata/htmlmemo.html",
                       context,
                       macro="editorfield",
                       language=language)
        return s.replace("REPLACE_WITH_IDENT", str(field.id))
Exemplo n.º 22
0
def getContent(req, ids):

    reload(su)

    language = lang(req)
    user = users.getUserFromRequest(req)
    username = user.getName()
    #access = acl.AccessData(user=user)
    access = acl.AccessData(req=req)

    if "schedule" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    errors = []
    error = ''

    if "action" in req.params.keys():
        action = req.params.get("action")
        if action.startswith("get_fields_for_"):
            schedule_func = req.params.get("action").replace(
                "get_fields_for_", "")
            fields = su.fc_dict[schedule_func].getMetafields(lang(req))
            fieldDicts = su.fc_dict[schedule_func].getMetafieldDicts(lang(req))

            field_errors = []
            for i, field in enumerate(fields):
                field_errors.append(False)

            d = {
                'fields': fields,
                'fieldDicts': fieldDicts,
                'currentField': fields[0],
                'field_errors': field_errors,
                'currentFunction': schedule_func,
                'explain_func':
                su.fc_dict[schedule_func].getExplanation(language)
            }

            req.writeTAL("web/edit/modules/schedule.html",
                         d,
                         macro="schedule_func_show_fields_and_explanation")
            return ""

        elif action.startswith("load_schedule_"):
            schedule_id = action.replace("load_schedule_", "")
            try:
                schedule = tree.getNode(schedule_id)
            except:
                errors.append("edit_schedule_no_such_node_error")
                return "no such schedule error"

            if not schedule.type == "schedule" and access and access.hasWriteAccess(
                    schedule):
                return "schedule access error"

            schedule_func = schedule.get("function")
            if schedule_func:
                fields = su.fc_dict[schedule_func].getMetafields(lang(req))
                fieldDicts = su.fc_dict[schedule_func].getMetafieldDicts(
                    lang(req))
                d['explain_func'] = su.fc_dict[schedule_func].getExplanation(
                    language)
            else:
                fields = []
                fieldDicts = []
                d['explain_func'] = ""

            field_errors = []
            for i, field in enumerate(fields):
                field_errors.append(False)

            has_evaluation_errors = False
            for i, dfield in enumerate(fieldDicts):
                field_name = dfield['field_name']
                field_value = schedule.get(field_name)
                dfield['value'] = field_value
                field_validator_func = dfield['field_validator_func']
                if field_validator_func and not field_validator_func(
                        field_value):
                    dfield['evaluation_error'] = True
                    has_evaluation_errors = True
                else:
                    dfield['evaluation_error'] = False

            if has_evaluation_errors:
                error = "\n<br/>\n".join([
                    error,
                    t(language, 'edit_schedule_field_validation_error')
                ])

            d = {
                'fields': fields,
                'fieldDicts': fieldDicts,
                'currentField': fields[0],
                'field_errors': field_errors,
                'currentFunction': schedule_func,
            }

            req.writeTAL("web/edit/modules/schedule.html",
                         d,
                         macro="schedule_func_show_fields_and_explanation")
            return ""

        elif action == "delete_node_from_schedule":

            node_id = req.params.get('node_id', None)

            if node_id:
                pass
            else:
                errors.append("edit_schedule_unexpected_no_such_node")

            schedule_id = req.params.get('schedule_id', None)
            if schedule_id:
                try:
                    schedule = tree.getNode(schedule_id)
                except:
                    errors.append(
                        "edit_schedule_unexpected_no_such_schedule_node")
            else:
                errors.append("edit_schedule_unexpected_no_such_schedule_node")

            delete_errors = su.deleteNodeIDsFromSchedule([node_id],
                                                         schedule_id,
                                                         access=access)

            if not delete_errors:
                msg = "user '%s' removed node %s from schedule '%s' (%s)" % (
                    username, node_id, schedule.name, schedule_id)
                logging.getLogger("backend").info(msg)
            else:
                error_msg = ", ".join([t(language, e) for e in delete_errors])
                msg = "user '%s' tried to remove node %s from schedule '%s' (%s): %s" % (
                    username, node_id, schedule.name, schedule_id, error_msg)
                logging.getLogger("backend").error(msg)

            errors += delete_errors

            s = {}
            s['errors'] = errors
            s['delete_errors'] = delete_errors

            s['delete_table_rows'] = ['sid_%s' % schedule_id]

            res_msg = req.params.get("jsoncallback") + "(%s)" % json.dumps(
                s, indent=4)
            req.write(res_msg)
            return ""

        elif action == "delete_schedule":
            schedule_id = req.params.get('schedule_id', None)
            if schedule_id:
                try:
                    schedule = tree.getNode(schedule_id)
                except:
                    errors.append(
                        "edit_schedule_unexpected_no_such_schedule_node")
            else:
                errors.append("edit_schedule_unexpected_no_such_schedule_node")

            delete_errors = su.deleteSchedule(schedule_id, access=access)

            if not delete_errors:
                msg = "user '%s' removed schedule %s (%s)" % (
                    username, schedule.name, schedule_id)
                logging.getLogger("backend").info(msg)
            else:
                error_msg = ", ".join([t(language, e) for e in delete_errors])
                msg = "user '%s' tried to remove schedule '%s' (%s): %s" % (
                    username, schedule.name, schedule_id, error_msg)
                logging.getLogger("backend").error(msg)

            errors += delete_errors

            s = {}
            s['errors'] = errors
            s['delete_errors'] = delete_errors
            s['delete_table_rows'] = ['sid_%s' % schedule_id]

            res_msg = req.params.get("jsoncallback") + "(%s)" % json.dumps(
                s, indent=4)
            req.write(res_msg)
            return ""

        elif action == "load_table_nid2schedules":

            nid2schedules, schedule2nids, nid2active_schedules = su.getSchedulesForIds(
                ids, access=access, language=language)

            nid2schedules_attrs = {}
            for nid in nid2schedules:
                nid2schedules_attrs[nid] = [[
                    s.id, s.name, s.get("single_trigger")
                ] for s in nid2schedules[nid]['schedule_list']]

            d = {}
            d['nid2schedules'] = nid2schedules
            d['nid2active_schedules'] = nid2active_schedules
            d['errors'] = ['testerror1', 'testerror1']
            d['date'] = datetime.now().isoformat()
            d['isActive'] = su.isActive

            req.writeTAL("web/edit/modules/schedule.html",
                         d,
                         macro="table_nid2schedules")
            return ""

        elif action == "load_table_schedule2nids":

            nid2schedules, schedule2nids, nid2active_schedules = su.getSchedulesForIds(
                ids, access=access, language=language)

            nid2schedules_attrs = {}
            for nid in nid2schedules:
                nid2schedules_attrs[nid] = [[
                    s.id, s.name, s.get("single_trigger")
                ] for s in nid2schedules[nid]['schedule_list']]

            d = {}
            d['nid2schedules'] = nid2schedules
            d['schedule2nids'] = schedule2nids
            d['nid2active_schedules'] = nid2active_schedules
            d['errors'] = ['testerror1', 'testerror1']
            d['date'] = datetime.now().isoformat()
            d['isActive'] = su.isActive

            req.writeTAL("web/edit/modules/schedule.html",
                         d,
                         macro="table_schedule2nids")
            return ""

    nid2schedules, schedule2nids, nid2active_schedules = su.getSchedulesForIds(
        ids, access=access, language=language)

    datetime_str = req.params.get("datetime", "").strip()
    datetime_error = False
    has_evaluation_errors = False

    if datetime_str:
        patter = "^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$"
        if not re.match(patter, datetime_str):
            error = t(
                language,
                "edit_schedule_input_datetime_format_error") % datetime_str
            datetime_error = True
        else:
            try:
                parser_test_result = datetime.strptime(
                    datetime_str, "%Y-%m-%dT%H:%M")  # "%Y-%m-%dT%H:%M:%S.%f"
            except:
                parser_test_result = None
                error = t(
                    language,
                    "edit_schedule_input_datetime_format_error") % datetime_str
                datetime_error = True
            if parser_test_result and datetime_str <= datetime.now().isoformat(
            ):
                error = t(language,
                          "edit_schedule_input_datetime_already_past_error"
                          ) % datetime_str
                datetime_error = True
    elif "submit" in req.params:
        error = t(language,
                  "edit_schedule_input_datetime_format_error") % datetime_str
        datetime_error = True

    schedule_id = req.params.get("schedule_id", "")
    if schedule_id:
        schedule = tree.getNode(schedule_id)
        if access and not access.hasWriteAccess(schedule):
            errors.append("edit_schedule_no_access_error")
            schedule = None
            current_function = req.params.get('schedule_function', '')
        else:
            current_function = schedule.get("function")
    else:
        schedule = None
        current_function = req.params.get('schedule_function', '')

    if "submit" in req.params or "submit_run_now" in req.params:
        current_function = req.params.get('schedule_function', '')
        if current_function in su.fc_dict:
            field_descriptors = su.fc_dict[
                current_function].getFieldDescriptors()
            field_errors = []
        else:
            # should not happen
            msg = "-> unexpected error: 'non-existant schedule function' requested in module %s: :s" % (
                str(__file__), str(inspect.currentframe().f_lineno))
            print msg
            logging.getLogger("backend").error(msg)

    d = {"id": req.params.get("id")}

    # nodes list is used to display icons in upper part of page
    # additional nodes should not / will not be shown there
    nodes = []
    for nid in ids:
        node = tree.getNode(nid)
        nodes.append(node)

    d['nodes'] = nodes

    if current_function in su.fc_dict:
        fields = su.fc_dict[current_function].getMetafields(lang(req))
        fieldDicts = su.fc_dict[current_function].getMetafieldDicts(lang(req))
        d['explain_func'] = su.fc_dict[current_function].getExplanation(
            language)
    else:
        fields = []
        fieldDicts = []
        d['explain_func'] = ""

    if not "submit_run_now" in req.params:
        has_evaluation_errors = datetime_error

    if schedule and not "submit" in req.params and not "submit_run_now" in req.params:
        for i, dfield in enumerate(fieldDicts):
            field_name = dfield['field_name']
            field_value = schedule.get(field_name)
            dfield['value'] = field_value
            field_validator_func = dfield['field_validator_func']
            if field_validator_func and not field_validator_func(field_value):
                dfield['evaluation_error'] = True
                has_evaluation_errors = True
            else:
                dfield['evaluation_error'] = False
    else:
        for i, dfield in enumerate(fieldDicts):
            field_name = dfield['field_name']
            # m_* classes from metadata/ are not multilingual for schedules
            # their getEditorHTML methods are used to display schedule node
            # attributes
            field_value = req.params.get(
                getDefaultLanguage() + '__' + field_name, '')
            dfield['value'] = field_value
            field_validator_func = dfield['field_validator_func']
            if field_validator_func and not field_validator_func(field_value):
                dfield['evaluation_error'] = True
                has_evaluation_errors = True
            else:
                dfield['evaluation_error'] = False

    additional_nodes_str = req.params.get("additional_nodes", "")
    additional_nodes_error = False
    additional_nodes_bad_ids = []

    try:
        additional_nodes_id_list = [
            str(int(nid.strip()))
            for nid in additional_nodes_str.strip().split(";") if nid.strip()
        ]
    except:
        has_evaluation_errors = True
        additional_nodes_error = True
        additional_nodes_id_list = []
        errors.append(
            "edit_schedule_additional_nodes_list_not_semikolon_separated_list_of_integers"
        )

    if not additional_nodes_error:
        collections_root = tree.getRoot("collections")
        for nid in additional_nodes_id_list:
            n = None
            try:
                n = tree.getNode(nid)
            except tree.NoSuchNodeError as e:
                has_evaluation_errors = True
                additional_nodes_error = True
                if nid not in additional_nodes_bad_ids:
                    additional_nodes_bad_ids.append(nid)
            if n and (not isDescendantOf(n, collections_root)
                      or not access.hasWriteAccess(n)):
                # to do? discussion: override collections rectriction for
                # admins ?
                has_evaluation_errors = True
                additional_nodes_error = True
                if nid not in additional_nodes_bad_ids:
                    additional_nodes_bad_ids.append(nid)

    if additional_nodes_bad_ids:
        has_evaluation_errors = True
        additional_nodes_error = True
        errors.append(
            t(language, "edit_schedule_additional_nodes_bad_ids") +
            (";".join(additional_nodes_bad_ids)))

    if has_evaluation_errors:
        errors.append('edit_schedule_field_validation_error')
        error = "\n<br/>\n".join(
            map(lambda x: t(language, x), [error] + errors))

    d['fields'] = fields
    d['fieldDicts'] = fieldDicts
    d['field_errors'] = [False] * len(fields)
    d['currentField'] = None
    d['currentFunction'] = current_function

    d['error'] = error

    d['fc_dict'] = su.filter_access(su.fc_dict, access)

    d['input_datetime'] = datetime_str
    d['input_datetime_error'] = datetime_error

    d['nid2schedules'] = nid2schedules
    d['schedule2nids'] = schedule2nids
    d['nid2active_schedules'] = nid2active_schedules

    d['loaded_schedule'] = schedule

    if schedule:
        d['loaded_schedule_id'] = str(schedule.id)
    else:
        d['loaded_schedule_id'] = None

    d['mklink'] = su.mklink

    d['language'] = language
    d['t'] = t
    d['isActive'] = su.isActive

    d['result'] = ''

    d['created_new_schedule'] = False

    d['additional_nodes'] = additional_nodes_str
    d['additional_nodes_error'] = additional_nodes_error

    d['submitbutton_run_now_label'] = t(language,
                                        'edit_schedule_submit_run_now_button')
    d['edit_schedule_submit_run_now_button_confirm'] = t(
        language, 'edit_schedule_submit_run_now_button_confirm')
    d['edit_schedule_delete_schedule_confirm'] = t(
        language, 'edit_schedule_delete_schedule_confirm')

    if has_evaluation_errors and not ('submit_run_now' in req.params):
        return req.getTAL("web/edit/modules/schedule.html",
                          d,
                          macro="schedule_popup")

    new_schedule = None
    if (not schedule
            and "submit" in req.params) or "submit_run_now" in req.params:

        new_schedule_name = user.name + \
            "_created_at_" + datetime.now().isoformat()
        new_schedule = tree.Node(new_schedule_name, 'schedule')

        username = user.getName()
        new_schedule.setAccess("write", "{user %s}" % username)

        if not "submit_run_now" in req.params:
            schedules = tree.getRoot("schedules")
            schedules.addChild(new_schedule)

            msg = "user '%s' created new schedule '%s' (%s), trigger='%s', function='%s', nodelist='%s'" % (
                username, new_schedule.name, str(
                    new_schedule.id), datetime_str, d['currentFunction'],
                new_schedule.get('nodelist'))
            logging.getLogger("backend").info(msg)

            d['result'] = t(language,
                            'edit_schedule_result_new_schedule_created')
            d['created_new_schedule'] = True
        else:
            msg = "user '%s' created temporary schedule '%s' (%s), trigger='%s', function='%s', nodelist='%s'" % (
                username, new_schedule.name, str(
                    new_schedule.id), datetime_str, d['currentFunction'],
                new_schedule.get('nodelist'))
            logging.getLogger("backend").info(msg)

            d['result'] = t(language,
                            'edit_schedule_result_temporary_schedule_created')
            d['created_temporary_schedule'] = True

    elif (schedule) and ("submit" in req.params):
        new_schedule = schedule
        msg = "user '%s' is editing schedule '%s' (%s), trigger='%s', function='%s', nodelist='%s'" % (
            username, new_schedule.name, str(new_schedule.id), datetime_str,
            d['currentFunction'], new_schedule.get('nodelist'))
        logging.getLogger("backend").info(msg)
        new_schedule.set("system.edited", datetime.now().isoformat())

        d['result'] = t(language,
                        'edit_schedule_result_existing_schedule_edited')

    if new_schedule:
        for i, dfield in enumerate(fieldDicts):
            field_name = dfield['field_name']
            field_value = dfield['value']
            new_schedule.set(field_name, field_value)

        ids_plus_additional_nodes = ids
        for nid in additional_nodes_id_list:
            if nid not in ids_plus_additional_nodes:
                ids_plus_additional_nodes.append(nid)

        new_schedule.set('function', d['currentFunction'])
        new_schedule.set('nodelist', ",".join(ids_plus_additional_nodes))
        new_schedule.set('single_trigger', datetime_str)

        if datetime.now().isoformat() < datetime_str:
            new_schedule.set('single_trigger_status', '')

        if "submit_run_now" in req.params:
            new_schedule.set("single_trigger", datetime.now().isoformat())
            has_fired, has_error, TT = su.handle_single_trigger(
                new_schedule,
                datetime.now().isoformat(), su.OUT)
            if has_error:
                _error1 = d['error']
                _error2 = "<br/>\n".join(
                    map(lambda x: (t(language, str(x))), TT))
                _error = "<br/>\n".join([_error1, _error2])
                d['error'] = _error

    return req.getTAL("web/edit/modules/schedule.html",
                      d,
                      macro="schedule_popup")
Exemplo n.º 23
0
def _handle_edit_metadata(req, mask, nodes):
    # check and save items
    user = current_user
    userdir = user.home_dir
    flag_nodename_changed = -1
    form = req.form

    for node in nodes:
        if not node.has_write_access() or node is userdir:
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    if not hasattr(mask, "i_am_not_a_mask"):
        if form.get('generate_new_version'):
            # Create new node version
            comment = u'({})\n{}'.format(t(req, "document_new_version_comment"), form.get('version_comment', ''))

            for node in nodes:
                with node.new_tagged_version(comment=comment, user=user):
                    mask.update_node(node, req, user)
        else:
            # XXX: why check here?
            # if nodes:
            old_nodename = nodes[0].name

            for node in nodes:
                mask.update_node(node, req, user)

            db.session.commit()

            # XXX: why check here?
            # if nodes:
            new_nodename = nodes[0].name
            if ( len(nodes) == 1 or old_nodename != new_nodename) and isinstance(nodes[0], Container):
                # for updates of node label in editor tree
                flag_nodename_changed = ustr(nodes[0].id)

    else:
        for field in mask.metaFields():
            logg.debug("in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %s, field.id: %s, field.name: %s, mask: %s, maskname: %s",
                __name__, funcname(), field, field.id, field.name, mask, mask.name)
            field_name = field.name
            if field_name == 'nodename' and mask.name == 'settings':
                if '__nodename' in form:
                    field_name = '__nodename'  # no multilang here !
                elif getDefaultLanguage() + '__nodename' in form:
                    # no multilang here !
                    field_name = getDefaultLanguage() + '__nodename'
                value = form.get(field_name, None)
                if value:
                    if value != node.name:
                        flag_nodename_changed = ustr(node.id)
                    for node in nodes:
                        node.name = value
            value = form.get(field_name, None)
            if value is not None:
                for node in nodes:
                    node.set(field.name, value)
            else:
                node.set(field.getName(), "")
        db.session.commit()

    return flag_nodename_changed
Exemplo n.º 24
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)

    if "metadata" in users.getHideMenusForUser(user):
        print "error 1"
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    access = AccessData(req)
    faultydir = users.getFaultyDir(user)
    metatypes = []
    nodes = []
    masklist = []
    err = 0

    # flag indicating change of node.name (fancytree node may have to be updated)
    # keep as integer
    # negative -> no change
    # else -> id of changed node
    flag_nodename_changed = -1

    for id in ids:
        node = tree.getNode(id)
        if not access.hasWriteAccess(node):
            print "error 2"
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        schema = node.getSchema()
        if schema not in metatypes:
            metatypes.append(schema)
        if len(nodes) == 0 or nodes[0].getSchema() == schema:
            nodes += [node]

    idstr = ",".join(ids)
    action = req.params.get('action', '').strip()

    logger.info("%s in editor metadata (action=%r): %r" %
                (user.getName(), action, [[n.id, n.name, n.type]for n in nodes]))

    for m in node.getType().getMasks(type="edit"):
        if access.hasReadAccess(m):
            masklist.append(m)

    if hasattr(node, "metaFields"):

        class SystemMask:

            def __init__(self, name, description, fields):
                self.name, self.description, self.fields = name, description, fields

            def getName(self):
                return self.name

            def getDescription(self):
                return self.description

            def getDefaultMask(self):
                return False

            def metaFields(self, lang=None):
                return self.fields

            def i_am_not_a_mask():
                pass
        masklist = [SystemMask(
            "settings", t(req, "settings"), node.metaFields(lang(req)))] + masklist

    default = None
    for m in masklist:
        if m.getDefaultMask():
            default = m
            break
    if not default and len(masklist):
        default = masklist[0]

    maskname = req.params.get("mask", node.get("edit.lastmask") or "editmask")
    if maskname == "":
        maskname = default.getName()

    mask = None
    for m in masklist:
        if maskname == m.getName():
            mask = m
            break

    if not mask and default:
        mask = default
        maskname = default.getName()

    for n in nodes:
        n.set("edit.lastmask", maskname)

    if not mask:
        return req.getTAL("web/edit/modules/metadata.html", {}, macro="no_mask")

    # context default for TAL interpreter
    ctx = {}
    ctx["user"] = user
    ctx["access"] = access
    ctx["metatypes"] = metatypes
    ctx["idstr"] = idstr
    ctx["node"] = nodes[0]  # ?
    ctx["flag_nodename_changed"] = flag_nodename_changed
    ctx["nodes"] = nodes
    ctx["masklist"] = masklist
    ctx["maskname"] = maskname
    ctx["language"] = lang(req)
    ctx["t"] = t

    if action == 'restore':
        vid = req.params.get('vid', '0')
        node = nodes[0].getActiveVersion()
        if (vid != '0' and vid != node.id):
            n = tree.getNode(vid)
            # Not active version
            if n.next_nid != '0':

                next = tree.getNode(n.next_nid)
                if next.prev_nid != '0':
                    next.removeChild(tree.getNode(next.prev_nid))
                next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    prev.setNextID(n.next_nid)
                    n.removeChild(prev)
                    next.addChild(prev)
                node.setNextID(n.id)

                n.setPrevID(node.id)
                n.setNextID('0')

                for pid in db.getParents(node.id):
                    parentNode = tree.getNode(pid)
                    parentNode.addChild(n)
                    parentNode.removeChild(node)
                n.addChild(node)

                nodes = [n]
                ids = [n.id]

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {'url': '?id=' + n.id + '&tab=metadata', 'pid':
                        None, 'flag_nodename_changed': flag_nodename_changed}

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if action == 'delete':
        vid = req.params.get('vid', '0')
        if (vid != '0'):
            node = nodes[0].getActiveVersion()
            n = tree.getNode(vid)

            if (vid != node.id):
                n.set("deleted", "true")
                for pid in db.getParents(n.id):
                    parentNode = tree.getNode(pid)
                    parentNode.removeChild(n)
                for cid in db.getChildren(n.id):
                    n.removeChild(tree.getNode(cid))
                if n.next_nid != '0' and n.prev_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    _next.addChild(tree.getNode(n.prev_nid))

                if n.next_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    if n.prev_nid != '0':
                        _next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    _prev = tree.getNode(n.prev_nid)
                    if n.next_nid != '0':
                        _prev.setNextID(n.next_nid)
            else:
                pids = db.getParents(n.id)

                # Active version
                prev = None
                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    while prev.prev_nid != None and prev.prev_nid != '0' and prev.get("deleted") == "true":
                        prev = tree.getNode(prev.prev_nid)

                if prev != None and prev.get("deleted") != "true":
                    prev.setNextID('0')
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.addChild(prev)
                    nodes = [prev]
                    ids = [prev.id]
                    n.set("deleted", "true")
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    for cid in db.getChildren(n.id):
                        n.removeChild(tree.getNode(cid))

                    if n.next_nid != '0' and n.prev_nid != '0':
                        _next = tree.getNode(n.next_nid)
                        _next.addChild(tree.getNode(n.prev_nid))

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + prev.id + '&tab=metadata', 'pid':
                            None, 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")
                else:
                    # Version 0
                    # Move node to trash
                    trashdir = users.getTrashDir(user)
                    trashdir.addChild(n)
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + pids[0] + '&tab=content', 'pid': pids[
                        0], 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if "edit_metadata" in req.params:
        # check and save items
        userdir = users.getHomeDir(users.getUserFromRequest(req))

        for node in nodes:
            if not access.hasWriteAccess(node) or node.id == userdir.id:
                print "error 3"
                req.setStatus(httpstatus.HTTP_FORBIDDEN)
                return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        logging.getLogger('usertracing').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').debug(pf(req.params))

        for node in nodes:
            node.set("updateuser", user.getName())
            if node.get('updatetime') < str(now()):
                node.set("updatetime", str(format_date()))

        if not hasattr(mask, "i_am_not_a_mask"):
            if (req.params.get('generate_new_version')):
                # Create new node version
                _ids = []
                _nodes = []
                for node in nodes:
                    n = node.createNewVersion(user)
                    n.set("system.version.comment", '(' + t(req, "document_new_version_comment") +
                          ')\n' + req.params.get('version_comment', ''))

                    # add all existing attributes to the new version node
                    for attr, value in node.items():
                        # do not overwrite existing attributes
                        # do not copy system attributes
                        if n.get(attr) != "" or attr.startswith("system."):
                            pass
                        else:
                            n.set(attr, value)

                    _nodes.append(n)
                    _ids.append(n.id)

                ids = _ids
                idstr = ",".join(ids)
                nodes = _nodes
                nodes = mask.updateNode(nodes, req)

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {
                    'url': '?id=' + nodes[0].id + '&tab=metadata',
                    'pid': None,
                }

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(
                    nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                ret += req.getTAL("web/edit/modules/metadata.html",
                                  data, macro="redirect")
            else:
                if nodes:
                    old_nodename = nodes[0].name
                nodes = mask.updateNode(nodes, req)
                if nodes:
                    new_nodename = nodes[0].name
                    if (old_nodename != new_nodename) and hasattr(nodes[0], 'isContainer') and nodes[0].isContainer():
                        # for updates of node label in editor tree
                        flag_nodename_changed = str(node.id)

        else:
            for field in mask.metaFields():
                msg = "in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %r, field.id: %r, field.name: %r, mask: %r, maskname: %r" % (
                    __name__, funcname(), field, field.id, field.getName(), mask, maskname)
                logger.debug(msg)
                field_name = field.getName()

                if field_name == 'nodename' and maskname == 'settings':
                    if '__nodename' in req.params:
                        field_name = '__nodename'  # no multilang here !
                    elif getDefaultLanguage() + '__nodename' in req.params:
                        # no multilang here !
                        field_name = getDefaultLanguage() + '__nodename'
                    value = req.params.get(field_name, None)
                    if value:
                        if value != node.name:
                            flag_nodename_changed = str(node.id)
                        for node in nodes:
                            node.setName(value)
                elif field_name in ('repec.code', 'repec.provider') and maskname == 'settings':
                    if '__' + field_name in req.params:
                        field_name = '__' + field_name  # no multilang here!
                    elif getDefaultLanguage() + '__' + field_name in req.params:
                        field_name = getDefaultLanguage() + '__' + field_name  # no multilang here!

                value = req.params.get(field_name, None)

                if value is not None:
                    for node in nodes:
                        node.set(field.getName(), value)
                else:
                    node.set(field.getName(), "")

    if "edit_metadata" in req.params or node.get("faulty") == "true":
        if not hasattr(mask, "i_am_not_a_mask"):
            req.params["errorlist"] = mask.validate(nodes)

    node_versions = nodes[0].getVersionList()
    update_date, creation_date = get_datelists(nodes)

    data = {}
    data["versions"] = node_versions
    data["creation_date"] = creation_date
    data["update_date"] = update_date
    data["err"] = err

    _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
    data["maskform"] = _maskform
    data["fields"] = _fields

    data.update(ctx)
    data["flag_nodename_changed"] = flag_nodename_changed

    ret += req.getTAL("web/edit/modules/metadata.html",
                      data, macro="edit_metadata")
    return ret
Exemplo n.º 25
0
def renameHomeDir(user, newusername):
    if (existsHomeDir(user)):
        getHomeDir(user).setName(
            translate("user_directory", getDefaultLanguage()) + " (" +
            newusername + ")")
Exemplo n.º 26
0
def buildHomeDirName(username):
    """
    make a string for naming the home directory in the browsing tree in the editor
    """
    return translate("user_directory", getDefaultLanguage()) + " (" + username + ")"