checkandfix.py 27.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
# -*- coding: utf-8 -*-
""" invenio_tools.checkandfix

"""
import re
import regex

from base import OAI_URL, REG_OAI, REG_YEAR
from exception import CheckException
from filters import CLEAN_REVIEW
11
from gluon import current
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
from inveniostore import InvenioStore
from marc12 import Marc12
from plugin_dbui import get_id


DECODE_ARXIV = re.compile("arXiv:(\d{2})(\d{2})\.")

# Decode submitted date: DD MMM YYYY or DD MM YYY
DECODE_DD_MMM_YYYY = re.compile(r"(\d{1,2}) *([A-Za-z]{3}) *(\d{4})")
DECODE_DD_MM_YYYY = re.compile(r"(\d{1,2}) +(\d{1,2}) +(\d{4})")
DECODE_YYYY = re.compile("^(\d{4})$")

# Decode publication reference:
#  Phys. Rev. Lett. 113, 032001 (2014)
#  Eur. Phys. J. C (2014) 74:2883
DECODE_REF = [re.compile("(?P<p>[A-Za-z\. ]+) +(?P<v>\d+),? +(?P<c>[\d-]+) +\((?P<y>[\d]+)\)"),
              re.compile("(?P<p>[A-Za-z\. ]+) +\((?P<y>\d+)\) +(?P<v>[\d]+):(?P<c>[\d-]+)")]

MONTHS = {u'Jan':'01',
          u'Feb':'02',
          u'Fev':'02',
          u'Mar':'03',
          u'Apr':'04',
          u'Avr':'04',
          u'May':'05',
          u'Mai':'05',
          u'Jun':'06',
          u'Jul':'07',
          u'Aug':'08',
          u'Sep':'09',
          u'Oct':'10',
          u'Nov':'11',
          u'Dec':'12'}

46 47 48 49
MSG_NO_AUTHOR = "Reject no author(s)"
MSG_NO_CONF = "Reject no conference information"
MSG_NO_COUNTRY = "Reject invalid country"
MSG_NO_DATE = "Reject no submission date"
50
MSG_NO_MY_AUTHOR = "Reject no authors of my institute"
51 52 53
MSG_NO_OAI = "Reject no OAI identifier"
MSG_NO_REF = "Reject incomplete paper reference"
MSG_NO_YEAR = "Reject no publication year"
54

55
MSG_TEMPORARY_RECORD = "Temporary record"
56

57 58 59
MSG_TO_MANY_DATE = "Reject to many submit date"
MSG_TO_MANY_FAUTHOR = "Reject to many first author"
MSG_TO_MANY_YEAR = "Reject to many year"
60

61 62 63
MSG_WELL_FORMED_COLLABORATION = "Reject collaboration is not well formed"
MSG_WELL_FORMED_CONF_DATES = "Reject conference dates is not well formed"
MSG_WELL_FORMED_DATE = "Reject submission date is not well formed"
64

65 66
MSG_WELL_FORMED_EDITOR = "Reject editor is not well formed"
MSG_WELL_FORMED_OAI = "Reject OAI is not well formed"
67 68 69 70 71 72 73 74 75 76

OAI_INVENIO = "oai:%s:%s"

REG_COLLABORATION = re.compile(regex.REG_COLLABORATION)
REG_CONF = re.compile("^C\d+-\d+-\d+(\.\d+)?$")
REG_CONF_DATES_1 = re.compile("(\d+) *-? *(\d+) *([A-Z][a-z]{2}) *(\d{4})")
REG_CONF_DATES_2 = re.compile("(\d+) *([A-Z][a-z]{2}) *-? *(\d+) *([A-Z][a-z]{2}) *(\d{4})")
REG_CONF_DATES = re.compile(regex.REG_CONF_DATES)
REG_SUBMITTED = re.compile(regex.REG_SUBMITTED)

77 78
UNIVERSITY = "University"

79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
def load_record(host, record_id):
    """Helper function to load a single record from an invenio store.

    Args:
        host (str): host of the store. Either cds.cern.ch or inspirhep.net.
        record_id (integer): the record identifier

    Returns:
        Record: the decoded record

    """
    store = InvenioStore(host)
    xml = store.get_record(record_id)

    svc = Marc12()
    return svc(xml)[0]


98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
class CheckAndFix(object):
    """Tool to check and repair the content of the Marc12 record:

            - Check the validity of the record.
            - Conference information are added for talk and proceeding.
            - Fix as far as possible inconsistencies and non-conformity.

    They can be call separately or in one go.
    Most of the method raise the CheckException when something went wrong.

    """
    def _get_conference(self, host, id, key):
        """Get the conference data associated to the record.
        The conference is identified by its id or key.

        @type host: unicode
        @param host:

        @type id: unicode
        @param id:

        @type key: unicode
        @param key:

        @rtype: L{Record}
        @return: The conference record

        @raise CheckException:

        """
        cds = InvenioStore(host)
        marc12 = Marc12()

        # search the conference by id the preferred method
        if id:
            xml = cds.get_record(id)
            for conference in marc12(xml):
                if conference.id() == id:
                    return conference

        # search the conference by key if the previous method failed.
        # the method depends on the store.
        if key:
            ids = []

            if cds._host.startswith('inspirehep'):
                key = key.replace('/', '-')
                if REG_CONF.match(key):
                    ids = cds.get_ids(cc='Conferences', p='111__g:%s' % key)

            else:
                ids = cds.get_ids(p=key)

            for id in ids:
                xml = cds.get_record(id)
                for conference in marc12(xml):
                    if conference.conference_key() == key:
                        return conference

        raise CheckException(MSG_NO_CONF)

    def _recover_submitted(self, record):
        """Recover submitted date using conference, preprint or thesis
        information.

        @type record: L{Record}
        @param record:

        @rtype: unicode
        @return: empty when procedure failed

        """
        val = u''
        if record.is_conference_data():

            # INSPIREHEP start date encoded as 2014-12-31
            if "x" in record["111"]:
                val = record["111"]["x"]

            # CDS end date encoded as 20141231
            elif "z" in record["111"]:
                val = record["111"]["z"]
                val = "%s-%s-%s" % (val[0:4], val[4:6], val[6:8])

        elif record.is_thesis():
            val = record.these_defense()

        else:
            report = record.preprint_number()
            if report:
                m_arxiv = DECODE_ARXIV.match(report)
                if m_arxiv:
                    val = "20%s-%s" % (m_arxiv.group(1), m_arxiv.group(2))

        return val

    def _repair_paper_reference(self, record):
        """Repair paper reference.
        The recovery procedure use the "o" field (invenio):

            - Eur. Phys. J. C (2014) 74:2883
            - Phys. Rev. Lett. 113, 032001 (2014)

        in order to extract editor, volume, year and page data.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        # standard case
        if isinstance(record["773"], dict):

            if "o" in record["773"]:
                for reg in DECODE_REF:
                    m = reg.match(record["773"]["o"])
                    if m:
                        record["773"]["p"] = m.group("p")
                        record["773"]["v"] = m.group("v")
                        record["773"]["y"] = m.group("y")
                        record["773"]["c"] = m.group("c")
                        return

            raise CheckException(MSG_NO_REF)

        # list case -- paper with erratum
        elif isinstance(record["773"], list):

            for i in range(len(record["773"])):

                if "o" in record["773"][i]:
                    fixed = False
                    for reg in DECODE_REF:
                        m = reg.match(record["773"][i]["o"])
                        if m:
                            record["773"][i]["p"] = m.group("p")
                            record["773"][i]["v"] = m.group("v")
                            record["773"][i]["y"] = m.group("y")
                            record["773"][i]["c"] = m.group("c")
                            fixed = True
                            break

                    if not fixed:
                        raise CheckException(MSG_NO_REF)
                else:
                    raise CheckException(MSG_NO_REF)

        # case not expected
        else:
            raise CheckException(MSG_NO_REF)

    def authors(self, record):
        """Check the consistency between author fields.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """

        if "100" not in record and "700" not in record:
            raise CheckException(MSG_NO_AUTHOR)

        if "100" in record and isinstance(record["100"], list):
            # from time to time first authors is duplicated
            li = []
            for di in record["100"]:
                if di not in li:
                    li.append(di)

            if len(li) == 1:
                record["100"] = li[0]
            else:
                raise CheckException(MSG_TO_MANY_FAUTHOR)

        # alias
        authors, first_author = None, None

        if "700" in record:
            authors = record["700"]

        if "100" in record:
            first_author = record["100"]

        # first author not defined
        if not first_author and authors:

            if isinstance(record["700"], list):
                record["100"] = record["700"][0]
            else:
                record["100"] = record["700"]

        # first author not in the authors list
        elif first_author and authors:
            if isinstance(record["700"], list):
                if record["100"]["a"] != record["700"][0]["a"]:
                    record["700"].insert(0, record["100"])

            elif record["700"]["a"] != record["100"]["a"]:
                record["700"] = [record["100"], record["700"]]

        # only the first author is defined
        elif first_author and not authors:
            record["700"] = record["100"]

    def clean_erratum(self, record):
        """Clean record with erratum by removing them.

        @note: after this check the editor, volume, page and
        paper year field contains one entry.

        @type record: L{Record}
        @param record:

        """
        if not record.is_with_erratum():
            return

        # use the simplest algorithm by selecting the first entry in the list
        # fare to assume that the article is published first.
        record["773"] = record["773"][0]

        # treat year and submitted date
        for k in ("260", "269"):
            if k in record and isinstance(record[k], list):
                record[k] = record[k][0]

    def collaboration(self, record):
        """Check that the collaboration is well formed.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        val = record.collaboration()
        if val and not REG_COLLABORATION.match(val):
            raise CheckException(MSG_WELL_FORMED_COLLABORATION)

    def conference(self, record):
        """Get the conference data associated to a talk/proceeding and
        push them in the record.

        @note: the conference is looks by its key.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        # conference information are available, i.e proceeding
        if "111" in record:
            return

        # alias
        host = record.host()
        key = record.reference_conference_key()

        # for talk or proceeding a key is always defined
        if not key:
            raise CheckException(MSG_NO_CONF)

        # get conference information
        id = record.reference_conference_id()
        conference = self._get_conference(host, id, key)

        # protection id can be a reference to other object like book
        if "111" not in conference:
            return

        # copy conference information in the current record
        # the conference URL is in 8564u
        record[u"111"] = conference["111"]
        if "8564" in conference:
            record[u"8564"] = conference["8564"]

        # check country information (all valid countries have been enter once)
        db = current.globalenv['db']
        id = get_id(db.countries, country=record.conference_country())
        if not id:
            raise CheckException(MSG_NO_COUNTRY)

        # check and fix conference date
        value = record[u"111"]["d"]
        m = REG_CONF_DATES.match(value)
        if not m:

            # 12 - 15 Mar 2014 or 29 Feb - 1 Mar 2014
            m1 = REG_CONF_DATES_1.match(value)
            m2 = REG_CONF_DATES_2.match(value)

            if m1:
                record[u"111"]["d"] = "%s-%s %s %s" % m1.groups()

            elif m2:
                record[u"111"]["d"] = "%s %s - %s %s %s" % m2.groups()

            else:
                raise CheckException(MSG_WELL_FORMED_CONF_DATES)

    def format_authors(self, record, func):
        """Format the author names using the function func.

        @type record: L{Record}
        @param record:

        @type func: function reference
        @param func: function used to format the author names

        """
        for key in ("100", "700"):
            if key in record:
                if isinstance(record[key], list):
                    for i in range(len(record[key])):
                        record[key][i]["a"] = func(record[key][i]["a"])

                else:
                    record[key]["a"] = func(record[key]["a"])

    def format_editor(self, record):
        """Format the editor abbreviation since the encoding
        depends on the store:

            - INVENIO:    Phys. Lett. B + volume 673
            - INSPIREHEP: Phys.Lett + volume B673

        Standardise the answer as Phys Lett B

        @note: It is recommended to call this method when erratum are removed.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        if not record.is_published():
            return

        # standard case
        if isinstance(record["773"], dict):
            if "p" in record["773"] and "v" in record["773"]:

                editor = record["773"]["p"]
                volume = record["773"]["v"]

                # add space after the dot  Phys.Rev -> Phys. Rev
                editor = re.sub(r'\.([A-Z])', r'. \1', editor)

                # get the volume letter
                m = re.match(r'([A-Z]+) *(\d+)', volume)
                if m and m.group(1) != editor[-1]:
                    editor = "%s %s" % (editor, m.group(1))
                    volume = m.group(2)

                # remove stupid mistake
                editor = CLEAN_REVIEW(editor)

                record["773"]["p"] = editor
                record["773"]["v"] = volume

        # list case -- publication with erratum
        elif isinstance(record["773"], list):

            editors = record._get("773", 'p', force_list=True)
            volumes = record._get("773", 'v', force_list=True)

            if len(editors) != len(volumes):
                raise CheckException(MSG_WELL_FORMED_EDITOR)

            for i in range(len(editors)):
                # add space after the dot  Phys.Rev -> Phys. Rev
                editor = re.sub(r'\.([A-Z])', r'. \1', editors[i])

                # get the volume letter
                m = re.match(r'([A-Z]+) *(\d+)', volumes[i])
                if m and m.group(1) != editor[-1]:
                    editor = "%s %s" % (editor, m.group(1))
                    volume = m.group(2)

                editor = CLEAN_REVIEW(editor)

                record["773"][i]["p"] = editor
                record["773"][i]["v"] = volume

487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    def format_universities(self, record):
        """Format the name of the university for PhD:

            - Fix the name of Aix-Marseille University
            - Replace U. by University

        @type record: L{Record}
        @param record:

        """
        # protection
        if not record.is_thesis():
            return

        # CPPM: fix the name of Aix-Marseille university
        if current.app.inspirehep_institute_id == 902989:

            year = REG_YEAR.search(record.these_defense()).group(1)
            if int(year) < 2012:
                university = u"Université de la Méditerrannée Aix-Marseille II"
            else:
                university = u"Aix Marseille Université"

            if u'502' in record and "b" in record[u'502']:
                if isinstance(record[u'502']['b'], unicode):
                    if "Marseille" in record[u'502']['b']:
                        record[u'502']['b'] = university

                elif isinstance(record[u'502']['b'], list):
                    for i in xrange(len(record[u'502']['b'])):
                        if "Marseille" in record[u'502']['b'][i]:
                            record[u'502']['b'][i] = university

        # Other: replace U. by University
        else:
            university = current.T(UNIVERSITY).decode("utf8")

            if u'502' in record and "b" in record[u'502']:
                if isinstance(record[u'502']['b'], unicode):
                    value = record[u'502']['b']
                    if "U." in value:
                        value = value.replace('U.', university)
                        record[u'502']['b'] = value

                elif isinstance(record[u'502']['b'], list):
                    for i in xrange(len(record[u'502']['b'])):
                        value = record[u'502']['b'][i]
                        if "U." in value:
                            value = value.replace('U.', university)
                            record[u'502']['b'][i] = value

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    def my_authors(self, record, reference=[], cmpFct=None):
        """Check that authors of my institutes signed the record.
        Fill the meta data record.my_authors.

        @type record: L{Record}
        @param record:

        @type reference: list
        @param reference: list of author names belonging to my institute

        @type cmpFct: reference to a function
        @param cmpFct: Extract the family name from the full name.
        It is used to sort my author list according to the author family name.

        @raise CheckException:

        """
        # alias
556 557 558 559 560 561 562 563 564 565 566 567 568 569
        app = current.app
        reg_institute = app.reg_institute

        # regular expression for the institute is not defined
        # find it using the institute definition in inspirehep
        # store the regular expression in current.app for a later use
        if not reg_institute:
            institute_id = app.inspirehep_institute_id
            institute = load_record("inspirehep.net", institute_id)

            reg_institute = institute.rex()

            app.institute = institute
            app.reg_institute = reg_institute
570 571

        # find authors of my institute signing the record
572
        s = record.find_authors_by_institute(reg_institute, cmpFct)
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

        # nothing found try with the rescue list
        if not s and reference:

            s1 = set(record.authors_as_list())
            s2 = set(reference)

            li = list(s1.intersection(s2))
            li.sort(key=cmpFct)

            s = u', '.join(li)

        if s:
            record.my_authors = s
            return

589
        raise CheckException(MSG_NO_MY_AUTHOR)
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870

    def oai(self, record):
        """Check that the OAI field is defined and well formed.
        In some tricky case the OAI can evolve with time. Therefore, the record
        has several values. In that case, the method selects the one matching the
        OAI use in the database.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        # the location of the OAI information depends on the store
        # CDS: (248, a) or INSPIREHEP: (909CO, o)
        if "0248" in record:
            field, subfield = "0248", "a"

        elif "909CO" in record:
            field, subfield = "909CO", "o"

        else:
            raise CheckException(MSG_NO_OAI)

        myid = record.id()

        # Clean OAI information.
        # in some case OAI is a list,e.g when two records were entered
        # for the same entry but one deleted.
        # Select the OAI corresponding to the current ID.
        if isinstance(record[field], list):
            val = ''
            for di in record[field]:
                if di[subfield].endswith(myid):
                    val = di
                    break

            if val:
                record[field] = val
            else:
                raise CheckException(MSG_NO_OAI)

        # check that the OAI is well formed
        m = REG_OAI.match(record[field][subfield])
        if not m:
                raise CheckException(MSG_WELL_FORMED_OAI)

        # The id in the OAI field might be different from the record id.
        # In INVENIO there is a mechanism to redirect to the correct one
        #
        # The fix depend on the content of the database
        if m.group(2) != myid:
            db = current.globalenv['db']

            # The record OAI is already used in the database. Do nothing
            oai_url = OAI_URL % (m.group(1), m.group(2))
            if get_id(db.publications, origin=oai_url):
                return

            # The OAI based on the record id is already used in the database.
            # Modify the record OAI
            oai_url = OAI_URL % (m.group(1), myid)
            if get_id(db.publications, origin=oai_url):
                record[field][subfield] = OAI_INVENIO % (m.group(1), myid)

    def paper_reference(self, record):
        """Check that editor, page, volume and paper year are defined
        for a published paper. Repair it as far as possible.

        @note: it is recommended to call this method when the
        erratum are removed.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        if not record.is_published():
            return

        # list of reference (paper with erratum)
        refs = record["773"]
        if not isinstance(record["773"], list):
            refs = [refs]

        # INSPIREHEP
        # fix the following case:
        #    {'p': u'Phys.Lett.B'},
        #    {'y': u'2013', 'p': u'Phys.Lett.B', 'c': u'6-12', 'v': u'B720'}

        if len(refs) == 2 and record.host().startswith('inspirehep'):
            nkeys = [len(di) for di in refs]
            if nkeys.count(1):
                index = nkeys.index(1)
                if 'p' in refs[index]:
                    refs.pop(index)

        # do we have all fields defining a reference
        # editor, volume, year and page
        for ref in refs:

            # proceeding can only contains "w" and "y" keys
            if "w" in ref:
                continue

            # check full reference
            for k in ("p", "v", "y", "c"):
                if k not in ref:
                    self._repair_paper_reference(record)
                    return

    def submitted(self, record):
        """Standardize the submitted date as YYYY-MM or YYYY-MM-DD.
        Look for alternative when it is not defined.

        @note: after this check the year submitted contains one entry.

        @type record: L{Record}
        @param record:

        @raise CheckException:

        """
        dates = record.submitted()

        # recover missing date using conference, preprint, thesis information
        if not dates:
            val = self._recover_submitted(record)
            if not val:
                raise CheckException(MSG_NO_DATE)
            dates.append(val)

        # check that date are well formed
        for i in range(len(dates)):

            # 22 Mar 2011
            m = DECODE_DD_MMM_YYYY.match(dates[i])
            if m:
                dates[i] = '%s-%s-%02i' % (m.group(3), MONTHS[m.group(2)], int(m.group(1)))
                continue

            # 22 03 2011
            m = DECODE_DD_MM_YYYY.match(dates[i])
            if m:
                dates[i] = '%s-%02i-%02i' % (m.group(3), int(m.group(2)), int(m.group(1)))
                continue

            # 2011
            m_year = DECODE_YYYY.match(dates[i])
            if m_year:
                dates[i] = self._recover_submitted(record)

            # check the minimum requirement is 2001-05
            if not REG_SUBMITTED.match(dates[i]):
                raise CheckException(MSG_WELL_FORMED_DATE)

        # protection against list of identical date
        if len(dates) > 1:
            dates = list(set(dates))

        # Only one date
        if len(dates) != 1:
            raise CheckException(MSG_TO_MANY_DATE)

        if "269" not in record or isinstance(record["269"], list):
            record[u"269"] = dict()

        record[u"269"]["c"] = dates[0]

    def temporary_record(self, record):
        """Some records are marked temporary.

        @type record: L{Record}
        @param record:

        @raise CheckException: when the record is marked temporary

        """
        # found on INSPIREHEP (see record 1317573)
        if "500" in record and "a" in record["500"]:
            if record["500"]["a"] == u"*Temporary record*":
                raise CheckException(MSG_TEMPORARY_RECORD)

    def year(self, record):
        """Standardize the the year as YYYY and look for alternative when
        it is not defined.

        @note: The method assumes that the erratum are removed.

        @note: It is recommended to call this method after
        the L{submitted} one, since the submitted field is used in
        the recovery procedure.

        @note: after this check the year field contains one entry.

        @type record: L{Record}
        @param record:

        @raise CheckException: when there is a list of year or when empty.

        """
        val = ''

        # protection against "publication date YYYY-MM-DD"
        li = record._get("260", 'c', force_list=True)
        li = [el for el in li if REG_YEAR.match(el)]

        if len(li) == 1:
            val = li[0]
        elif len(li) > 1:
            raise CheckException(MSG_TO_MANY_YEAR)

        # alternative: look to the year in the publication reference
        if not val:
            val = record.paper_year()

        # alternative: look to the submitted date
        if not val:
            val = record.submitted()

        # protection against remaining list
        if isinstance(val, list):
            if len(val) == 1:
                val = val[0]
            else:
                raise CheckException(MSG_TO_MANY_YEAR)

        # the value can have several format 1992, 1992-12-31, .... standardize
        if val:
            m = REG_YEAR.search(val)
            if m:
                if "260" in record and isinstance(record["260"], dict):
                    record["260"]["c"] = m.group(1)
                else:
                    record["260"] = {"c": m.group(1)}
                return

        raise CheckException(MSG_NO_YEAR)

    def __call__(self, record, func=lambda x: x, reference=[], cmpFct=None):
        """The following points are checked and fixed:

            - Validity of the record (oai, year, submitted date)
            - Conference information
            - Format author names
            - Consistency of author fields
            - Signed by authors of my institute
            - Consistency of the paper reference
            - Fixed editor abbreviation
            - Remove erratum

        @type func: function reference
        @param func: function to format the author names.

        @type reference: list
        @param reference: list of author names belonging to my institute

        @type cmpFct: reference to a function
        @param cmpFct: Extract the family name form the full author name.
        It is used to sort the authors of my institute according to their
        family name.

        @raise CheckException: when one check failed.

        """
        # NOTE: order matter
        self.temporary_record(record)
        self.authors(record)
        self.format_authors(record, func)
        self.my_authors(record, reference, cmpFct)

        self.oai(record)
        self.clean_erratum(record)

        self.conference(record)
        self.submitted(record)
        self.year(record)

        self.paper_reference(record)
        self.format_editor(record)