source: indico/indico/MaKaC/common/output.py @ d531f9

burotelhello-world-walkthroughipv6new-webexv0.97-seriesv0.98-seriesv0.98.2v0.98.3v0.98b1v0.98b2v0.99v1.0v1.1
Last change on this file since d531f9 was d531f9, checked in by Jeremy Herr <jeremy.herr@…>, 3 years ago

[IMP] Added more security, plugin options

Now the method _confToXMLMarc21() checks to make sure the RecordingManager? plugin is installed and active before creating the 506 tag stuff.

Also now subfields 2 and 5 are not hardcoded, they are set by RecordingManager? options.

  • Property mode set to 100644
File size: 77.8 KB
Line 
1# -*- coding: utf-8 -*-
2##
3##
4## This file is part of CDS Indico.
5## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN.
6##
7## CDS Indico is free software; you can redistribute it and/or
8## modify it under the terms of the GNU General Public License as
9## published by the Free Software Foundation; either version 2 of the
10## License, or (at your option) any later version.
11##
12## CDS Indico is distributed in the hope that it will be useful, but
13## WITHOUT ANY WARRANTY; without even the implied warranty of
14## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15## General Public License for more details.
16##
17## You should have received a copy of the GNU General Public License
18## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
19## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20
21from datetime import datetime
22from pytz import timezone
23from MaKaC.plugins.base import PluginsHolder
24
25from MaKaC.plugins.Collaboration.collaborationTools import CollaborationTools
26from MaKaC.user import Avatar
27from MaKaC.user import CERNGroup
28
29try:
30    import libxml2
31    import libxslt
32except ImportError:
33    pass
34import string,re
35import simplejson
36
37import MaKaC.conference as conference
38import MaKaC.schedule as schedule
39import MaKaC.webcast as webcast
40import MaKaC.webinterface.urlHandlers as urlHandlers
41import MaKaC.webinterface.displayMgr as displayMgr
42from MaKaC.common.general import DEVELOPMENT
43from MaKaC.webinterface.linking import RoomLinker
44from Configuration import Config
45from xmlGen import XMLGen
46import os, time
47from MaKaC.i18n import _
48from MaKaC.common.timezoneUtils import DisplayTZ, nowutc
49from MaKaC.common.utils import getHierarchicalId, resolveHierarchicalId
50from MaKaC.common.cache import MultiLevelCache, MultiLevelCacheEntry
51from MaKaC.rb_location import CrossLocationQueries, CrossLocationDB
52
53
54def fake(string1=""):
55    return ""
56
57# TODO This really needs to be fixed... no i18n and strange implementation using month names as keys
58def stringToDate( str ):
59    months = { "January":1, "February":2, "March":3, "April":4, "May":5, "June":6, "July":7, "August":8, "September":9, "October":10, "November":11, "December":12 }
60    [ day, month, year ] = str.split("-")
61    return datetime(int(year),months[month],int(day))
62
63class XSLTransformer:
64
65    def __init__(self, stylesheet):
66        # instanciate stylesheet object
67        styledoc = libxml2.parseFile(stylesheet)
68        self.__style = libxslt.parseStylesheetDoc(styledoc)
69
70    def process (self, xml):
71        try:
72            doc = libxml2.parseDoc(xml)
73        except:
74            return _("""_("error parsing xml"):\n <pre>%s</pre>""") % xml.replace("<","&lt;")
75        # compute the transformation
76        result = self.__style.applyStylesheet(doc, None)
77        output = self.__style.saveResultToString(result)
78        # free memory
79        self.__style.freeStylesheet()
80        doc.freeDoc()
81        result.freeDoc()
82        #libxslt.cleanupGlobals() # this line causes mod_python to segfault
83        libxml2.cleanupParser()
84        return output
85
86class outputGenerator:
87    """
88    this class generates the application standard XML (getBasicXML)
89    and also provides a method to format it using an XSLt stylesheet
90    (getFormattedOutput method)
91    """
92
93    def __init__(self, aw, XG = None, dataInt=None):
94        self.__aw = aw
95        if XG != None:
96            self._XMLGen = XG
97        else:
98            self._XMLGen = XMLGen()
99        self._config = Config.getInstance()
100        self.iconfNamespace = self._config.getIconfNamespace()
101        self.iconfXSD = self._config.getIconfXSD()
102        self.text = ""
103        self.dataInt = dataInt
104        self.time_XML = 0
105        self.time_HTML = 0
106
107        if dataInt:
108            self.cache = ProtectedXMLCache(dataInt)
109        else:
110            self.cache = XMLCache()
111
112        from MaKaC.webinterface.webFactoryRegistry import WebFactoryRegistry
113        self.webFactory = WebFactoryRegistry()
114
115    def _generateMaterialList(self, obj):
116        """
117        Generates a list containing all the materials, with the
118        corresponding Ids for those that already exist
119        """
120
121        # yes, this may look a bit redundant, but materialRegistry isn't
122        # bound to a particular target
123        materialRegistry = obj.getMaterialRegistry()
124        return materialRegistry.getMaterialList(obj.getConference())
125
126
127    def getOutput(self, conf, stylesheet, vars=None, includeSession=1,includeContribution=1,includeMaterial=1,showSession="all",showDate="all",showContribution="all"):
128        # get xml conference
129        start_time_XML = time.time()
130        xml = self._getBasicXML(conf, vars, includeSession,includeContribution,includeMaterial,showSession,showDate,showContribution)
131        end_time_XML = start_time_HTML = time.time()
132        if not os.path.exists(stylesheet):
133            self.text = _("Cannot find stylesheet")
134        if os.path.basename(stylesheet) == "xml.xsl":
135            self.text = xml
136        else:
137            # instanciate the XSL tool
138            try:
139                parser = XSLTransformer(stylesheet)
140                self.text = parser.process(xml)
141            except Exception, e:
142                self.text = _("Cannot parse stylesheet: %s") % str(e)
143        end_time_HTML = time.time()
144        self.time_XML = end_time_XML - start_time_XML
145        self.time_HTML = end_time_HTML - start_time_HTML
146        return self.text
147
148
149    def getFormattedOutput(self, conf, stylesheet, vars=None, includeSession=1,includeContribution=1,includeMaterial=1,showSession="all",showDate="all",showContribution="all"):
150        """
151        conf: conference object
152        stylesheet: path to the xsl file
153        """
154        self.getOutput(conf, stylesheet, vars, includeSession,includeContribution,includeMaterial,showSession,showDate,showContribution)
155        html = self.text
156        if DEVELOPMENT:
157            stat_text = _("""<br><br><font size="-2">_("XML creation"): %s<br>_("HTML creation"): %s</font>""") % (self.time_XML,self.time_HTML)
158        else:
159            stat_text = ""
160        if (re.search("xml.xsl$",stylesheet) or re.search("text.xsl$",stylesheet) or re.search("jacow.xsl$",stylesheet)) and vars.get("frame","") != "no":
161            return "<pre>%s</pre>" % html.replace("<","&lt;") + stat_text
162        else:
163            return html + stat_text
164
165    def _getBasicXML(self, conf, vars,includeSession,includeContribution,includeMaterial,showSession="all",showDate="all",showContribution="all", out=None):
166        if not out:
167            out = self._XMLGen
168        """
169        conf: conference object
170        """
171        #out.initXml()
172        out.openTag("iconf")
173        self._confToXML(conf,vars,includeSession,includeContribution,includeMaterial,showSession,showDate, showContribution,out=out)
174        out.closeTag("iconf")
175        return out.getXml()
176
177    def _userToXML(self, user, out):
178        out.openTag("user")
179        out.writeTag("title",user.getTitle())
180        out.writeTag("name","",[["first",user.getFirstName()],["middle",""],["last",user.getFamilyName()]])
181        out.writeTag("organization",user.getAffiliation())
182        out.writeTag("email",user.getEmail())
183        try:
184            out.writeTag("userid",user.id)
185        except:
186            pass
187        out.closeTag("user")
188
189    def _getRoom(self, room, location):
190        # get the name that is saved
191        roomName = room.getName()
192
193        # if there is a connection to the room booking DB
194        if CrossLocationDB.isConnected() and location:
195            # get the room info
196            roomFromDB = CrossLocationQueries.getRooms( roomName = roomName, location = location.getName() )
197            #roomFromDB can be a list or an object room
198            if isinstance(roomFromDB,list) and roomFromDB != []:
199                roomFromDB = roomFromDB[0]
200            # If there's a room with such name.
201            # Sometimes CrossLocationQueries.getRooms returns a list with None elements
202            if roomFromDB:
203                # use the full name instead
204                roomName = roomFromDB.getFullName()
205        return roomName
206
207
208    def _confToXML(self, conf, vars, includeSession=1, includeContribution=1, includeMaterial=1, showSession="all", showDate="all",showContribution="all", showWithdrawed=True, useSchedule=True, out=None):
209        if not out:
210            out = self._XMLGen
211
212        if vars and vars.has_key("frame") and vars["frame"] == "no":
213            modificons = 0
214        else:
215            modificons = 1
216
217        out.writeTag("ID",conf.getId())
218
219        if conf.getOwnerList():
220            out.writeTag("category",conf.getOwnerList()[0].getName())
221        else:
222            out.writeTag("category","")
223
224        out.writeTag("parentProtection", simplejson.dumps(conf.getAccessController().isProtected()))
225        out.writeTag("materialList", simplejson.dumps(self._generateMaterialList(conf)))
226
227        if conf.canModify( self.__aw ) and vars and modificons:
228            out.writeTag("modifyLink",vars["modifyURL"])
229        if conf.canModify( self.__aw ) and vars and modificons:
230            out.writeTag("minutesLink",True)
231        if conf.canModify( self.__aw ) and vars and modificons:
232            out.writeTag("materialLink", True)
233        if conf.canModify( self.__aw ) and vars and vars.has_key("cloneURL") and modificons:
234            out.writeTag("cloneLink",vars["cloneURL"])
235        if  vars and vars.has_key("iCalURL"):
236            out.writeTag("iCalLink",vars["iCalURL"])
237        if  vars and vars.has_key("webcastAdminURL"):
238            out.writeTag("webcastAdminLink",vars["webcastAdminURL"])
239
240        if conf.getOrgText() != "":
241            out.writeTag("organiser", conf.getOrgText())
242
243        out.openTag("announcer")
244        chair = conf.getCreator()
245        if chair != None:
246            self._userToXML(chair, out)
247        out.closeTag("announcer")
248
249        if conf.getSupportEmail() != '':
250            out.writeTag("supportEmail", conf.getSupportEmail(), [["caption", displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(conf).getSupportEmailCaption()]])
251
252        rnh = conf.getReportNumberHolder()
253        rns = rnh.listReportNumbers()
254        if len(rns) != 0:
255            for rn in rns:
256                out.openTag("repno")
257                out.writeTag("system",rn[0])
258                out.writeTag("rn",rn[1])
259                out.closeTag("repno")
260
261        out.writeTag("title",conf.getTitle())
262
263        out.writeTag("description",conf.getDescription())
264
265        if conf.getParticipation().displayParticipantList() :
266            out.writeTag("participants",conf.getParticipation().getPresentParticipantListText())
267        if (conf.getType() == "meeting" or conf.getType() == "simple_event") and conf.getParticipation().isAllowedForApplying() and conf.getStartDate() > nowutc():
268            out.writeTag("apply",urlHandlers.UHConfParticipantsNewPending.getURL(conf))
269
270        evaluation = conf.getEvaluation()
271        if evaluation.isVisible() and evaluation.inEvaluationPeriod() and evaluation.getNbOfQuestions()>0 :
272            out.writeTag("evaluationLink",urlHandlers.UHConfEvaluationDisplay.getURL(conf))
273
274#        if len(conf.getBookingsList()):
275#            out.openTag("videoconference")
276#            for b in conf.getBookingsList():
277#                out.openTag(b.getSystem())
278#                if b.getSystem() == "VRVS":
279#                    out.writeTag("description",b.getPublicDescription())
280#                out.closeTag(b.getSystem())
281#            out.closeTag("videoconference")
282
283        if conf.getLocationList()!=[] or conf.getRoom():
284            out.openTag("location")
285            loc=None
286            for l in conf.getLocationList():
287                if l.getName() != "":
288                    loc=l
289                out.writeTag("name",l.getName())
290                out.writeTag("address",l.getAddress())
291            if conf.getRoom():
292                roomName = self._getRoom(conf.getRoom(), loc)
293                out.writeTag("room", roomName)
294                url=RoomLinker().getURL(conf.getRoom(), loc)
295                if url != "":
296                    out.writeTag("roomMapURL",url)
297            else:
298                out.writeTag("room","")
299            out.closeTag("location")
300
301        tzUtil = DisplayTZ(self.__aw,conf)
302        tz = tzUtil.getDisplayTZ()
303        adjusted_startDate = conf.getAdjustedStartDate(tz)
304        adjusted_endDate = conf.getAdjustedEndDate(tz)
305        out.writeTag("startDate","%d-%s-%sT%s:%s:00" %(adjusted_startDate.year, string.zfill(adjusted_startDate.month,2), string.zfill(adjusted_startDate.day,2), string.zfill(adjusted_startDate.hour,2), string.zfill(adjusted_startDate.minute,2)))
306        out.writeTag("endDate","%d-%s-%sT%s:%s:00" %(adjusted_endDate.year, string.zfill(adjusted_endDate.month,2), string.zfill(adjusted_endDate.day,2), string.zfill(adjusted_endDate.hour,2), string.zfill(adjusted_endDate.minute,2)))
307        out.writeTag("creationDate",conf.getCreationDate().astimezone(timezone(tz)).strftime("%Y-%m-%dT%H:%M:%S"))
308        out.writeTag("modificationDate",conf.getModificationDate().strftime("%Y-%m-%dT%H:%M:%S"))
309        out.writeTag("timezone","%s" %(tz))
310
311        uList = conf.getChairList()
312        if len(uList) > 0 or conf.getChairmanText() != "":
313            out.openTag("chair")
314            for chair in uList:
315                self._userToXML(chair, out)
316            if conf.getChairmanText() != "":
317                out.writeTag("UnformatedUser",conf.getChairmanText())
318            out.closeTag("chair")
319
320        if showContribution != "all" and conf.getContributionById(showContribution) != None:
321            self._contribToXML(conf.getContributionById(showContribution),vars,includeMaterial,conf, out=out)
322        elif useSchedule:
323            confSchedule = conf.getSchedule()
324            if showDate == "all":
325                entrylist = confSchedule.getEntries()
326            else:
327                entrylist = confSchedule.getEntriesOnDay(timezone(tz).localize(stringToDate(showDate)))
328            for entry in entrylist:
329                if type(entry) is schedule.BreakTimeSchEntry: #TODO: schedule.BreakTimeSchEntry doesn't seem to exist!
330                    self._breakToXML(entry, out=out)
331                elif type(entry) is conference.ContribSchEntry:
332                    owner = entry.getOwner()
333                    if owner.canView(self.__aw):
334                        if includeContribution:
335                            if showWithdrawed or not isinstance(owner.getCurrentStatus(), conference.ContribStatusWithdrawn):
336                                self._contribToXML(owner,vars,includeMaterial,conf, out=out)
337                elif type(entry) is schedule.LinkedTimeSchEntry: #TODO: schedule.LinkedTimeSchEntry doesn't seem to exist!
338                    owner = entry.getOwner()
339                    if type(owner) is conference.Contribution:
340                        if owner.canView(self.__aw):
341                            if includeContribution:
342                                if showWithdrawed or not isinstance(owner.getCurrentStatus(), conference.ContribStatusWithdrawn):
343                                    self._contribToXML(owner,vars,includeMaterial,conf, out=out)
344                    elif type(owner) is conference.Session:
345                        if owner.canView(self.__aw):
346                            if includeSession and (showSession == "all" or owner.getId() == showSession):
347                                self._sessionToXML(owner,vars,includeContribution,includeMaterial, showWithdrawed=showWithdrawed, out=out)
348                    elif type(owner) is conference.SessionSlot:
349                        if owner.getSession().canView(self.__aw):
350                            if includeSession and (showSession == "all" or owner.getSession().getId() == showSession):
351                                self._slotToXML(owner,vars,includeContribution,includeMaterial, showWithdrawed=showWithdrawed, out=out)
352        else:
353            confSchedule = conf.getSchedule()
354            for entry in confSchedule.getEntries():
355                if type(entry) is conference.ContribSchEntry:
356                    owner = entry.getOwner()
357                    if owner.canView(self.__aw):
358                        if includeContribution:
359                            self._contribToXML(owner,vars,includeMaterial,conf,out=out)
360            sessionList = conf.getSessionList()
361            for session in sessionList:
362                if session.canAccess(self.__aw) and includeSession:
363                    self._sessionToXML(session, vars, includeContribution, includeMaterial, showWithdrawed=showWithdrawed, useSchedule=False, out=out)
364
365        mList = conf.getAllMaterialList()
366        for mat in mList:
367            if mat.canView(self.__aw) and mat.getTitle() != "Internal Page Files":
368                if includeMaterial:
369                    self._materialToXML(mat, vars, out=out)
370
371        wm = webcast.HelperWebcastManager.getWebcastManagerInstance()
372        url = wm.isOnAir(conf)
373        if url:
374            out.openTag("material")
375            out.writeTag("ID","live webcast")
376            out.writeTag("title","live webcast")
377            out.writeTag("description","")
378            out.writeTag("type","")
379            out.writeTag("displayURL",url)
380            out.closeTag("material")
381        elif wm.getForthcomingWebcast(conf):
382            out.openTag("material")
383            out.writeTag("ID","forthcoming webcast")
384            out.writeTag("title","forthcoming webcast")
385            out.writeTag("description","")
386            out.writeTag("type","")
387            out.writeTag("displayURL", wm.getWebcastServiceURL())
388            out.closeTag("material")
389
390        #plugins XML
391        out.openTag("plugins")
392        if PluginsHolder().hasPluginType("Collaboration"):
393            from MaKaC.plugins.Collaboration.output import OutputGenerator
394            OutputGenerator.collaborationToXML(out, conf, tz)
395        out.closeTag("plugins")
396
397
398
399    def _sessionToXML(self,session,vars,includeContribution,includeMaterial, showWithdrawed=True, useSchedule=True, out=None):
400        if not out:
401            out = self._XMLGen
402        if vars and vars.has_key("frame") and vars["frame"] == "no":
403            modificons = 0
404        else:
405            modificons = 1
406        out.openTag("session")
407        out.writeTag("ID",session.getId())
408
409        if session.getCode() not in ["no code", ""]:
410            out.writeTag("code",session.getCode())
411        else:
412            out.writeTag("code",session.getId())
413        if (session.canModify( self.__aw ) or session.canCoordinate(self.__aw)) and vars and modificons:
414            out.writeTag("modifyLink",vars["sessionModifyURLGen"](session))
415        if (session.canModify( self.__aw ) or session.canCoordinate(self.__aw)) and vars and modificons:
416            out.writeTag("minutesLink",True)
417            out.writeTag("materialLink", True)
418        out.writeTag("title",session.title)
419        out.writeTag("description",session.description)
420        cList = session.getConvenerList()
421        if len(cList) != 0:
422            out.openTag("convener")
423            for conv in cList:
424                self._userToXML(conv, out)
425            if session.getConvenerText() != "":
426                out.writeTag("UnformatedUser",session.getConvenerText())
427            out.closeTag("convener")
428        l = session.getLocation()
429        if l!=None or session.getRoom():
430            out.openTag("location")
431            if l!=None:
432                out.writeTag("name",l.getName())
433                out.writeTag("address",l.getAddress())
434            if session.getRoom():
435                roomName = self._getRoom(session.getRoom(), l)
436                out.writeTag("room", roomName)
437                url=RoomLinker().getURL(session.getRoom(), l)
438                if url != "":
439                    out.writeTag("roomMapURL",url)
440            else:
441                out.writeTag("room","")
442            out.closeTag("location")
443        try:
444            displayMode = self.__aw._currentUser.getDisplayTZMode()
445        except:
446            # not logged in, use meeting timezone
447            displayMode = 'Meeting'
448        if displayMode == 'Meeting':
449            tz = self.conf.getTimezone()
450        else:
451            tz = self.__aw._currentUser.getTimezone()
452        startDate = session.getStartDate().astimezone(timezone(tz))
453        out.writeTag("startDate","%d-%s-%sT%s:%s:00" %(startDate.year, string.zfill(startDate.month,2), string.zfill(startDate.day,2),string.zfill(startDate.hour,2), string.zfill(startDate.minute,2)))
454        endDate = session.startDate + session.duration
455        out.writeTag("endDate","%d-%s-%sT%s:%s:00" %(endDate.year, string.zfill(endDate.month,2), string.zfill(endDate.day,2),string.zfill(endDate.hour,2), string.zfill(endDate.minute,2)))
456        out.writeTag("duration","%s:%s" %(string.zfill((datetime(1900,1,1)+session.duration).hour,2), string.zfill((datetime(1900,1,1)+session.duration).minute,2)))
457        if includeContribution:
458            if useSchedule:
459                sessionSchedule = session.getSchedule()
460                for entry in sessionSchedule.getEntries():
461                    if type(entry) is schedule.BreakTimeSchEntry: #TODO: schedule.BreakTimeSchEntry doesn't seem to exist!
462                        self._breakToXML(entry, out=out)
463                    elif type(entry) is schedule.LinkedTimeSchEntry: #TODO: schedule.LinkedTimeSchEntry doesn't seem to exist!
464                        owner = entry.getOwner()
465                        if type(owner) is conference.Contribution:
466                            if owner.canView(self.__aw):
467                                if showWithdrawed or not isinstance(owner.getCurrentStatus(), conference.ContribStatusWithdrawn):
468                                    self._contribToXML(owner,vars,includeMaterial, conf,out=out)
469            else:
470                for contrib in session.getContributionList():
471                    if contrib.canView(self.__aw):
472                        if showWithdrawed or not isinstance(contrib.getCurrentStatus(), conference.ContribStatusWithdrawn):
473                            self._contribToXML(contrib, vars, includeMaterial, conf,out=out)
474
475        mList = session.getAllMaterialList()
476        for mat in mList:
477            self._materialToXML(mat, vars, out=out)
478        out.closeTag("session")
479
480
481
482    def _slotToXML(self,slot,vars,includeContribution,includeMaterial, showWithdrawed=True, out=None):
483        if not out:
484            out = self._XMLGen
485        session = slot.getSession()
486        conf = session.getConference()
487        if vars and vars.has_key("frame") and vars["frame"] == "no":
488            modificons = 0
489        else:
490            modificons = 1
491        out.openTag("session")
492        out.writeTag("ID",session.getId())
493
494        out.writeTag("parentProtection", simplejson.dumps(session.getAccessController().isProtected()))
495        out.writeTag("materialList", simplejson.dumps(self._generateMaterialList(session)))
496
497
498        slotCode = session.getSortedSlotList().index(slot) + 1
499        if session.getCode() not in ["no code", ""]:
500            out.writeTag("code","%s-%s" % (session.getCode(),slotCode))
501        else:
502            out.writeTag("code","sess%s-%s" % (session.getId(),slotCode))
503        if (session.canModify( self.__aw ) or session.canCoordinate(self.__aw)) and vars and modificons:
504            out.writeTag("modifyLink",vars["sessionModifyURLGen"](session))
505        if (session.canModify( self.__aw ) or session.canCoordinate(self.__aw)) and vars and modificons:
506            out.writeTag("minutesLink",True)
507            out.writeTag("materialLink", True)
508        title = session.title
509        if slot.getTitle() != "" and slot.getTitle() != title:
510            title += ": %s" %  slot.getTitle()
511        out.writeTag("title",title)
512        out.writeTag("description",session.description)
513        cList = slot.getConvenerList()
514        if len(cList) != 0:
515            out.openTag("convener")
516            for conv in cList:
517                self._userToXML(conv, out)
518            if session.getConvenerText() != "":
519                out.writeTag("UnformatedUser",session.getConvenerText())
520            out.closeTag("convener")
521        l = slot.getLocation()
522        room = slot.getRoom()
523        if not conf.getEnableSessionSlots():
524            l = session.getLocation()
525            room = session.getRoom()
526        if l!=None or room:
527            out.openTag("location")
528            if l!=None:
529                out.writeTag("name",l.getName())
530                out.writeTag("address",l.getAddress())
531            if room:
532                roomName = self._getRoom(room, l)
533                out.writeTag("room", roomName)
534                url=RoomLinker().getURL(room, l)
535                if url != "":
536                    out.writeTag("roomMapURL",url)
537            else:
538                out.writeTag("room","")
539            out.closeTag("location")
540        tzUtil = DisplayTZ(self.__aw,conf)
541        tz = tzUtil.getDisplayTZ()
542        startDate = slot.getStartDate().astimezone(timezone(tz))
543        endDate = slot.getEndDate().astimezone(timezone(tz))
544        out.writeTag("startDate","%d-%s-%sT%s:%s:00" %(startDate.year, string.zfill(startDate.month,2), string.zfill(startDate.day,2),string.zfill(startDate.hour,2), string.zfill(startDate.minute,2)))
545        out.writeTag("endDate","%d-%s-%sT%s:%s:00" %(endDate.year, string.zfill(endDate.month,2), string.zfill(endDate.day,2),string.zfill(endDate.hour,2), string.zfill(endDate.minute,2)))
546        out.writeTag("duration","%s:%s" %(string.zfill((datetime(1900,1,1)+slot.duration).hour,2), string.zfill((datetime(1900,1,1)+slot.duration).minute,2)))
547        if includeContribution:
548            for entry in slot.getSchedule().getEntries():
549                if type(entry) is schedule.BreakTimeSchEntry: #TODO: schedule.BreakTimeSchEntry doesn't seem to exist!
550                    self._breakToXML(entry, out=out)
551                else:
552                    owner = entry.getOwner()
553                    if isinstance(owner, conference.AcceptedContribution) or isinstance(owner, conference.Contribution):
554                        if owner.canView(self.__aw):
555                            if showWithdrawed or not isinstance(owner.getCurrentStatus(), conference.ContribStatusWithdrawn):
556                                self._contribToXML(owner,vars,includeMaterial, conf,out=out)
557        mList = session.getAllMaterialList()
558        for mat in mList:
559            self._materialToXML(mat, vars, out=out)
560        out.closeTag("session")
561
562
563
564    def _contribToXML(self,cont,vars,includeMaterial, conf, out=None):
565        if not out:
566            out = self._XMLGen
567        if vars and vars.has_key("frame") and vars["frame"] == "no":
568            modificons = 0
569        else:
570            modificons = 1
571        out.openTag("contribution")
572        out.writeTag("ID",cont.getId())
573
574        out.writeTag("parentProtection", simplejson.dumps(cont.getAccessController().isProtected()))
575        out.writeTag("materialList", simplejson.dumps(self._generateMaterialList(cont)))
576
577        if cont.getBoardNumber() != "":
578            out.writeTag("board",cont.getBoardNumber())
579        if cont.getTrack() != None:
580            out.writeTag("track",cont.getTrack().getTitle())
581        if cont.getType() != None:
582            out.openTag("type")
583            out.writeTag("id",cont.getType().getId())
584            out.writeTag("name",cont.getType().getName())
585            out.closeTag("type")
586        if cont.canModify( self.__aw ) and vars and modificons:
587            out.writeTag("modifyLink",vars["contribModifyURLGen"](cont))
588        if (cont.canModify( self.__aw ) or cont.canUserSubmit(self.__aw.getUser())) and vars and modificons:
589            out.writeTag("minutesLink", True)
590        if (cont.canModify( self.__aw ) or cont.canUserSubmit(self.__aw.getUser())) and vars and modificons:
591            out.writeTag("materialLink", True)
592        keywords = cont.getKeywords()
593        keywords.replace("\r\n", "\n")
594        for keyword in keywords.split("\n"):
595            out.writeTag("keyword",keyword.strip())
596        rnh = cont.getReportNumberHolder()
597        rns = rnh.listReportNumbers()
598        if len(rns) != 0:
599            for rn in rns:
600                out.openTag("repno")
601                out.writeTag("system",rn[0])
602                out.writeTag("rn",rn[1])
603                out.closeTag("repno")
604        out.writeTag("title",cont.title)
605        sList = cont.getSpeakerList()
606        if len(sList) != 0:
607            out.openTag("speakers")
608            for sp in sList:
609                self._userToXML(sp, out)
610            if cont.getSpeakerText() != "":
611                out.writeTag("UnformatedUser",cont.getSpeakerText())
612            out.closeTag("speakers")
613        primaryAuthorList = cont.getPrimaryAuthorList()
614        if len(primaryAuthorList) != 0:
615            out.openTag("primaryAuthors")
616            for sp in primaryAuthorList:
617                self._userToXML(sp, out)
618            out.closeTag("primaryAuthors")
619        coAuthorList = cont.getCoAuthorList()
620        if len(coAuthorList) != 0:
621            out.openTag("coAuthors")
622            for sp in coAuthorList:
623                self._userToXML(sp, out)
624            out.closeTag("coAuthors")
625        l = cont.getLocation()
626        if l != None or cont.getRoom():
627            out.openTag("location")
628            if l!=None:
629                out.writeTag("name",l.getName())
630                out.writeTag("address",l.getAddress())
631            if cont.getRoom():
632                roomName = self._getRoom(cont.getRoom(), l)
633                out.writeTag("room", roomName)
634                url=RoomLinker().getURL(cont.getRoom(), l)
635                if url != "":
636                    out.writeTag("roomMapURL",url)
637            else:
638                out.writeTag("room","")
639            out.closeTag("location")
640        tzUtil = DisplayTZ(self.__aw,conf)
641        tz = tzUtil.getDisplayTZ()
642
643        startDate = None
644        if cont.startDate:
645            startDate = cont.startDate.astimezone(timezone(tz))
646
647        if startDate:
648            endDate = startDate + cont.duration
649            out.writeTag("startDate","%d-%s-%sT%s:%s:00" %(startDate.year, string.zfill(startDate.month,2), string.zfill(startDate.day,2),string.zfill(startDate.hour,2), string.zfill(startDate.minute,2)))
650            out.writeTag("endDate","%d-%s-%sT%s:%s:00" %(endDate.year, string.zfill(endDate.month,2), string.zfill(endDate.day,2),string.zfill(endDate.hour,2), string.zfill(endDate.minute,2)))
651        if cont.duration:
652            out.writeTag("duration","%s:%s" %(string.zfill((datetime(1900,1,1)+cont.duration).hour,2), string.zfill((datetime(1900,1,1)+cont.duration).minute,2)))
653        out.writeTag("abstract",cont.getDescription())
654        matList = cont.getAllMaterialList()
655        for mat in matList:
656            if mat.canView(self.__aw):
657                if includeMaterial:
658                    self._materialToXML(mat, vars, out=out)
659                else:
660                    out.writeTag("material",out.writeTag("id",mat.id))
661        for subC in cont.getSubContributionList():
662            self._subContributionToXML(subC,vars,includeMaterial, out=out)
663        out.closeTag("contribution")
664
665
666    def _subContributionToXML(self, subCont, vars, includeMaterial, out=None):
667        if not out:
668            out = self._XMLGen
669        if vars and vars.has_key("frame") and vars["frame"] == "no":
670            modificons = 0
671        else:
672            modificons = 1
673        out.openTag("subcontribution")
674        out.writeTag("ID",subCont.getId())
675
676        out.writeTag("parentProtection", simplejson.dumps(subCont.getContribution().getAccessController().isProtected()))
677        out.writeTag("materialList", simplejson.dumps(self._generateMaterialList(subCont)))
678
679        if subCont.canModify( self.__aw ) and vars and modificons:
680            out.writeTag("modifyLink",vars["subContribModifyURLGen"](subCont))
681        if (subCont.canModify( self.__aw ) or subCont.canUserSubmit( self.__aw.getUser())) and vars and modificons:
682            out.writeTag("minutesLink",True)
683        if (subCont.canModify( self.__aw ) or subCont.canUserSubmit( self.__aw.getUser())) and vars and modificons:
684            out.writeTag("materialLink", True)
685        rnh = subCont.getReportNumberHolder()
686        rns = rnh.listReportNumbers()
687        if len(rns) != 0:
688            for rn in rns:
689                out.openTag("repno")
690                out.writeTag("system",rn[0])
691                out.writeTag("rn",rn[1])
692                out.closeTag("repno")
693        out.writeTag("title",subCont.title)
694        sList = subCont.getSpeakerList()
695        if len(sList) > 0 or subCont.getSpeakerText() != "":
696            out.openTag("speakers")
697        for sp in sList:
698            self._userToXML(sp, out)
699        if subCont.getSpeakerText() != "":
700            out.writeTag("UnformatedUser",subCont.getSpeakerText())
701        if len(sList) > 0 or subCont.getSpeakerText() != "":
702            out.closeTag("speakers")
703        out.writeTag("duration","%s:%s"%((string.zfill((datetime(1900,1,1)+subCont.getDuration()).hour,2), string.zfill((datetime(1900,1,1)+subCont.getDuration()).minute,2))))
704        out.writeTag("abstract",subCont.getDescription())
705        matList = subCont.getAllMaterialList()
706        for mat in matList:
707            if mat.canView(self.__aw):
708                if includeMaterial:
709                    self._materialToXML(mat, vars, out=out)
710        out.closeTag("subcontribution")
711
712
713    def _materialToXML(self,mat, vars, out=None):
714        if not out:
715            out = self._XMLGen
716        out.openTag("material")
717        out.writeTag("ID",mat.getId())
718        out.writeTag("title",mat.title)
719        out.writeTag("description",mat.description)
720        out.writeTag("type",mat.type)
721        if vars:
722            out.writeTag("displayURL",vars["materialURLGen"](mat))
723        from MaKaC.conference import Minutes
724        if isinstance(mat, Minutes):
725            out.writeTag("minutesText",mat.getText())
726        pdfs = []
727        docs = []
728        ppts = []
729        odps = []
730        odts = []
731        odss = []
732        others = []
733        links = []
734        if len(mat.getResourceList()) > 0:
735            out.openTag("files")
736            for res in mat.getResourceList():
737                try:
738                    type = res.getFileType().lower()
739                    if type=="pdf":
740                        pdfs.append(res)
741                    elif type=="doc" or type == "docx":
742                        docs.append(res)
743                    elif type=="ppt" or type == "pptx":
744                        ppts.append(res)
745                    elif type=="sxi" or type=="odp":
746                        odps.append(res)
747                    elif type=="sxw" or type=="odt":
748                        odts.append(res)
749                    elif type=="sxc" or type=="ods":
750                        odss.append(res)
751                    else:
752                        others.append(res)
753                    if vars:
754                        out.openTag("file")
755                        out.writeTag("name",res.getFileName())
756                        out.writeTag("type",res.getFileType().lower())
757                        out.writeTag("url",vars["resourceURLGen"](res))
758                        out.closeTag("file")
759                except:
760                    links.append(res)
761            out.closeTag("files")
762            if not len(pdfs) > 1 and not len(docs) > 1 and not len(ppts) > 1 and not len(odps) > 1 and not len(odts) > 1 and not len(odss) > 1 and len(others) == 0 and not len(links) > 1:
763                if vars:
764                    if len(pdfs)==1:
765                        out.writeTag("pdf",vars["resourceURLGen"](pdfs[0]))
766                    if len(docs)==1:
767                        out.writeTag("doc",vars["resourceURLGen"](docs[0]))
768                    if len(ppts)==1:
769                        out.writeTag("ppt",vars["resourceURLGen"](ppts[0]))
770                    if len(odps)==1:
771                        out.writeTag("odp",vars["resourceURLGen"](odps[0]))
772                    if len(odts)==1:
773                        out.writeTag("odt",vars["resourceURLGen"](odts[0]))
774                    if len(odss)==1:
775                        out.writeTag("ods",vars["resourceURLGen"](odss[0]))
776                if len(links)==1:
777                    out.writeTag("link",str(links[0].getURL()))
778        if mat.isItselfProtected():
779            out.writeTag("locked","yes")
780        out.closeTag("material")
781
782    def _resourcesToXML(self, rList, out=None):
783        if not out:
784            out = self._XMLGen
785        out.openTag("resources")
786        for res in rList:
787            if res.canView(self.__aw):
788                self._resourceToXML(res, out=out)
789        out.closeTag("resources")
790
791    def _resourceToXML(self,res, out=None):
792        if not out:
793            out = self._XMLGen
794        if type(res) == conference.LocalFile:
795            self._resourceFileToXML(res, out=out)
796        else:
797            self._resourceLinkToXML(res, out=out)
798
799    def _resourceLinkToXML(self,res, out=None):
800        if not out:
801            out = self._XMLGen
802        out.openTag("resourceLink")
803        out.writeTag("name",res.getName())
804        out.writeTag("description",res.getDescription())
805        out.writeTag("url",res.getURL())
806        out.closeTag("resourceLink")
807
808    def _resourceFileToXML(self,res, out=None):
809        if not out:
810            out = self._XMLGen
811        out.openTag("resourceFile")
812        out.writeTag("name",res.getName())
813        out.writeTag("description",res.getDescription())
814        out.writeTag("type",res.fileType)
815        out.writeTag("url",res.getURL())
816        out.writeTag("fileName",res.getFileName())
817        out.writeTag("duration","1")#TODO:DURATION ISN'T ESTABLISHED
818        cDate = res.getCreationDate()
819        creationDateStr = "%d-%s-%sT%s:%s:00Z" %(cDate.year, string.zfill(cDate.month,2), string.zfill(cDate.day,2), string.zfill(cDate.hour,2), string.zfill(cDate.minute,2))
820        out.writeTag("creationDate",creationDateStr)
821        out.closeTag("resourceFile")
822
823    def _breakToXML(self,br, out=None):
824        if not out:
825            out = self._XMLGen
826        out.openTag("break")
827        out.writeTag("name",br.getTitle())
828        tzUtil = DisplayTZ(self.__aw,br.getOwner())
829        tz = tzUtil.getDisplayTZ()
830        startDate = br.getStartDate().astimezone(timezone(tz))
831        endDate = br.getEndDate().astimezone(timezone(tz))
832        out.writeTag("startDate","%d-%s-%sT%s:%s" %(startDate.year, string.zfill(startDate.month,2), string.zfill(startDate.day,2),string.zfill(startDate.hour,2), string.zfill(startDate.minute,2)))
833        out.writeTag("endDate","%d-%s-%sT%s:%s" %(endDate.year, string.zfill(endDate.month,2), string.zfill(endDate.day,2),string.zfill(endDate.hour,2), string.zfill(endDate.minute,2)))
834        out.writeTag("duration","%s:%s"%((string.zfill((datetime(1900,1,1)+br.getDuration()).hour,2), string.zfill((datetime(1900,1,1)+br.getDuration()).minute,2))))
835        if br.getDescription() != "":
836            out.writeTag("description", br.getDescription())
837        l = br.getLocation()
838        if l != None or br.getRoom():
839            out.openTag("location")
840            if l!=None:
841                out.writeTag("name",l.getName())
842                out.writeTag("address",l.getAddress())
843            if br.getRoom():
844                roomName = self._getRoom(br.getRoom(), l)
845                out.writeTag("room", roomName)
846                url=RoomLinker().getURL(br.getRoom(), l)
847                if url != "":
848                    out.writeTag("roomMapURL",url)
849            else:
850                out.writeTag("room","")
851            out.closeTag("location")
852        out.closeTag("break")
853
854
855    def confToXML(self,conf,includeSession,includeContribution,includeMaterial,showSession="all", showContribution="all", out=None, forceCache=False):
856        if not out:
857            out = self._XMLGen
858        #try to get a cache
859        version = "ses-%s_cont-%s_mat-%s_sch-%s"%(includeSession,includeContribution,includeMaterial,False)
860        obj = None
861        if not forceCache:
862            obj = self.cache.loadObject(version, conf)
863        if obj:
864            xml = obj.getContent()
865        else:
866            temp = XMLGen(init=False)
867            self._confToXML(conf,None,includeSession,includeContribution,includeMaterial,showSession=showSession, showDate="all", showContribution=showContribution, showWithdrawed=False, useSchedule=False, out=temp)
868            xml = temp.getXml()
869            self.cache.cacheObject(version, xml, conf)
870        #    out.writeTag("cache", "not found in cache")
871        #else:
872        #    out.writeTag("cache", "found in cache")
873
874        out.writeXML(xml)
875        #return xml
876
877
878
879    #fb
880
881    def confToXMLMarc21(self,conf,includeSession=1,includeContribution=1,includeMaterial=1,out=None, forceCache=False, source=None):
882
883        if not out:
884            out = self._XMLGen
885        #try to get a cache
886        version = "MARC21_ses-%s_cont-%s_mat-%s"%(includeSession,includeContribution,includeMaterial)
887        obj = None
888        if not forceCache:
889            obj = self.cache.loadObject(version, conf)
890        if obj:
891            xml = obj.getContent()
892        else:
893            # No cache, build the XML
894            temp = XMLGen(init=False)
895            self._confToXMLMarc21(conf,includeSession,includeContribution,includeMaterial, out=temp, source=source)
896            xml = temp.getXml()
897            # save XML in cache
898            self.cache.cacheObject(version, xml, conf)
899        out.writeXML(xml)
900
901    def _confToXMLMarc21(self,conf,includeSession=1,includeContribution=1,includeMaterial=1,out=None, source=None):
902        if not out:
903            out = self._XMLGen
904
905        out.openTag("marc:datafield",[["tag","245"],["ind1"," "],["ind2"," "]])
906        out.writeTag("marc:subfield",conf.getTitle(),[["code","a"]])
907        out.closeTag("marc:datafield")
908
909        out.writeTag("marc:leader", "00000nmm  2200000uu 4500")
910        out.openTag("marc:datafield",[["tag","111"],["ind1"," "],["ind2"," "]])
911        out.writeTag("marc:subfield",conf.title,[["code","a"]])
912
913        # XXX: If there is ROOM and not LOCATION....There will be information missed.
914        for l in conf.getLocationList():
915            loc = ""
916            if l.getName() != "":
917                loc = conf.getLocation().getName()
918            if l.getAddress() != "":
919                loc = loc +", "+conf.getLocation().getAddress()
920
921            if conf.getRoom():
922                roomName = self._getRoom(conf.getRoom(), l)
923                loc = loc + ", " + roomName
924
925            if l.getName() != "":
926                out.writeTag("marc:subfield",loc,[["code","c"]])
927
928
929        #out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(conf.getStartDate().year, string.zfill(conf.getStartDate().month,2), string.zfill(conf.getStartDate().day,2), string.zfill(conf.getStartDate().hour,2), string.zfill(conf.getStartDate().minute,2)),[["code","9"]])
930        #out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(conf.getEndDate().year, string.zfill(conf.getEndDate().month,2), string.zfill(conf.getEndDate().day,2), string.zfill(conf.getEndDate().hour,2), string.zfill(conf.getEndDate().minute,2)),[["code","z"]])
931        #tz = conf.getTimezone()
932        #sd = conf.getAdjustedStartDate(tz)
933        #ed = conf.getAdjustedEndDate(tz)
934        sd = conf.getStartDate()
935        ed = conf.getEndDate()
936        out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(sd.year, string.zfill(sd.month,2), string.zfill(sd.day,2), string.zfill(sd.hour,2), string.zfill(sd.minute,2)),[["code","9"]])
937        out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(ed.year, string.zfill(ed.month,2), string.zfill(ed.day,2), string.zfill(ed.hour,2), string.zfill(ed.minute,2)),[["code","z"]])
938
939        out.writeTag("marc:subfield", self.dataInt.objToId(conf),[["code","g"]])
940        out.closeTag("marc:datafield")
941
942        for path in conf.getCategoriesPath():
943            out.openTag("marc:datafield",[["tag","650"],["ind1"," "],["ind2","7"]])
944            out.writeTag("marc:subfield", ":".join(path), [["code","a"]])
945            out.closeTag("marc:datafield")
946
947        ####################################
948        # Fermi timezone awareness         #
949        ####################################
950        #if conf.getStartDate() is not None:
951        #    out.openTag("marc:datafield",[["tag","518"],["ind1"," "],["ind2"," "]])
952        #    out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(conf.getStartDate().year, string.zfill(conf.getStartDate().month,2), string.zfill(conf.getStartDate().day,2), string.zfill(conf.getStartDate().hour,2), string.zfill(conf.getStartDate().minute,2)),[["code","d"]])
953        #    out.closeTag("marc:datafield")
954        #sd = conf.getAdjustedStartDate(tz)
955        sd = conf.getStartDate()
956        if sd is not None:
957            out.openTag("marc:datafield",[["tag","518"],["ind1"," "],["ind2"," "]])
958            out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(sd.year, string.zfill(sd.month,2), string.zfill(sd.day,2), string.zfill(sd.hour,2), string.zfill(sd.minute,2)),[["code","d"]])
959            out.closeTag("marc:datafield")
960        ####################################
961        # Fermi timezone awareness(end)    #
962        ####################################
963
964        out.openTag("marc:datafield",[["tag","520"],["ind1"," "],["ind2"," "]])
965        out.writeTag("marc:subfield",conf.getDescription(),[["code","a"]])
966        out.closeTag("marc:datafield")
967
968        if conf.getReportNumberHolder().listReportNumbers():
969            out.openTag("marc:datafield",[["tag","088"],["ind1"," "],["ind2"," "]])
970            for report in conf.getReportNumberHolder().listReportNumbers():
971                out.writeTag("marc:subfield",report[1],[["code","a"]])
972            out.closeTag("marc:datafield")
973
974
975        out.openTag("marc:datafield",[["tag","653"],["ind1","1"],["ind2"," "]])
976        keywords = conf.getKeywords()
977        keywords.replace("\r\n", "\n")
978        for keyword in keywords.split("\n"):
979            out.writeTag("marc:subfield",keyword,[["code","a"]])
980        out.closeTag("marc:datafield")
981
982
983        import MaKaC.webinterface.simple_event as simple_event
984        import MaKaC.webinterface.meeting as meeting
985        type = "Conference"
986        if self.webFactory.getFactory(conf) == simple_event.WebFactory:
987            type = "Lecture"
988        elif self.webFactory.getFactory(conf) == meeting.WebFactory:
989            type = "Meeting"
990        out.openTag("marc:datafield",[["tag","650"],["ind1","2"],["ind2","7"]])
991        out.writeTag("marc:subfield",type,[["code","a"]])
992        out.closeTag("marc:datafield")
993        #### t o d o
994
995        #out.openTag("datafield",[["tag","650"],["ind1","3"],["ind2","7"]])
996        #out.writeTag("subfield",,[["code","a"]])
997        #out.closeTag("datafield")
998
999
1000        # tag 700 chair name
1001        uList = conf.getChairList()
1002        for chair in uList:
1003            out.openTag("marc:datafield",[["tag","906"],["ind1"," "],["ind2"," "]])
1004            nom = chair.getFamilyName() + " " + chair.getFirstName()
1005            out.writeTag("marc:subfield",nom,[["code","p"]])
1006            out.writeTag("marc:subfield",chair.getAffiliation(),[["code","u"]])
1007            out.closeTag("marc:datafield")
1008
1009
1010        #out.openTag("datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1011        matList = conf.getAllMaterialList()
1012        for mat in matList:
1013            if self.dataInt.isPrivateDataInt() or mat.canView(self.__aw):
1014                if includeMaterial:
1015                    self.materialToXMLMarc21(mat, out=out)
1016        #out.closeTag("datafield")
1017
1018        #if respEmail != "":
1019        #    out.openTag("datafield",[["tag","859"],["ind1"," "],["ind2"," "]])
1020        #   out.writeTag("subfield",respEmail,[["code","f"]])
1021        #   out.closeTag("datafield")
1022        # tag 859 email
1023        uList = conf.getChairList()
1024        for chair in uList:
1025            out.openTag("marc:datafield",[["tag","859"],["ind1"," "],["ind2"," "]])
1026            out.writeTag("marc:subfield",chair.getEmail(),[["code","f"]])
1027            out.closeTag("marc:datafield")
1028
1029        edate = conf.getCreationDate()
1030        creaDate = datetime( edate.year, edate.month, edate.day )
1031
1032        out.openTag("marc:datafield",[["tag","961"],["ind1"," "],["ind2"," "]])
1033        out.writeTag("marc:subfield","%d-%s-%sT"%(creaDate.year, string.zfill(creaDate.month,2), string.zfill(creaDate.day,2)),[["code","x"]])
1034        out.closeTag("marc:datafield")
1035
1036        edate = conf.getModificationDate()
1037        modifDate = datetime( edate.year, edate.month, edate.day )
1038
1039        out.openTag("marc:datafield",[["tag","961"],["ind1"," "],["ind2"," "]])
1040        out.writeTag("marc:subfield","%d-%s-%sT"%(modifDate.year, string.zfill(modifDate.month,2), string.zfill(modifDate.day,2)),[["code","c"]])
1041        out.closeTag("marc:datafield")
1042
1043        out.openTag("marc:datafield",[["tag","980"],["ind1"," "],["ind2"," "]])
1044        confcont = "Indico"
1045        out.writeTag("marc:subfield",confcont,[["code","a"]])
1046        out.closeTag("marc:datafield")
1047
1048        out.openTag("marc:datafield",[["tag","970"],["ind1"," "],["ind2"," "]])
1049        out.writeTag("marc:subfield","INDICO." + self.dataInt.objToId(conf),[["code","a"]])
1050        out.closeTag("marc:datafield")
1051
1052        out.openTag("marc:datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1053        url = str(urlHandlers.UHConferenceDisplay.getURL(conf))
1054        out.writeTag("marc:subfield",url,[["code","u"]])
1055        out.writeTag("marc:subfield", "Event details", [["code","y"]])
1056        out.closeTag("marc:datafield")
1057
1058
1059        # Check to make sure this request is coming from the Recording Manager.
1060        # We don't want to provide CERN access list information to external sources like OAI harvesters.
1061        if source is not None and source == 'RecordingManager':
1062
1063            # Also check to make sure that the RecordingManager plugin is installed and active
1064            if (PluginsHolder().hasPluginType("Collaboration") and
1065                PluginsHolder().getPluginType("Collaboration").hasPlugin("RecordingManager") and
1066                PluginsHolder().getPluginType("Collaboration").getPlugin("RecordingManager").isActive()):
1067
1068                # Only provide MARC tag 506 information if there is any access list
1069                # Get set containing Avatar objects (if empty, that means event is public)
1070                allowed_users = conf.getRecursiveAllowedToAccessList()
1071                if allowed_users is not None and len(allowed_users) > 0:
1072                    # Populate two lists holding email/group strings instead of Avatar/Group objects
1073                    allowed_emails = []
1074                    allowed_groups = []
1075                    for user_obj in allowed_users:
1076                        if isinstance(user_obj, Avatar):
1077                            allowed_emails.append(user_obj.getEmail())
1078                        elif isinstance(user_obj, CERNGroup):
1079                            allowed_groups.append(user_obj.getId() + " [CERN]")
1080                        else:
1081                            allowed_emails.append("UNKNOWN: %s" % user_obj.getId())
1082
1083                    # Get subfields from plugin settings:
1084
1085
1086                    field506tag2 = CollaborationTools.getOptionValue("RecordingManager", "MarcField506Subfield2")
1087#                    PluginsHolder().getPluginType("Collaboration").getPlugin("RecordingManager").
1088                    field506tag5 = CollaborationTools.getOptionValue("RecordingManager", "MarcField506Subfield5")
1089
1090                    # Create section for tag 506, listing allowed groups
1091                    if len(allowed_groups) > 0:
1092                        out.openTag("marc:datafield",[["tag","506"], ["ind1","1"], ["ind2"," "]])
1093                        out.writeTag("marc:subfield", "Restricted",  [["code", "a"]])
1094                        for group_id in allowed_groups:
1095                            out.writeTag("marc:subfield", group_id,  [["code", "d"]])
1096                        out.writeTag("marc:subfield", "group",       [["code", "f"]])
1097                        out.writeTag("marc:subfield", field506tag2, [["code", "2"]])
1098                        out.writeTag("marc:subfield", field506tag5, [["code", "5"]])
1099                        out.closeTag("marc:datafield")
1100
1101                    # Create another section for tag 506, listing allowed users
1102                    if len(allowed_users) > 0:
1103                        out.openTag("marc:datafield",[["tag","506"], ["ind1","1"], ["ind2"," "]])
1104                        out.writeTag("marc:subfield", "Restricted",  [["code", "a"]])
1105                        for email_id in allowed_emails:
1106                            out.writeTag("marc:subfield", email_id,  [["code", "d"]])
1107                        out.writeTag("marc:subfield", "email",       [["code", "f"]])
1108                        out.writeTag("marc:subfield", field506tag2, [["code", "2"]])
1109                        out.writeTag("marc:subfield", field506tag5, [["code", "5"]])
1110                        out.closeTag("marc:datafield")
1111
1112    ## def sessionToXMLMarc21(self,session,includeMaterial=1, out=None, forceCache=False):
1113    ##     if not out:
1114    ##         out = self._XMLGen
1115    ##     #try to get a cache
1116    ##     version = "MARC21_mat-%s"%(includeMaterial)
1117    ##     xml = ""
1118    ##     if not xml:
1119    ##         # No cache, build the XML
1120    ##         temp = XMLGen(init=False)
1121    ##         self._sessionToXMLMarc21(session,includeMaterial, out=temp)
1122    ##         xml = temp.getXml()
1123    ##     out.writeXML(xml)
1124
1125
1126    ## def _sessionToXMLMarc21(self,session,includeMaterial=1, out=None):
1127    ##     if not out:
1128    ##         out = self._XMLGen
1129
1130    ##     out.writeTag("marc:leader", "00000nmm  2200000uu 4500")
1131    ##     out.openTag("marc:datafield",[["tag","035"],["ind1"," "],["ind2"," "]])
1132    ##     out.writeTag("marc:subfield","INDICO%s"%(self.dataInt.objToId(session, separator="."), session.getId()),[["code","a"]])
1133    ##     out.closeTag("marc:datafield")
1134
1135    ##     out.openTag("marc:datafield",[["tag","035"],["ind1"," "],["ind2"," "]])
1136    ##     out.writeTag("marc:subfield",self.dataInt.objToId(session, separator="."),[["code","a"]])
1137    ##     out.writeTag("marc:subfield","Indico",[["code","9"]])
1138    ##     out.closeTag("marc:datafield")
1139
1140    ##     out.openTag("marc:datafield",[["tag","245"],["ind1"," "],["ind2"," "]])
1141    ##     out.writeTag("marc:subfield",session.getTitle(),[["code","a"]])
1142    ##     out.closeTag("marc:datafield")
1143
1144    ##     out.openTag("marc:datafield",[["tag","300"],["ind1"," "],["ind2"," "]])
1145    ##     out.writeTag("marc:subfield",session.getDuration(),[["code","a"]])
1146    ##     out.closeTag("marc:datafield")
1147
1148    ##     out.openTag("marc:datafield",[["tag","111"],["ind1"," "],["ind2"," "]])
1149    ##     out.writeTag("marc:subfield", self.dataInt.objToId(session.getConference()),[["code","g"]])
1150    ##     out.closeTag("marc:datafield")
1151
1152    ##     for path in session.getConference().getCategoriesPath():
1153    ##         out.openTag("marc:datafield",[["tag","650"],["ind1"," "],["ind2","7"]])
1154    ##         out.writeTag("marc:subfield", ":".join(path), [["code","a"]])
1155    ##         out.closeTag("marc:datafield")
1156
1157    ##     l=session.getLocation()
1158    ##     if (l and l.getName() != "") or session.getStartDate() is not None:
1159    ##         out.openTag("marc:datafield",[["tag","518"],["ind1"," "],["ind2"," "]])
1160    ##         if l:
1161    ##             if l.getName() != "":
1162    ##                 out.writeTag("marc:subfield",l.getName(),[["code","r"]])
1163    ##         if session.getStartDate() is not None:
1164    ##             out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(session.getStartDate().year, string.zfill(session.getStartDate().month,2), string.zfill(session.getStartDate().day,2), string.zfill(session.getStartDate().hour,2), string.zfill(session.getStartDate().minute,2)),[["code","d"]])
1165    ##             out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(session.getEndDate().year, string.zfill(session.getEndDate().month,2), string.zfill(session.getEndDate().day,2), string.zfill(session.getEndDate().hour,2), string.zfill(session.getEndDate().minute,2)),[["code","h"]])
1166    ##         out.closeTag("marc:datafield")
1167    ## #
1168    ##     out.openTag("marc:datafield",[["tag","520"],["ind1"," "],["ind2"," "]])
1169    ##     out.writeTag("marc:subfield",session.getDescription(),[["code","a"]])
1170    ##     out.closeTag("marc:datafield")
1171
1172    ##     out.openTag("marc:datafield",[["tag","611"],["ind1","2"],["ind2","4"]])
1173    ##     out.writeTag("marc:subfield",session.getConference().getTitle(),[["code","a"]])
1174    ##     out.closeTag("marc:datafield")
1175    ##     out.openTag("marc:datafield",[["tag","650"],["ind1","1"],["ind2","7"]])
1176    ##     out.writeTag("marc:subfield","SzGeCERN",[["code","2"]])
1177    ##     out.closeTag("marc:datafield")
1178
1179
1180    ##     # tag 100/700 Convener name
1181    ##     cList = session.getConvenerList()
1182
1183    ##     for user in cList:
1184    ##         if user == cList[0]:
1185    ##             code = "100"
1186    ##         else:
1187    ##             code = "700"
1188    ##         out.openTag("marc:datafield",[["tag",code],["ind1"," "],["ind2"," "]])
1189    ##         fullName = user.getFamilyName() + " " + user.getFirstName()
1190    ##         out.writeTag("marc:subfield",fullName,[["code","a"]])
1191    ##         out.writeTag("marc:subfield","Convener",[["code","e"]])
1192    ##         out.writeTag("marc:subfield",user.getAffiliation(),[["code","u"]])
1193    ##         out.closeTag("marc:datafield")
1194
1195    ##     matList = session.getAllMaterialList()
1196    ##     for mat in matList:
1197    ##         if mat.canView(self.__aw):
1198    ##             if includeMaterial:
1199    ##                 self.materialToXMLMarc21(mat, out=out)
1200
1201    ##     out.openTag("marc:datafield",[["tag","962"],["ind1"," "],["ind2"," "]])
1202    ##     out.writeTag("marc:subfield","INDICO.%s"%self.dataInt.objToId(session.getConference()),[["code","b"]])
1203    ##     out.closeTag("marc:datafield")
1204
1205    ##     out.openTag("marc:datafield",[["tag","970"],["ind1"," "],["ind2"," "]])
1206    ##     confses = "INDICO." + self.dataInt.objToId(session.getConference(), separator=".")
1207    ##     out.writeTag("marc:subfield",confses,[["code","a"]])
1208    ##     out.closeTag("marc:datafield")
1209
1210    ##     out.openTag("marc:datafield",[["tag","980"],["ind1"," "],["ind2"," "]])
1211    ##     confcont = "INDICO." + self.dataInt.objToId(session.getConference())
1212    ##     out.writeTag("marc:subfield",confcont,[["code","a"]])
1213    ##     out.closeTag("marc:datafield")
1214
1215    ##     out.openTag("marc:datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1216    ##     url = str(urlHandlers.UHSessionDisplay.getURL(session))
1217    ##     out.writeTag("marc:subfield",url,[["code","u"]])
1218    ##     out.writeTag("marc:subfield", "Session details", [["code","y"]])
1219    ##     out.closeTag("marc:datafield")
1220
1221
1222    #fb
1223
1224    def contribToXMLMarc21(self,cont,includeMaterial=1, out=None, forceCache=False):
1225        if not out:
1226            out = self._XMLGen
1227        #try to get a cache
1228        version = "MARC21_mat-%s"%(includeMaterial)
1229        obj = None
1230        if not forceCache:
1231            obj = self.cache.loadObject(version, cont)
1232        if obj:
1233            xml = obj.getContent()
1234        else:
1235            # No cache, build the XML
1236            temp = XMLGen(init=False)
1237            self._contribToXMLMarc21(cont,includeMaterial, out=temp)
1238            xml = temp.getXml()
1239            # save XML in cache
1240            self.cache.cacheObject(version, xml, cont)
1241        out.writeXML(xml)
1242
1243
1244    def _contribToXMLMarc21(self,cont,includeMaterial=1, out=None):
1245        if not out:
1246            out = self._XMLGen
1247
1248        #out.writeTag("controlfield","SzGeCERN",[["tag","003"]])
1249        out.writeTag("marc:leader", "00000nmm  2200000uu 4500")
1250        out.openTag("marc:datafield",[["tag","035"],["ind1"," "],["ind2"," "]])
1251        out.writeTag("marc:subfield","INDICO.%s"%self.dataInt.objToId(cont, separator="."),[["code","a"]])
1252        out.closeTag("marc:datafield")
1253    #
1254        out.openTag("marc:datafield",[["tag","035"],["ind1"," "],["ind2"," "]])
1255        out.writeTag("marc:subfield",self.dataInt.objToId(cont, separator="t"),[["code","a"]])
1256        out.writeTag("marc:subfield","Indico",[["code","9"]])
1257        out.closeTag("marc:datafield")
1258
1259        out.openTag("marc:datafield",[["tag","245"],["ind1"," "],["ind2"," "]])
1260        out.writeTag("marc:subfield",cont.getTitle(),[["code","a"]])
1261        out.closeTag("marc:datafield")
1262
1263        out.openTag("marc:datafield",[["tag","300"],["ind1"," "],["ind2"," "]])
1264        out.writeTag("marc:subfield",cont.getDuration(),[["code","a"]])
1265        out.closeTag("marc:datafield")
1266
1267        out.openTag("marc:datafield",[["tag","111"],["ind1"," "],["ind2"," "]])
1268        out.writeTag("marc:subfield", self.dataInt.objToId(cont.getConference()),[["code","g"]])
1269        out.closeTag("marc:datafield")
1270
1271        for path in cont.getConference().getCategoriesPath():
1272            out.openTag("marc:datafield",[["tag","650"],["ind1"," "],["ind2","7"]])
1273            out.writeTag("marc:subfield", ":".join(path), [["code","a"]])
1274            out.closeTag("marc:datafield")
1275
1276        l=cont.getLocation()
1277        if (l and l.getName() != "") or cont.getStartDate() is not None:
1278            out.openTag("marc:datafield",[["tag","518"],["ind1"," "],["ind2"," "]])
1279            if l:
1280                if l.getName() != "":
1281                    out.writeTag("marc:subfield",l.getName(),[["code","r"]])
1282            if cont.getStartDate() is not None:
1283                out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(cont.getStartDate().year, string.zfill(cont.getStartDate().month,2), string.zfill(cont.getStartDate().day,2), string.zfill(cont.getStartDate().hour,2), string.zfill(cont.getStartDate().minute,2)),[["code","d"]])
1284                out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(cont.getEndDate().year, string.zfill(cont.getEndDate().month,2), string.zfill(cont.getEndDate().day,2), string.zfill(cont.getEndDate().hour,2), string.zfill(cont.getEndDate().minute,2)),[["code","h"]])
1285            out.closeTag("marc:datafield")
1286    #
1287        out.openTag("marc:datafield",[["tag","520"],["ind1"," "],["ind2"," "]])
1288        out.writeTag("marc:subfield",cont.getDescription(),[["code","a"]])
1289        out.closeTag("marc:datafield")
1290
1291        out.openTag("marc:datafield",[["tag","611"],["ind1","2"],["ind2","4"]])
1292        out.writeTag("marc:subfield",cont.getConference().getTitle(),[["code","a"]])
1293        out.closeTag("marc:datafield")
1294
1295
1296        if cont.getReportNumberHolder().listReportNumbers():
1297            out.openTag("marc:datafield",[["tag","088"],["ind1"," "],["ind2"," "]])
1298            for report in cont.getReportNumberHolder().listReportNumbers():
1299                out.writeTag("marc:subfield",report[1],[["code","a"]])
1300            out.closeTag("marc:datafield")
1301
1302
1303        out.openTag("marc:datafield",[["tag","653"],["ind1","1"],["ind2"," "]])
1304        keywords = cont.getKeywords()
1305        keywords.replace("\r\n", "\n")
1306        for keyword in keywords.split("\n"):
1307            out.writeTag("marc:subfield",keyword,[["code","a"]])
1308        out.closeTag("marc:datafield")
1309
1310
1311    #
1312        out.openTag("marc:datafield",[["tag","650"],["ind1","1"],["ind2","7"]])
1313        out.writeTag("marc:subfield","SzGeCERN",[["code","2"]])
1314        if cont.getTrack():
1315            out.writeTag("marc:subfield",cont.getTrack().getTitle(),[["code","a"]])
1316        out.closeTag("marc:datafield")
1317
1318
1319        # tag 700 Speaker name
1320        aList = cont.getAuthorList()
1321        sList = cont.getSpeakerList()
1322        list = {}
1323        auth = cont.getPrimaryAuthorList()
1324        if auth:
1325            auth = auth[0]
1326            list[auth] = ["Primary Author"]
1327        for user in aList:
1328            if user in list:
1329                if user != auth:
1330                    list[user].append("Author")
1331            else:
1332                list[user] = ["Author"]
1333
1334        for user in sList:
1335            if user in list:
1336                list[user].append("Speaker")
1337            else:
1338                list[user] = ["Speaker"]
1339
1340        if auth:
1341            user = auth
1342            out.openTag("marc:datafield",[["tag","100"],["ind1"," "],["ind2"," "]])
1343            fullName = auth.getFamilyName() + " " + auth.getFirstName()
1344            out.writeTag("marc:subfield",fullName,[["code","a"]])
1345            for val in list[user]:
1346                out.writeTag("marc:subfield",val,[["code","e"]])
1347            out.writeTag("marc:subfield",auth.getAffiliation(),[["code","u"]])
1348            out.closeTag("marc:datafield")
1349            del list[auth]
1350
1351        for user in list.keys():
1352            out.openTag("marc:datafield",[["tag","700"],["ind1"," "],["ind2"," "]])
1353            fullName = user.getFamilyName() + " " + user.getFirstName()
1354            out.writeTag("marc:subfield",fullName,[["code","a"]])
1355            for val in list[user]:
1356                out.writeTag("marc:subfield",val,[["code","e"]])
1357            out.writeTag("marc:subfield",user.getAffiliation(),[["code","u"]])
1358            out.closeTag("marc:datafield")
1359
1360
1361
1362
1363
1364        matList = cont.getAllMaterialList()
1365        for mat in matList:
1366            #out.openTag("datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1367            if self.dataInt.isPrivateDataInt() or mat.canView(self.__aw):
1368                if includeMaterial:
1369                    self.materialToXMLMarc21(mat, out=out)
1370            #   else:
1371            #       out.writeTag("material",out.writeTag("id",mat.id))
1372        # no subContibution
1373        #for subC in cont.getSubContributionList():
1374        #    self.subContributionToXML(subC,includeMaterial)
1375            #out.closeTag("datafield")
1376
1377
1378
1379        out.openTag("marc:datafield",[["tag","962"],["ind1"," "],["ind2"," "]])
1380        out.writeTag("marc:subfield","INDICO.%s"%self.dataInt.objToId(cont.getConference()),[["code","b"]])
1381        out.closeTag("marc:datafield")
1382
1383        out.openTag("marc:datafield",[["tag","970"],["ind1"," "],["ind2"," "]])
1384        confcont = "INDICO." + self.dataInt.objToId(cont, separator=".")
1385        out.writeTag("marc:subfield",confcont,[["code","a"]])
1386        out.closeTag("marc:datafield")
1387
1388        out.openTag("marc:datafield",[["tag","980"],["ind1"," "],["ind2"," "]])
1389        confcont = "INDICO." + self.dataInt.objToId(cont.getConference())
1390        out.writeTag("marc:subfield",confcont,[["code","a"]])
1391        out.closeTag("marc:datafield")
1392
1393        out.openTag("marc:datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1394        url = str(urlHandlers.UHContributionDisplay.getURL(cont))
1395        out.writeTag("marc:subfield",url,[["code","u"]])
1396        out.writeTag("marc:subfield", "Contribution details", [["code","y"]])
1397        out.closeTag("marc:datafield")
1398
1399    ####
1400    #fb
1401
1402
1403    def subContribToXMLMarc21(self,subCont,includeMaterial=1, out=None, forceCache=False):
1404        if not out:
1405            out = self._XMLGen
1406        #try to get a cache
1407        version = "MARC21_mat-%s"%(includeMaterial)
1408        obj = None
1409        if not forceCache:
1410            obj = self.cache.loadObject(version, subCont)
1411        if obj:
1412            xml = obj.getContent()
1413        else:
1414            # No cache, build the XML
1415            temp = XMLGen(init=False)
1416            self._subContribToXMLMarc21(subCont,includeMaterial, out=temp)
1417            xml = temp.getXml()
1418            # save XML in cache
1419            self.cache.cacheObject(version, xml, subCont)
1420        out.writeXML(xml)
1421
1422
1423    def _subContribToXMLMarc21(self,subCont,includeMaterial=1, out=None):
1424        if not out:
1425            out = self._XMLGen
1426
1427        #out.writeTag("controlfield","SzGeCERN",[["tag","003"]])
1428        out.writeTag("marc:leader", "00000nmm  2200000uu 4500")
1429        out.openTag("marc:datafield",[["tag","035"],["ind1"," "],["ind2"," "]])
1430        out.writeTag("marc:subfield","INDICO.%s"%(self.dataInt.objToId(subCont, separator=".")),[["code","a"]])
1431        out.closeTag("marc:datafield")
1432    #
1433        out.openTag("marc:datafield",[["tag","035"],["ind1"," "],["ind2"," "]])
1434        out.writeTag("marc:subfield",self.dataInt.objToId(subCont, separator=["t","sc"]),[["code","a"]])
1435        out.writeTag("marc:subfield","Indico",[["code","9"]])
1436        out.closeTag("marc:datafield")
1437
1438        out.openTag("marc:datafield",[["tag","245"],["ind1"," "],["ind2"," "]])
1439        out.writeTag("marc:subfield",subCont.getTitle(),[["code","a"]])
1440        out.closeTag("marc:datafield")
1441
1442        out.openTag("marc:datafield",[["tag","300"],["ind1"," "],["ind2"," "]])
1443        out.writeTag("marc:subfield",subCont.getDuration(),[["code","a"]])
1444        out.closeTag("marc:datafield")
1445
1446        out.openTag("marc:datafield",[["tag","111"],["ind1"," "],["ind2"," "]])
1447        out.writeTag("marc:subfield", self.dataInt.objToId(subCont.getConference(), separator="."),[["code","g"]])
1448        out.closeTag("marc:datafield")
1449
1450        if subCont.getReportNumberHolder().listReportNumbers():
1451            out.openTag("marc:datafield",[["tag","088"],["ind1"," "],["ind2"," "]])
1452            for report in subCont.getReportNumberHolder().listReportNumbers():
1453                out.writeTag("marc:subfield",report[1],[["code","a"]])
1454            out.closeTag("marc:datafield")
1455
1456
1457        out.openTag("marc:datafield",[["tag","653"],["ind1","1"],["ind2"," "]])
1458        keywords = subCont.getKeywords()
1459        keywords.replace("\r\n", "\n")
1460        for keyword in keywords.split("\n"):
1461            out.writeTag("marc:subfield",keyword,[["code","a"]])
1462        out.closeTag("marc:datafield")
1463
1464
1465        for path in subCont.getConference().getCategoriesPath():
1466            out.openTag("marc:datafield",[["tag","650"],["ind1"," "],["ind2","7"]])
1467            out.writeTag("marc:subfield", ":".join(path), [["code","a"]])
1468            out.closeTag("marc:datafield")
1469
1470        l=subCont.getLocation()
1471        if (l and l.getName() != "") or subCont.getContribution().getStartDate() is not None:
1472            out.openTag("marc:datafield",[["tag","518"],["ind1"," "],["ind2"," "]])
1473            if l:
1474                if l.getName() != "":
1475                    out.writeTag("marc:subfield",l.getName(),[["code","r"]])
1476            if subCont.getContribution().getStartDate() is not None:
1477                out.writeTag("marc:subfield","%d-%s-%sT%s:%s:00Z" %(subCont.getContribution().getStartDate().year, string.zfill(subCont.getContribution().getStartDate().month,2), string.zfill(subCont.getContribution().getStartDate().day,2), string.zfill(subCont.getContribution().getStartDate().hour,2), string.zfill(subCont.getContribution().getStartDate().minute,2)),[["code","d"]])
1478                #out.writeTag("subfield","%d-%s-%sT%s:%s:00Z" %(subCont.getEndDate().year, string.zfill(subCont.getEndDate().month,2), string.zfill(subCont.getEndDate().day,2), string.zfill(subCont.getEndDate().hour,2), string.zfill(subCont.getEndDate().minute,2)),[["code","h"]])
1479            out.closeTag("marc:datafield")
1480    #
1481        out.openTag("marc:datafield",[["tag","520"],["ind1"," "],["ind2"," "]])
1482        out.writeTag("marc:subfield",subCont.getDescription(),[["code","a"]])
1483        out.closeTag("marc:datafield")
1484
1485        out.openTag("marc:datafield",[["tag","611"],["ind1","2"],["ind2","4"]])
1486        out.writeTag("marc:subfield",subCont.getConference().getTitle(),[["code","a"]])
1487        out.closeTag("marc:datafield")
1488    #
1489        out.openTag("marc:datafield",[["tag","650"],["ind1","1"],["ind2","7"]])
1490        out.writeTag("marc:subfield","SzGeCERN",[["code","2"]])
1491        if subCont.getContribution().getTrack():
1492            out.writeTag("marc:subfield",subCont.getContribution().getTrack().getTitle(),[["code","a"]])
1493        out.closeTag("marc:datafield")
1494
1495
1496        # tag 700 Speaker name
1497        aList = subCont.getContribution().getAuthorList()
1498        sList = subCont.getSpeakerList()
1499        list = {}
1500        auth = subCont.getContribution().getPrimaryAuthorList()
1501        if auth:
1502            auth = auth[0]
1503            list[auth] = ["Primary Author"]
1504        for user in aList:
1505            if user in list:
1506                if user != auth:
1507                    list[user].append("Author")
1508            else:
1509                list[user] = ["Author"]
1510
1511        for user in sList:
1512            if user in list:
1513                list[user].append("Speaker")
1514            else:
1515                list[user] = ["Speaker"]
1516
1517        if auth:
1518            user = auth
1519            out.openTag("marc:datafield",[["tag","100"],["ind1"," "],["ind2"," "]])
1520            fullName = auth.getFamilyName() + " " + auth.getFirstName()
1521            out.writeTag("marc:subfield",fullName,[["code","a"]])
1522            for val in list[user]:
1523                out.writeTag("marc:subfield",val,[["code","e"]])
1524            out.writeTag("marc:subfield",auth.getAffiliation(),[["code","u"]])
1525            out.closeTag("marc:datafield")
1526            del list[auth]
1527
1528        for user in list.keys():
1529            out.openTag("marc:datafield",[["tag","700"],["ind1"," "],["ind2"," "]])
1530            fullName = user.getFamilyName() + " " + user.getFirstName()
1531            out.writeTag("marc:subfield",fullName,[["code","a"]])
1532            for val in list[user]:
1533                out.writeTag("marc:subfield",val,[["code","e"]])
1534            out.writeTag("marc:subfield",user.getAffiliation(),[["code","u"]])
1535            out.closeTag("marc:datafield")
1536
1537
1538
1539
1540
1541        matList = subCont.getAllMaterialList()
1542        for mat in matList:
1543            #out.openTag("datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1544            if self.dataInt.isPrivateDataInt() or mat.canView(self.__aw):
1545                if includeMaterial:
1546                    self.materialToXMLMarc21(mat, out=out)
1547            #    else:
1548            #        out.writeTag("material",out.writeTag("id",mat.id))
1549
1550
1551
1552
1553        out.openTag("marc:datafield",[["tag","962"],["ind1"," "],["ind2"," "]])
1554        out.writeTag("marc:subfield","INDICO.%s"%self.dataInt.objToId(subCont.getConference()),[["code","b"]])
1555        out.closeTag("marc:datafield")
1556
1557        out.openTag("marc:datafield",[["tag","970"],["ind1"," "],["ind2"," "]])
1558        confcont = "INDICO." + self.dataInt.objToId(subCont, separator=".")
1559        out.writeTag("marc:subfield",confcont,[["code","a"]])
1560        out.closeTag("marc:datafield")
1561
1562        out.openTag("marc:datafield",[["tag","980"],["ind1"," "],["ind2"," "]])
1563        confcont = "INDICO." + self.dataInt.objToId(subCont.getConference())
1564        out.writeTag("marc:subfield",confcont,[["code","a"]])
1565        out.closeTag("marc:datafield")
1566
1567        out.openTag("marc:datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1568        url = str(urlHandlers.UHSubContributionDisplay.getURL(subCont))
1569        out.writeTag("marc:subfield",url,[["code","u"]])
1570        out.writeTag("marc:subfield", "Contribution details", [["code","y"]])
1571        out.closeTag("marc:datafield")
1572
1573
1574    def materialToXMLMarc21(self,mat, out=None):
1575        if not out:
1576            out = self._XMLGen
1577        #out.openTag("material")
1578        #out.writeTag("ID",mat.getId())
1579        #out.writeTag("title",mat.title)
1580        #out.writeTag("description",mat.description)
1581        #out.writeTag("type",mat.type)
1582        rList = mat.getResourceList()
1583        self.resourcesToXMLMarc21(rList, out=out)
1584        #out.closeTag("material")
1585
1586    def resourcesToXMLMarc21(self, rList, out=None):
1587        if not out:
1588            out = self._XMLGen
1589        #out.openTag("resources")
1590        for res in rList:
1591            if self.dataInt.isPrivateDataInt() or res.canView(self.__aw):
1592                self.resourceToXMLMarc21(res, out=out)
1593        #out.closeTag("resources")
1594
1595
1596
1597    def resourceToXMLMarc21(self,res, out=None):
1598        if not out:
1599            out = self._XMLGen
1600        if type(res) == conference.LocalFile:
1601            self.resourceFileToXMLMarc21(res, out=out)
1602        else:
1603            self.resourceLinkToXMLMarc21(res, out=out)
1604
1605    def resourceLinkToXMLMarc21(self,res, out=None):
1606        if not out:
1607            out = self._XMLGen
1608
1609        #out.writeTag("name",res.getName())
1610        out.openTag("marc:datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1611        out.writeTag("marc:subfield",res.getDescription(),[["code","a"]])
1612        #out.writeTag("description",res.getDescription())
1613        #out.writeTag("url",res.getURL())
1614        out.writeTag("marc:subfield",res.getURL(),[["code","u"]])
1615        out.writeTag("marc:subfield", "resource", [["code","x"]])
1616        out.writeTag("marc:subfield", res.getOwner().getTitle(), [["code","y"]])
1617        out.closeTag("marc:datafield")
1618
1619    def resourceFileToXMLMarc21(self,res, out=None):
1620        if not out:
1621            out = self._XMLGen
1622
1623        #out.writeTag("name",res.getName())
1624        #out.writeTag("description",res.getDescription())
1625        #out.writeTag("type",res.fileType)
1626        out.openTag("marc:datafield",[["tag","856"],["ind1","4"],["ind2"," "]])
1627        out.writeTag("marc:subfield",res.getDescription(),[["code","a"]])
1628        try:
1629            out.writeTag("marc:subfield",res.getSize(),[["code","s"]])
1630        except:
1631            pass
1632        #out.writeTag("subfield",res.getURL(),[["code","u"]])
1633
1634        #out.writeTag("subfield",res.getFileName(),[["code","q"]])
1635        url = str(urlHandlers.UHFileAccess.getURL( res ))
1636        out.writeTag("marc:subfield",url,[["code","u"]])
1637        out.writeTag("marc:subfield", res.getFileName(), [["code","y"]])
1638        out.writeTag("marc:subfield", "resource", [["code","x"]])
1639        out.closeTag("marc:datafield")
1640        #out.writeTag("duration","1")#TODO:DURATION ISN'T ESTABLISHED
1641        #cDate = res.getCreationDate()
1642        #creationDateStr = "%d-%s-%sT%s:%s:00Z" %(cDate.year, string.zfill(cDate.month,2), string.zfill(cDate.day,2), string.zfill(cDate.hour,2), string.zfill(cDate.minute,2))
1643        #out.writeTag("creationDate",creationDateStr)
1644
1645class XMLCacheEntry(MultiLevelCacheEntry):
1646    def __init__(self, objId):
1647        MultiLevelCacheEntry.__init__(self)
1648        self.id = objId
1649
1650    def getId(self):
1651        return self.id
1652
1653    @classmethod
1654    def create(cls, content, obj):
1655        entry = cls(getHierarchicalId(obj))
1656        entry.setContent(content)
1657        return entry
1658
1659
1660class XMLCache(MultiLevelCache):
1661
1662    _entryFactory = XMLCacheEntry
1663
1664    def __init__(self):
1665        MultiLevelCache.__init__(self, 'xml')
1666
1667
1668    def isDirty(self, file, object):
1669
1670        # get event OAI date
1671        oaiModDate = resolveHierarchicalId(object.getId()).getOAIModificationDate()
1672        fileModDate = timezone("UTC").localize(
1673            datetime.utcfromtimestamp(os.path.getmtime(file)))
1674
1675        # check file system date vs. event date
1676        return (oaiModDate > fileModDate)
1677
1678    def _generatePath(self, entry):
1679        """
1680        Generate the actual hierarchical location
1681        """
1682
1683        # by default, use the dots and first char
1684        # a205.0 -> /cachedir/a/a205/0
1685
1686        tree = entry.getId().split('.')
1687        return [tree[0][0]]+tree
1688
1689
1690class ProtectedXMLCache(XMLCache):
1691    """
1692    XMLCache that is content protection-aware
1693    It uses a DataInt, in order to map object to their
1694    corresponding ids (rXXX, pXXX)
1695    """
1696
1697
1698    def __init__(self, dataInt):
1699        XMLCache.__init__(self)
1700        self.dataInt = dataInt
1701
1702    def _getRecordId(self, obj):
1703        return self.dataInt.objToId(obj, separator='.')
1704
1705    def generatePath(self, obj):
1706        """
1707        Generate the actual hierarchical location
1708        """
1709
1710        # by default, use the dots and first char
1711        # pa205.0 -> /cachedir/p/a/a205/0
1712
1713        tree = self._getRecordId(obj).split('.')
1714        return [tree[0][0]]+[tree[0][1]]+[tree[0][1:]]+tree[1:]
Note: See TracBrowser for help on using the repository browser.