Exemplo n.º 1
0
 def _process(self):
     try:
         user = self._request_token.getUser()
         access_tokens = Catalog.getIdx('user_oauth_access_token').get(user.getId())
         timestamp = nowutc()
         if access_tokens is not None:
             for access_token in list(access_tokens):
                 if access_token.getConsumer().getName() == self._request_token.getConsumer().getName():
                     access_token.setTimestamp(timestamp)
                     response = {'oauth_token': access_token.getId(),
                                 'oauth_token_secret': access_token.getToken().secret,
                                 'user_id': user.getId(),
                                 'oauth_token_ttl': Config.getInstance().getOAuthAccessTokenTTL(),
                                 'oauth_token_expiration_timestamp': access_token.getTimestamp() +
                                 timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL())}
                     return urlencode(response)
         access_token_key = OAuthUtils.gen_random_string()
         access_token_secret = OAuthUtils.gen_random_string()
         access_token = Token(access_token_key, oauth.Token(access_token_key, access_token_secret),
                              timestamp, self._request_token.getConsumer(), user)
         AccessTokenHolder().add(access_token)
         response = {'oauth_token': access_token_key,
                     'oauth_token_secret': access_token_secret,
                     'user_id': user.getId(),
                     'oauth_token_ttl': Config.getInstance().getOAuthAccessTokenTTL(),
                     'oauth_token_expiration_timestamp': access_token.getTimestamp() +
                     timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL())}
         return urlencode(response)
     except oauth.Error, err:
         raise OAuthError(err.message, 401)
Exemplo n.º 2
0
 def convert(filepath, converter, material):
     # Material UID
     materialUID="%s"%material.getLocator()
     # Getting variables
     responseURL = Config.getInstance().getFileConverterResponseURL()
     serverURL = Config.getInstance().getFileConverterServerURL()
     up = urlparse.urlparse(serverURL)
     if up[0] == "":
         #writeLog("Wrong conversion server URL")
         return
     host = up[1]
     selector = up[2]        
     # Checking the file
     localFile = filepath.strip()
     localFile = localFile.replace("\\", "/")
     filename = localFile.split("/")[-1]
     if not os.access(localFile, os.F_OK):
         #writeLog("Local file to upload invalid")
         return False
     fic=open(localFile, "rb")
     segnum=0
     segsize = SEGMENT_SIZE
     filekey = 'segfile'
     i = 0
     
     try :
         h = httplib.HTTP(host)
     except Exception, e:
         #writeLog("Error : Can't connect to host:%s"%host)
         return False
Exemplo n.º 3
0
    def alertCreation(self, confs):
        conf = confs[0]
        fromAddr = Config.getInstance().getSupportEmail()
        addrs = [ Config.getInstance().getSupportEmail() ]
        eventType = conf.getType()
        if eventType == "conference":
            type = "conference"
        elif eventType == "meeting":
            type = "meeting"
        else:
            type = "lecture"
        chair = ""
        if conf.getChairmanText() != "":
            chair = conf.getChairmanText()
        else:
            for c in conf.getChairList():
                chair += c.getFullName() + "; "
        subject = "New %s in indico (%s)" % (type,conf.getId())
        if conf.getRoom() != None:
            room = conf.getRoom().getName()
        else:
            room = ""
        text = """
_Category_
%s
_Title_
%s
_Speaker/Chair_
%s
_Room_
%s
_Description_
%s
_Creator_
%s (%s)"""%(conf.getOwner().getTitle(), conf.getTitle(), chair, room, conf.getDescription(), conf.getCreator().getFullName(), conf.getCreator().getId())
        if len(confs) == 1:
            text += """
_Date_
%s -> %s
_Access_
%s""" % ( conf.getAdjustedStartDate(), conf.getAdjustedEndDate(), urlHandlers.UHConferenceDisplay.getURL(conf))
        else:
            i = 1
            for c in confs:
                text += """
_Date%s_
%s -> %s
_Access%s_
%s """ % (i,c.getAdjustedStartDate(), c.getAdjustedEndDate(), i,urlHandlers.UHConferenceDisplay.getURL(c))
                i+=1

        msg = ("Content-Type: text/plain; charset=\"utf-8\"\r\nFrom: %s\r\nReturn-Path: %s\r\nTo: %s\r\nCc: \r\nSubject: %s\r\n\r\n"%(fromAddr, fromAddr, addrs, subject))
        msg = msg + text
        maildata = { "fromAddr": fromAddr, "toList": addrs, "subject": subject, "body": text }
        GenericMailer.send(maildata)
        # Category notification
        if conf.getOwner().getNotifyCreationList() != "":
            addrs2 = [ conf.getOwner().getNotifyCreationList() ]
            maildata2 = { "fromAddr": fromAddr, "toList": addrs2, "subject": subject, "body": text }
            GenericMailer.send(maildata2)
Exemplo n.º 4
0
    def _getHTMLHeader( self ):
        from MaKaC.webinterface.pages.conferences import WPConfSignIn
        from MaKaC.webinterface.pages.signIn import WPSignIn
        from MaKaC.webinterface.pages.registrationForm import WPRegistrationFormSignIn
        from MaKaC.webinterface.rh.base import RHModificationBaseProtected
        from MaKaC.webinterface.rh.admins import RHAdminBase

        baseurl = self._getBaseURL()
        if ((isinstance(self, WPSignIn) or isinstance(self, WPConfSignIn) or isinstance(self, WPRegistrationFormSignIn)) and \
                Config.getInstance().getLoginURL().startswith("https")) or \
                self._rh._req.is_https() and self._rh._tohttps:
            baseurl = baseurl.replace("http://","https://")
            baseurl = urlHandlers.setSSLPort( baseurl )

        area=""
        if isinstance(self._rh, RHModificationBaseProtected):
            area=_(""" - _("Management area")""")
        elif isinstance(self._rh, RHAdminBase):
            area=_(""" - _("Administrator area")""")

        return wcomponents.WHTMLHeader().getHTML({
                            "area": area,
                            "baseurl": baseurl,
                            "conf": Config.getInstance(),
                            "page": self,
                            "extraCSSFiles": self._extraCSSFiles,
                            "extraCSS": self._extraCSS,
                            "extraJSFiles": self.getJSFiles(),
                            "extraJS": self._extraJS,
                            "language": self._getAW().getSession().getLang()
                            })
Exemplo n.º 5
0
def generate_public_auth_request(apiMode, apiKey, path, params= {}, persistent=False, https = True):
    from indico.web.http_api import API_MODE_KEY, API_MODE_ONLYKEY, API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED

    key = apiKey.getKey() if apiKey else None
    secret_key = apiKey.getSignKey() if apiKey else None
    if https:
        baseURL = Config.getInstance().getBaseSecureURL()
    else:
        baseURL = Config.getInstance().getBaseURL()
    publicRequestsURL = None
    authRequestURL = None
    if apiMode == API_MODE_KEY:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key) if key else None
    elif apiMode == API_MODE_ONLYKEY:
        authRequestURL = build_indico_request(path, params, key) if key else None
        params["onlypublic"] = "yes"
        publicRequestsURL = build_indico_request(path, params, key) if key else None
    elif apiMode == API_MODE_SIGNED:
        publicRequestsURL = build_indico_request(path, params)
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key and secret_key else None
    elif apiMode == API_MODE_ONLYKEY_SIGNED:
        publicRequestsURL = build_indico_request(path, params, key)  if key else None
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key and secret_key else None
    elif apiMode == API_MODE_ALL_SIGNED:
        authRequestURL = build_indico_request(path, params, key, secret_key, persistent)  if key else None
        params["onlypublic"] = "yes"
        publicRequestsURL = build_indico_request(path, params, key, secret_key, persistent)  if key else None
    return {"publicRequestURL": (baseURL + publicRequestsURL) if publicRequestsURL else "", "authRequestURL": (baseURL + authRequestURL) if authRequestURL else ""}
Exemplo n.º 6
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list(traceback.extract_tb(tb))
        text = (
            _(
                """
                    Offline website creation for the [event:%s] had caused
                    an error while running the task.

                    - Request from user: %s <%s>

                    - Details of the exception:
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """
            )
            % (self._conf.getId(), self._toUser.getFullName(), self._toUser.getEmail(), e, "\n".join(tracebackList))
        )
        maildata = {
            "fromAddr": Config.getInstance().getSupportEmail(),
            "toList": [Config.getInstance().getSupportEmail()],
            "subject": _("[Indico] Error in task: Offline website creation"),
            "body": text,
        }
        GenericMailer.send(GenericNotification(maildata))
Exemplo n.º 7
0
    def create(self):
        config = Config.getInstance()
        self._fileHandler = ZIPFileHandler()

        # create the home page html
        self._create_home()

        # Create main and static folders
        self._mainPath = "OfflineWebsite-%s" % self._normalize_path(self._conf.getTitle())
        self._fileHandler.addDir(self._mainPath)
        self._staticPath = os.path.join(self._mainPath, "static")
        self._fileHandler.addDir(self._staticPath)
        # Add i18n js
        self._addFolderFromSrc(
            os.path.join(self._staticPath, "js", "indico", "i18n"),
            os.path.join(config.getHtdocsDir(), "js", "indico", "i18n"),
        )
        # Add system icons (not referenced in HTML/CSS)
        for icon in Config.getInstance().getSystemIcons().itervalues():
            self._addFileFromSrc(
                os.path.join(self._staticPath, "images", icon), os.path.join(config.getHtdocsDir(), "images", icon)
            )
        # IE compat files (in conditional comments so BS doesn't see them)
        for path in ie_compatibility.urls():
            self._addFileFromSrc(
                os.path.join(self._staticPath, path.lstrip("/")), os.path.join(config.getHtdocsDir(), path.lstrip("/"))
            )

        # Getting all materials, static files (css, images, js and vars.js.tpl)
        self._getAllMaterial()
        self._html = self._get_static_files(self._html)

        # Specific changes
        self._create_other_pages()

        # Retrieve files that were not available in the file system (e.e. js/css from plugins)
        self._get_failed_paths()
        self._failed_paths = set()

        # Retrieve files referenced in CSS files
        self._get_css_refs()

        # A custom event CSS might reference an uploaded image so we need to check for failed paths again
        self._get_failed_paths()

        # Creating ConferenceDisplay.html file
        conferenceDisplayPath = os.path.join(self._mainPath, urlHandlers.UHConferenceDisplay.getStaticURL())
        self._fileHandler.addNewFile(conferenceDisplayPath, self._html)

        # Creating index.html file
        self._fileHandler.addNewFile(
            "index.html", '<meta http-equiv="Refresh" content="0; url=%s">' % conferenceDisplayPath
        )

        self._fileHandler.close()
        self._outputFile = self._generateZipFile(self._fileHandler.getPath())
        return self._outputFile
Exemplo n.º 8
0
def getReportNumberItems(obj):
    rns = obj.getReportNumberHolder().listReportNumbers()
    reportCodes = []

    for rn in rns:
        key = rn[0]
        if key in Config.getInstance().getReportNumberSystems().keys():
            number = rn[1]
            reportNumberId="s%sr%s"%(key, number)
            name = Config.getInstance().getReportNumberSystems()[key]["name"]
            reportCodes.append({"id" : reportNumberId, "number": number, "system": key, "name": name})
    return reportCodes
Exemplo n.º 9
0
 def getVars( self ):
     
     vars = wcomponents.WTemplated.getVars( self )
     vars["title"] = self._file.getName()
     vars["description"] = self._file.getDescription()
     vars["type"] = self._file.getFileType()
     vars["typeDesc"] = Config.getInstance().getFileTypeDescription( self._file.getFileType() )
     vars["downloadImg"] = Config.getInstance().getSystemIconURL("download")
     vars["fileName"] = self._file.getFileName()
     vars["fileSize"] = strfFileSize( self._file.getSize() )
     
     return vars
Exemplo n.º 10
0
def _fix_url_path(path):
    """Sanitizes an URL extracted from the HTML document"""
    if path.startswith("static/"):
        # It's a path that was prefixed with baseurl
        path = path[7:]
    elif path.startswith(Config.getInstance().getBaseURL()):
        path = path[len(Config.getInstance().getBaseURL()) :]
    elif path.startswith(Config.getInstance().getBaseSecureURL()):
        path = path[len(Config.getInstance().getBaseSecureURL()) :]
    path = path.lstrip("/")
    path = _remove_qs(path)
    return path
Exemplo n.º 11
0
 def getByLoginOrUPN(self, id):
     params = urllib.urlencode({'UserName': "******"%id})
     #headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
     cred = base64.encodestring("%s:%s"%(Config.getInstance().getNiceLogin(), Config.getInstance().getNicePassword()))[:-1]
     headers = {}
     headers["Content-type"] = "application/x-www-form-urlencoded"
     headers["Accept"] = "text/plain"
     headers["Authorization"] = "Basic %s"%cred
     conn = httplib.HTTPSConnection("winservices-soap.web.cern.ch")
     try:
         conn.request("POST", "/winservices-soap/generic/Authentication.asmx/GetUserInfoFromLogin", params, headers)
     except Exception, e:
         raise MaKaCError( _("Sorry, due to a temporary unavailability of the NICE service, we are unable to authenticate you. Please try later or use your local Indico account if you have one."))
Exemplo n.º 12
0
    def __init__( self, rh ):
        config = Config.getInstance()
        db_connected = DBMgr.getInstance().isConnected()

        self._rh = rh
        self._locTZ = ""

        self._asset_env = Environment(config.getHtdocsDir(), '')

        if db_connected:
            debug = HelperMaKaCInfo.getMaKaCInfoInstance().isDebugActive()
        else:
            debug = False

        # This is done in order to avoid the problem sending the error report because the DB is not connected.
        if db_connected:
            info = HelperMaKaCInfo.getMaKaCInfoInstance()
            self._asset_env.debug = info.isDebugActive()

        self._dir = config.getTPLDir()
        self._asset_env.debug = debug

        if db_connected:
            css_file = config.getCssStylesheetName()
        else:
            css_file = 'Default.css'

        # register existing assets
        assets.register_all_js(self._asset_env)
        assets.register_all_css(self._asset_env, css_file)

        #store page specific CSS and JS
        self._extraCSS = []
        self._extraJS = []
Exemplo n.º 13
0
    def _getAnswer(self):
        spkWrapper = None
        manager = Catalog.getIdx("cs_bookingmanager_conference").get(self._conf.getId())
        for sw in manager.getSpeakerWrapperList():
            if sw.getUniqueIdHash() == self.authKey:
                spkWrapper = sw

        if spkWrapper:
            spkWrapper.setStatus(SpeakerStatusEnum.SIGNED, request.remote_addr)
            spkWrapper.triggerNotification()
            if manager.notifyElectronicAgreementAnswer():
                subject = """[Indico] Electronic Agreement Accepted: '%s'""" % (self._conf.getTitle())
                content = _(self.MESSAGE_ACCEPT).format(
                    speaker=spkWrapper.getObject().getDirectFullName(),
                    title=self._conf.getTitle(),
                    url=self._conf.getURL(),
                )
                emailToList = [self._conf.getCreator().getEmail()]
                for event_manager in self._conf.getManagerList():
                    emailToList.append(event_manager.getEmail())
                notification = ElectronicAgreementOrganiserNotification(
                    emailToList, Config.getInstance().getNoReplyEmail(), content, subject
                )

                GenericMailer.sendAndLog(notification, self._conf, MODULE_NAME)
Exemplo n.º 14
0
    def OAuthCheckAccessResource(cls, req, query_string):
        from indico.modules.oauth.db import  ConsumerHolder, AccessTokenHolder, OAuthServer

        oauth_request = oauth.Request.from_request(req.get_method(),req.construct_url(req.get_uri()), headers=req.headers_in, query_string=urlencode(query_string))
        Logger.get('oauth.resource').info(oauth_request)
        try:
            now = time.time()
            consumer_key = oauth_request.get_parameter('oauth_consumer_key')
            if not ConsumerHolder().hasKey(consumer_key):
                raise OAuthError('Invalid Consumer Key' , apache.HTTP_UNAUTHORIZED)
            consumer = ConsumerHolder().getById(consumer_key)
            token = oauth_request.get_parameter('oauth_token')
            if not token or not AccessTokenHolder().hasKey(token):
                raise OAuthError('Invalid Token', apache.HTTP_UNAUTHORIZED)
            access_token = AccessTokenHolder().getById(token)
            oauth_consumer = oauth.Consumer(consumer.getId(), consumer.getSecret())
            OAuthServer.getInstance().verify_request(oauth_request, oauth_consumer, access_token.getToken())
            if access_token.getConsumer().getId() != oauth_consumer.key:
                raise OAuthError('Invalid Consumer Key' , apache.HTTP_UNAUTHORIZED)
            elif (now - access_token.getTimestamp()) > Config.getInstance().getOAuthAccessTokenTTL():
                raise OAuthError('Expired Token', apache.HTTP_UNAUTHORIZED)
            return access_token
        except oauth.Error, e:
            if e.message.startswith("Invalid Signature"):
                raise OAuthError("Invalid Signature", apache.HTTP_UNAUTHORIZED)
            else:
                raise OAuthError(e.message, apache.HTTP_BAD_REQUEST)
Exemplo n.º 15
0
def createCSV(resvs, req):

    results=[['URL',
             'id',
             'start date',
             'end date',
             'name',
             'site',
             'building',
             'floor',
             'roomNr',
             'IP',
             'H323 IP',
             'uses VC equipment'
             ]]

    for collision in resvs:
        resv = collision.withReservation
        if resv.usesAVC:
            usesAVC = 1
        else:
            usesAVC = 0
        results.append([str(UHRoomBookingBookingDetails.getURL(resv)),
                         str(resv.id),
                         collision.startDT.strftime("%Y-%m-%d %H:%M:%S"),
                         collision.endDT.strftime("%Y-%m-%d %H:%M:%S"),
                         resv.room.name or "",
                         resv.room.site,
                         str(resv.room.building),
                         resv.room.floor,
                         str(resv.room.roomNr),
                         resv.room.customAtts.get('IP') or "",
                         resv.room.customAtts.get('H323 IP') or "",
                         usesAVC
                         ])



    #################### create temp file ###################
    cfg = Config.getInstance()
    tempPath = cfg.getUploadedFilesTempDir()
    tempFileName = tempfile.mkstemp( prefix="Bookings", suffix=".csv", dir = tempPath )[1]

    #################### write the results in the temp file ###################
    fd=open(tempFileName, 'w')
    writer = csv.writer(fd, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for i in results:
        writer.writerow(i)
    fd.close()

    #################### return the CSV file ###################
    req.headers_out["Content-Length"] = "%s"%int(os.stat(tempFileName)[stat.ST_SIZE])
    mimetype = cfg.getFileTypeMimeType( cfg.getFileType("CSV") )
    req.content_type = """%s"""%(mimetype)
    req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%cleanHTMLHeaderFilename(os.path.basename(tempFileName))

    fr = open(tempFileName, "rb")
    data = fr.read()
    fr.close()
    return data
Exemplo n.º 16
0
def getCat(Cat, fid, icon):#checks if Category exists, creates if need be, then returns the Category to add Conference to
    if fid != '0': #If level is below root
        cursor = agenda.cursor()
        cursor.execute("select * from LEVEL where uid = \'" + fid + "\'")#gets parent LEVEL
        cp = cursor.fetchone()#gets parent info
        #cp[0]-uid, cp[1]-fid, cp[2]-level, cp[3]-title, cp[4]-cd, cp[5]-md, cp[6]-abstract, cp[7]-icon
        #cp[8]-stitle, cp[9]-visibility, cp[10]-modifyPassword, cp[11]-accessPassword, cp[12]-categorder
        if cp[1] == "delet":
            return None
        newCat = conference.Category()#creates Category with parents properties
        newCat.setName(cp[3])
        newCat.setDescription(cp[6])
        newCat.setOrder(cp[12])
        newCat.setVisibility(cp[9])
        newCat.setId(cp[0])
        catParent = getCat(newCat, cp[1], cp[7])#goes to fetch the parent category
    else:#If at root level get the root category
        catParent = conference.CategoryManager().getRoot()
    catlist = catParent.getSubCategoryList()#get list of subcategories already in category
    for tup in catlist:#checks if the category already exists and returns it
        if tup.name == Cat.name and tup.id == Cat.id:
            return tup
    #if category doesn't exist - create it
    catParent.newSubCategory(Cat)
    if icon != "":
        iconpath = Config.getInstance().getCategoryIconPath(Cat.getId())
        os.system("scp tbaron@%s:%s/%s.gif /tmp/%s.gif" % (file_host,hosticonpath,Cat.getId(),Cat.getId()))
        os.system("convert /tmp/%s.gif %s" % (Cat.getId(),iconpath))
    #get_transaction().commit()
    return Cat
Exemplo n.º 17
0
    def _getHTMLHeader( self ):
        from MaKaC.webinterface.pages.conferences import WPConfSignIn
        from MaKaC.webinterface.pages.signIn import WPSignIn
        from MaKaC.webinterface.pages.registrationForm import WPRegistrationFormSignIn
        from MaKaC.webinterface.rh.base import RHModificationBaseProtected
        from MaKaC.webinterface.rh.admins import RHAdminBase

        area=""
        if isinstance(self._rh, RHModificationBaseProtected):
            area=i18nformat(""" - _("Management area")""")
        elif isinstance(self._rh, RHAdminBase):
            area=i18nformat(""" - _("Administrator area")""")

        info = HelperMaKaCInfo().getMaKaCInfoInstance()
        websession = self._getAW().getSession()
        if websession:
            language = websession.getLang()
        else:
            language = info.getLang()

        return wcomponents.WHTMLHeader().getHTML({
            "area": area,
            "baseurl": self._getBaseURL(),
            "conf": Config.getInstance(),
            "page": self,
            "extraCSS": self.getCSSFiles(),
            "extraJSFiles": self.getJSFiles(),
            "extraJS": self._extraJS,
            "language": language,
            "social": info.getSocialAppConfig()
            })
Exemplo n.º 18
0
 def getFromAddr(self):
     # TODO: There will be on "from address" from a conference, but what if there are more different conferences
     supEmail = self._psList[0].getConference().getSupportInfo().getEmail(returnNoReply=True)
     if self._forceIndicoFromAddress or supEmail.strip()=="":
         info = HelperMaKaCInfo.getMaKaCInfoInstance()
         return "%s <%s>"%(info.getTitle(), Config.getInstance().getSupportEmail())
     return supEmail
Exemplo n.º 19
0
def _define_lookup():
    return IndicoTemplateLookup(directories=[TEMPLATE_DIR],
                                module_directory=os.path.join(Config.getInstance().getTempDir(), "mako_modules"),
                                disable_unicode=True,
                                filesystem_checks=True,
                                imports=FILTER_IMPORTS,
                                cache_enabled=not ContextManager.get('offlineMode'))
Exemplo n.º 20
0
    def OAuthCheckAccessResource(cls):
        from indico.modules.oauth.db import ConsumerHolder, AccessTokenHolder, OAuthServer

        oauth_request = oauth.Request.from_request(request.method, request.base_url, request.headers,
                                                   parameters=create_flat_args())
        Logger.get('oauth.resource').info(oauth_request)
        try:
            now = nowutc()
            consumer_key = oauth_request.get_parameter('oauth_consumer_key')
            if not ConsumerHolder().hasKey(consumer_key):
                raise OAuthError('Invalid Consumer Key', apache.HTTP_UNAUTHORIZED)
            consumer = ConsumerHolder().getById(consumer_key)
            token = oauth_request.get_parameter('oauth_token')
            if not token or not AccessTokenHolder().hasKey(token):
                raise OAuthError('Invalid Token', 401)
            access_token = AccessTokenHolder().getById(token)
            oauth_consumer = oauth.Consumer(consumer.getId(), consumer.getSecret())
            OAuthServer.getInstance().verify_request(oauth_request, oauth_consumer, access_token.getToken())
            if access_token.getConsumer().getId() != oauth_consumer.key:
                raise OAuthError('Invalid Consumer Key', apache.HTTP_UNAUTHORIZED)
            elif (now - access_token.getTimestamp()) > timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL()):
                raise OAuthError('Expired Token', apache.HTTP_UNAUTHORIZED)
            return access_token
        except oauth.Error, e:
            if e.message.startswith("Invalid Signature"):
                raise OAuthError("Invalid Signature", 401)
            else:
                raise OAuthError(e.message, 400)
Exemplo n.º 21
0
    def _getItem( self, categ, level=0 ):
        if not categ.canView( self._aw ):
            return ""
        html = ""
        number=self._number.newCount()
        for i in range(level):
            html = "%s&nbsp;&nbsp;&nbsp;"%html
        cfg = Config.getInstance()
        checked = ""

        if categ in self._selCategs:
            checked = "checked"
        title = """<input type="checkbox" name="selCateg" id="%s" onClick="alerta(%s);" value="%s" %s> %s"""%\
                    (number,number,categ.getId(), checked, categ.getName() )
        if categ in self._expandedCategs:
            temp = copy( self._expandedCategs )
            temp.remove( categ )
            html = """%s<a href="%s"><img src="%s" border="0" alt="fold"></a> %s"""%\
                (   html, \
                    self._expandURLGen( temp ), \
                    cfg.getSystemIconURL("itemExploded"), \
                    title )
            for subcat in categ.getSubCategoryList():
                html = "%s<br>%s"%(html, self._getItem(subcat, level+1) )
        else:
            html = """%s<a href="%s"><img src="%s" border="0" alt="unfold"></a> %s"""%\
                (   html, \
                    self._expandURLGen( self._expandedCategs+[categ] ), \
                    cfg.getSystemIconURL("itemCollapsed"), \
                    title )
        return html
Exemplo n.º 22
0
 def _process( self ):
     from MaKaC.common.Configuration import Config
     from MaKaC.externUsers import ExtUserHolder
     from urllib import urlencode
     euh = ExtUserHolder()
     ah = user.AvatarHolder()
     newIdentityList = []
     for id in self._identityList:
         newId = id
         for authId in Config.getInstance().getAuthenticatorList():
             if id[:len(authId)] == authId:
                 dict = euh.getById(authId).getById(id.split(':')[1])
                 av = user.Avatar(dict)
                 newId = ah.add(av)
                 identity = dict["identity"](dict["login"], av)
                 try:
                     dict["authenticator"].add(identity)
                 except:
                     pass
                 av.activateAccount()
         newIdentityList.append("selectedPrincipals=%s"%newId)
     if self._addURL.find("?") != -1:
         targetURL = self._addURL + "&" + urlencode(self._params) + "&" + "&".join(newIdentityList)
     else:
         targetURL = self._addURL + "?" + urlencode(self._params) + "&" + "&".join(newIdentityList)
     self._redirect( targetURL )
Exemplo n.º 23
0
    def __init__(self, plugin_name, plugin_dir, url_path):
        config = Config.getInstance()
        output_dir = os.path.join(config.getHtdocsDir(), 'build', plugin_name)

        super(PluginEnvironment, self).__init__(output_dir, url_path)

        self.append_path(os.path.join(plugin_dir, 'htdocs'), url=url_path)
Exemplo n.º 24
0
    def __init__(self, booking):
        VidyoOwnerNotificationBase.__init__(self)
        self._owner = booking.getOwnerObject()

        self.setFromAddr("Indico Mailer <%s>" % Config.getInstance().getSupportEmail())
        self.setContentType("text/html")

        owner = booking.getOwnerObject()
        event = booking.getConference()

        self.setToList([owner.getEmail()])

        self.setSubject("""[Indico] The Vidyo public room %s has been deleted""" % booking.getBookingParamByName("roomName") )

        self.setBody("""Dear %s%s,<br />
<br />
Please note that the Vidyo room named "%s" associated with the Indico event <a href="%s">%s</a>, of which you were the owner, has been deleted by a manager of this event.<br />
<br />
Thank you for using Vidyo and Indico<br />
"""%
                     (self._getOwnerTitleText(),
                      owner.getStraightFullName(),
                      booking.getBookingParamByName("roomName"),
                      urlHandlers.UHConferenceDisplay.getURL(event),
                      event.getTitle()))
Exemplo n.º 25
0
    def _getAnswer(self):
        spkWrapper = None
        manager = self._conf.getCSBookingManager()
        for sw in manager.getSpeakerWrapperList():
            if sw.getUniqueIdHash() == self.authKey:
                spkWrapper = sw

        if spkWrapper:
            spkWrapper.setStatus(SpeakerStatusEnum.REFUSED)
            spkWrapper.setRejectReason(self.reason)
            spkWrapper.triggerNotification()
            if manager.notifyElectronicAgreementAnswer():
                subject = """[Indico] Electronic Agreement Rejected: '%s'""" % (self._conf.getTitle())
                content = _(self.MESSAGE_REJECT).format(
                    speaker=spkWrapper.getObject().getDirectFullName(),
                    title=self._conf.getTitle(),
                    reason=self.reason,
                    url=self._conf.getURL())
                emailToList = [self._conf.getCreator().getEmail()]
                for event_manager in self._conf.getManagerList():
                    emailToList.append(event_manager.getEmail())
                notification = ElectronicAgreementOrganiserNotification(emailToList, Config.getInstance().getNoReplyEmail(), content, subject)

                GenericMailer.sendAndLog(notification, self._conf,
                                         MODULE_NAME)
Exemplo n.º 26
0
    def blockingRequestProcessed(roomBlocking):
        """
        Notifies (e-mails) blocking creator about approval/rejection of his
        blocking request for a room
        """

        emails = []
        # ---- Email creator and contact ----

        to = roomBlocking.block.createdByUser.getEmail()

        if roomBlocking.active == True:
            verb = 'ACCEPTED'
        else:
            verb = 'REJECTED'
        subject = "Room blocking %s" % verb
        wc = WTemplated('RoomBookingEmail_2BlockingCreatorRequestProcessed')
        text = wc.getHTML({
            'block': roomBlocking.block,
            'roomBlocking': roomBlocking,
            'verb': verb
        })
        fromAddr = Config.getInstance().getSupportEmail()
        mailData = {
            "fromAddr": fromAddr,
            "toList": [to],
            "subject": subject,
            "body": text
        }
        emails.append(mailData)
        return emails
Exemplo n.º 27
0
    def requestConfirmation(owner, block, roomBlockings):
        """
        Notifies (e-mails) room owner about blockings he has to approve.
        Expects only blockings for rooms owned by the specified owner
        """

        emails = []
        # ---- Email creator and contact ----

        to = owner.getEmail()

        subject = "Confirm room blockings"
        wc = WTemplated('RoomBookingEmail_2ResponsibleConfirmBlocking')
        text = wc.getHTML({
            'owner': owner,
            'block': block,
            'roomBlockings': roomBlockings
        })
        fromAddr = Config.getInstance().getNoReplyEmail()
        mailData = {
            "fromAddr": fromAddr,
            "toList": [to],
            "subject": subject,
            "body": text
        }
        emails.append(mailData)
        return emails
Exemplo n.º 28
0
 def getVars( self ):
     vars = wcomponents.WTemplated.getVars( self )
     vars["indicobaseurl"] = Config.getInstance().getBaseURL()
     url = vars["url"] = self._file.getURL()
     vars["download"] = ""
     if url.find("http://") != -1:
         vars["download"] = """<a href="%s">Download File</a>""" % url
     return vars
Exemplo n.º 29
0
 def __init__(self):
     (fh,name)=tempfile.mkstemp(prefix="Indico",dir=Config.getInstance().getTempDir())
     os.fdopen(fh).close()
     try:
         self._file=zipfile.ZipFile(name,"w", zipfile.ZIP_DEFLATED, allowZip64=True)
     except:
         self._file=zipfile.ZipFile(name,"w", allowZip64=True)
     self._name=name
Exemplo n.º 30
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars( self )
        vars["duration"] =(datetime(1900,1,1)+self._subContrib.getDuration()).strftime("%H:%M")
        vars["SubContrib"] = self._subContrib
        vars["accessWrapper"] = self._aw
        vars["reportNumberSystems"] = Config.getInstance().getReportNumberSystems()

        return vars
Exemplo n.º 31
0
 def getById(self, id):
     params = urllib.urlencode({'DisplayName': "%s" % id})
     #headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
     cred = base64.encodestring(
         "%s:%s" % (Config.getInstance().getNiceLogin(),
                    Config.getInstance().getNicePassword()))[:-1]
     headers = {}
     headers["Content-type"] = "application/x-www-form-urlencoded"
     headers["Accept"] = "text/plain"
     headers["Authorization"] = "Basic %s" % cred
     conn = httplib.HTTPSConnection("winservices-soap.web.cern.ch")
     try:
         conn.request(
             "POST",
             "/winservices-soap/generic/Authentication.asmx/ListUsers",
             params, headers)
     except Exception, e:
         raise MaKaCError(
             _("Sorry, due to a temporary unavailability of the NICE service, we are unable to authenticate you. Please try later or use your local Indico account if you have one."
               ))
Exemplo n.º 32
0
def contextHelp(helpId):
    """
    Allows you to put [?], the context help marker.
    Help content is defined in <div id="helpId"></div>.
    """
    from MaKaC.webinterface.wcomponents import WTemplated
    params = {
        "helpId": helpId,
        "imgSrc": Config.getInstance().getSystemIconURL("help")
    }
    return WTemplated('ContextHelp').getHTML(params)
Exemplo n.º 33
0
def inlineContextHelp(helpContent):
    """
    Allows you to put [?], the context help marker.
    Help content passed as argument helpContent.
    """
    from MaKaC.webinterface.wcomponents import WTemplated
    params = {
        "helpContent": helpContent,
        "imgSrc": Config.getInstance().getSystemIconURL("help")
    }
    return WTemplated('InlineContextHelp').getHTML(params)
Exemplo n.º 34
0
 def _getImagesList(self):
     imgFiles = {}
     systemIcons = Config.getInstance().getSystemIcons()
     for icon in systemIcons.keys():
         imgFiles[icon] = "./images/%s" % systemIcons[icon]
     logo = self._conf.getLogo()
     imgFiles["logo"] = ""
     if logo is not None:
         logoName = "logo.%s" % self._getFileExtension(logo.getFileName())
         imgFiles["logo"] = "./images/%s" % logoName
     return imgFiles
Exemplo n.º 35
0
    def __init__(self, args):
        super(SchedulerApp, self).__init__()
        self.args = args
        config = Config.getInstance()
        worker = config.getWorkerName()
        self.mailer = SMTPHandler(config.getSmtpServer(),
                                  'scheduler@%s' % worker,
                                  config.getSupportEmail(),
                                  "[indico_scheduler] Problem at %s" % worker)

        self.mailer.setLevel(logging.ERROR)
Exemplo n.º 36
0
 def _doGetPhotoId( self, force = False ):
     photoId = "%s-%s-%s-%s" % ( str( self._getSafeLocationName() ), str( self.building ).strip(), str( self.floor ).strip(), str( self.roomNr ).strip() )
     
     filePath = Config.getInstance().getRoomPhotosDir()
     fileName = photoId + ".jpg"
     fullPath = os.path.join( filePath, fileName )
     from os.path import exists
     if exists( fullPath ) or force:
         return photoId
     else:
         return None
Exemplo n.º 37
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     vars["conversion"] = ""
     if Config.getInstance().hasFileConverter():
         vars["conversion"] = _("""
                             <tr>
                                 <td nowrap class="titleCellTD"><span class="titleCellFormat"> _("To PDF")</span></td>
                                 <td align="left"><input type="checkbox" name="topdf" checked="checked"> _("Automatic conversion to pdf (when applicable)? (PPT, DOC)")</td>
                             </tr>
                             """)
     return vars
Exemplo n.º 38
0
 def _processData(self):
     filename = "%s - Event.ics" % self._target.getName().replace("/", "")
     data = ""
     data += CategoryToiCal(self._target).getBody()
     self._req.headers_out["Content-Length"] = "%s" % len(data)
     cfg = Config.getInstance()
     mimetype = cfg.getFileTypeMimeType("ICAL")
     self._req.content_type = """%s""" % (mimetype)
     self._req.headers_out[
         "Content-Disposition"] = """inline; filename="%s\"""" % filename
     return data
Exemplo n.º 39
0
    def __init__(self, booking):
        GenericNotification.__init__(self)
        self._booking = booking
        self._bp = booking.getBookingParams()
        self._conference = booking.getConference()
        self._isLecture = self._conference.getType() == 'simple_event'

        self._modifLink = str(booking.getModificationURL())

        self.setFromAddr("Indico Mailer<%s>"%Config.getInstance().getSupportEmail())
        self.setContentType("text/html")
Exemplo n.º 40
0
 def _publicFile(self, path):
     filename=os.path.basename(path)
     if self._fileHandler is not None and \
             isinstance(self._fileHandler, ZIPFileHandler) and \
             not filename.lower().endswith(".zip"):
         filename="%s.zip"%filename
     try:
         shutil.copyfile(path, os.path.join(Config.getInstance().getPublicDir(), filename))
     except:
         raise MaKaCError( _("It is not possible to copy the offline website's zip file in the folder \"results\" to publish the file. \
                 Please contact with the system administrator"))
     return filename
Exemplo n.º 41
0
 def _checkParams(self):
     """ Checks for external authenticators
         For now the underlying MaKaC.common.search code only supports
         1 external authenticator, so we just see if a proper external authenticator is present or not
     """
     self._searchExt = False
     config = Config.getInstance()
     for authenticatorName in config.getAuthenticatorList():
         authParamName = "searchExternal-" + authenticatorName
         if authParamName in self._params and self._params[authParamName]:
             self._searchExt = True
             break
Exemplo n.º 42
0
def displayRSSList(res, req, tz):
    ch = ConferenceHolder()
    rss = xmlGen.XMLGen()
    rss.openTag('rss version="2.0"')
    rss.openTag("channel")
    rss.writeTag("title", "Indico RSS Feed")
    rss.writeTag("link", Config.getInstance().getBaseURL())
    rss.writeTag("description", "Export of some events stored in Indico")
    rss.writeTag("language", "en")
    rss.writeTag("pubDate", nowutc().strftime("%a, %d %b %Y %H:%M:%S %Z"))
    rss.writeTag("category", "")
    rss.writeTag("generator",
                 "CDS Indico %s" % Config.getInstance().getVersion())
    rss.writeTag("webMaster",
                 HelperMaKaCInfo.getMaKaCInfoInstance().getSupportEmail())
    rss.writeTag("ttl", "1440")
    for confId in res:
        c = ch.getById(confId)
        rss = displayRSSConf(c, rss, tz)
    rss.closeTag("channel")
    rss.closeTag("rss")
    return rss.getXml()
Exemplo n.º 43
0
    def __init__(self, booking):
        GenericNotification.__init__(self)

        self._booking = booking
        self._bp = booking._bookingParams
        self._conference = booking.getConference()

        self._modifLink = str(self._booking.getModificationURL())

        self.setFromAddr("Indico Mailer <%s>" %
                         Config.getInstance().getSupportEmail())
        self.setToList(MailTools.getAdminEmailList())
        self.setContentType("text/html")
Exemplo n.º 44
0
    def _sendErrorEmail(self, e):
        ty, ex, tb = sys.exc_info()
        tracebackList = traceback.format_list( traceback.extract_tb( tb ) )
        text = _("""
                    Offline website creation for the [event:%s] had caused
                    an error while running the task.

                    - Request from user: %s <%s>

                    - Details of the exception:
                        %s

                    - Traceback:

                        %s

                    --

                    <Indico support> indico-project @ cern.ch
                    """)%(self._conf.getId(), self._toUser.getFullName(), self._toUser.getEmail(), e, "\n".join( tracebackList ))
        maildata = { "fromAddr": Config.getInstance().getSupportEmail(), "toList": [Config.getInstance().getSupportEmail()], "subject": _("[Indico] Error in task: Offline website creation"), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Exemplo n.º 45
0
    def addPendingParticipant(self, participant):
        if participant.getConference().getId() != self._conference.getId():
            return False
        if participant.getId() is not None:
            return False
        if self.alreadyParticipating(participant) != 0:
            return False
        if self.isAutoAccept():
            self.addParticipant(participant)
        else:
            self._pendingParticipantList["%d" %
                                         self._newPendingId()] = participant

            logData = participant.getParticipantData()
            logData["subject"] = _(
                "New pending participant : %s") % participant.getWholeName()
            self._conference.getLogHandler().logAction(
                logData, log.ModuleNames.PARTICIPANTS)

            participant.setStatusPending()

            profileURL = urlHandlers.UHConfModifParticipantsPending.getURL(
                self._conference)

            toList = []
            creator = self._conference.getCreator()
            if isinstance(creator, Avatar):
                toList.append(creator.getEmail())
            for manager in self._conference.getAccessController(
            ).getModifierList():
                if isinstance(manager, Avatar):
                    toList.append(manager.getEmail())

            data = {}
            data["toList"] = toList
            data["fromAddr"] = Config.getInstance().getSupportEmail()
            data["subject"] = _("New pending participant for %s"
                                ) % self._conference.getTitle()
            data["body"] = """
            Dear Event Manager,

            a new person is asking for participation in %s.
            Personal profile of this pending participant is available at %s
            Please take this candidature into consideration and accept or reject it

            Your Indico
            """ % (self._conference.getTitle(), profileURL)

            GenericMailer.send(GenericNotification(data))
            self.notifyModification()
        return True
Exemplo n.º 46
0
def displayRSSConf(conf, rss, tz):
    date = str(conf.getAdjustedStartDate(tz).date().isoformat())
    time = str(conf.getAdjustedStartDate(tz).time().isoformat()[0:5])
    title = "%s - %s - %s" % (date, time, conf.getTitle())
    if Config.getInstance().getShortEventURL() != "":
        url = "%s%s" % (Config.getInstance().getShortEventURL(), conf.getId())
    else:
        url = urlHandlers.UHConferenceDisplay.getURL(conf)
    rss.openTag("item")
    rss.writeTag("title", title)
    rss.writeTag("link", url)
    if conf.isProtected():
        desc = getCategText(conf.getOwnerList()[0])
    else:
        desc = "%s<br>%s" % (getCategText(
            conf.getOwnerList()[0]), conf.getDescription())
    rss.writeTag("description", desc)
    rss.writeTag(
        "pubDate",
        conf.getModificationDate().strftime("%a, %d %b %Y %H:%M:%S %Z"))
    rss.writeTag("guid", url)
    rss.closeTag("item")
    return rss
Exemplo n.º 47
0
    def __init__(self):

        self.AuthenticatorList = []
        config = Config.getInstance()
        for auth in config.getAuthenticatorList():
            if auth == "Local":
                self.AuthenticatorList.append(LocalAuthenticator())
            if auth == "Nice":
                from MaKaC.authentication.NiceAuthentication import NiceAuthenticator
                self.AuthenticatorList.append(NiceAuthenticator())
            if auth == "LDAP":
                from MaKaC.authentication.LDAPAuthentication import LDAPAuthenticator
                self.AuthenticatorList.append(LDAPAuthenticator())
        self.create = True
Exemplo n.º 48
0
class ReviewingFactory(MaterialFactory):

    _id = "reviewing"
    _title = "Reviewing"
    _iconURL = Config.getInstance().getSystemIconURL("material")
    _materialKlasses = [conference.Reviewing]
    _needsCreationPage = False

    def get(owner):
        """returns the material"""
        if isinstance(owner, conference.Contribution):
            return owner.getReviewing()
        else:
            # we supposed that it is a Review object
            return owner.getMaterialById(0)

    get = staticmethod(get)

    def remove(owner):
        """performs the deletion of the paper from the owner"""
        owner.removeReviewing()

    remove = staticmethod(remove)

    def canAdd(target):
        #only one paper can be added to a contribution
        return target.getReviewing() == None

    canAdd = staticmethod(canAdd)

    def canDelete(target):
        #only a paper which is already set in a contribution can be deleted
        return target.getReviewing() != None

    canDelete = staticmethod(canDelete)

    def getModificationURL(cls, mat):
        """returns the URL for accessing to the modification view of the
            material"""
        return urlHandlers.UHMaterialModification.getURL(mat)

    getModificationURL = classmethod(getModificationURL)

    def create(cls, target):
        m = conference.Reviewing()
        m.setTitle(cls.getTitle())
        target.setReviewing(m)
        return m

    create = classmethod(create)
Exemplo n.º 49
0
 def _getAllImages(self, newImagesPath):
     # copy every images in resources/images
     imagesPath = Config.getInstance().getImagesDir()
     for img in os.listdir(imagesPath):
         if os.path.isfile(os.path.join(imagesPath, img)):
             newImgPath=os.path.join(newImagesPath, os.path.basename(img))
             file=open(os.path.join(imagesPath, os.path.basename(img)), "rb")
             self._fileHandler.addNewFile(newImgPath, file.read())
     # Logo
     logo = self._conf.getLogo()
     if logo is not None:
         logoName = "logo.%s"%self._getFileExtension(logo.getFileName())
         logoPath = os.path.join(newImagesPath, logoName)
         self._fileHandler.add(logoPath, logo.getFilePath())
Exemplo n.º 50
0
    def _sendEmail(self, ofu):
        text = _("""
                    Offline website creation for your event
                    was finished and you can recover the zip file from
                    the following URL:
                    <%s>

                    Thanks for using Indico

                    --
                    Indico
                    """)%ofu
        maildata = { "fromAddr": Config.getInstance().getSupportEmail(), "toList": [self._toUser.getEmail()], "subject": _("[Indico] Offline website creation done"), "body": text }
        GenericMailer.send(GenericNotification(maildata))
Exemplo n.º 51
0
    def _process( self ):

        hook = CategoryEventHook({'from': ['today']}, 'categ', {'idlist':self._target.getId(), 'dformat': 'atom'})
        res = hook(self.getAW(), self._req)
        resultFossil = {'results': res[0], 'url': str(self._uh.getURL(self._target))}

        serializer = Serializer.create('atom')
        data = serializer(resultFossil)

        cfg = Config.getInstance()
        mimetype = cfg.getFileTypeMimeType( "ATOM" )
        self._req.content_type = """%s"""%(mimetype)

        return data
Exemplo n.º 52
0
    def calculatePath(cls, filepath, local_path=None):
        config = Config.getInstance()

        # get compiled files from htdocs/build/{_min_dir}
        if '.min.' in filepath and cls._min_dir:
            local_path = os.path.join(config.getHtdocsDir(), 'build',
                                      cls._min_dir)
        else:
            local_path = local_path or cls._local_path

        f_abspath = os.path.abspath(os.path.join(local_path, filepath))
        if f_abspath.startswith(local_path):
            return f_abspath
        else:
            raise SERVER_RETURN, HTTP_NOT_FOUND
Exemplo n.º 53
0
def displayConf(conf, displayCateg, day, tz):
    if conf.getRoom() != None:
        room = conf.getRoom().getName()
    else:
        room = ""
    categText = getCategText(conf.getOwnerList()[0], displayCateg)
    if day:
        startTime = conf.calculateDayStartTime(day).time().isoformat()[0:5]
    else:
        startTime = conf.getAdjustedStartDate(tz).time().isoformat()[0:5]
    if Config.getInstance().getShortEventURL() != "":
        url = "%s%s" % (Config.getInstance().getShortEventURL(), conf.getId())
    else:
        url = urlHandlers.UHConferenceDisplay.getURL(conf)
    speakers = ""
    for chair in conf.getChairList():
        if speakers != "":
            speakers += ", "
        speakers += chair.getDirectFullName()
        if chair.getAffiliation() != "":
            speakers += " (%s)" % chair.getAffiliation()
    t = "<br><b>%s</b>%s&nbsp;/&nbsp;<a href=\"%s\">%s</a>/%s/%s" % (
        startTime, categText, url, conf.getTitle(), speakers, room)
    return t
Exemplo n.º 54
0
 def getVars(self):
     vars = wcomponents.WTemplated.getVars(self)
     conf = self._question.getEvaluation().getConference()
     #required
     if self._question.isRequired():
         vars["required"] = "* "
     else:
         vars["required"] = ""
     #questionValue, keyword, description, help
     vars["questionValue"] = self._question.getQuestionValue()
     vars["keyword"] = self._question.getKeyword()
     vars["description"] = self._question.getDescription()
     vars["help"] = self._question.getHelp()
     #question input
     vars["input"] = self._question.displayHtml(disabled="disabled")
     #actionUrl for change position + edit question
     url = urlHandlers.UHConfModifEvaluationEditPerformChanges.getURL(conf)
     url.addParam("mode", Question._EDIT)
     vars["actionUrl"] = url
     #change question position select
     posName = "posChange_%s" % (self._question.getPosition())
     nbQuestions = self._question.getEvaluation().getNbOfQuestions()
     questionPos = self._question.getPosition()
     vars["posChange"] = WUtils.createSelect(False,
                                             range(1, nbQuestions + 1),
                                             questionPos,
                                             name=posName,
                                             onchange="this.form.submit()")
     #actual position
     vars["actualPosition"] = self._question.getPosition()
     #modifiy question
     url = urlHandlers.UHConfModifEvaluationEdit.getURL(
         conf, mode=Question._EDIT, questionPos=questionPos)
     vars["editQuestion"] = WUtils.createImgButton(url, "edit", "edit")
     #remove question
     url = urlHandlers.UHConfModifEvaluationEditPerformChanges.getURL(
         conf, mode=Question._REMOVE, questionPos=questionPos)
     vars["removeQuestionUrl"] = url
     vars["removeQuestionConfirm"] = _(
         """javascript:return confirm( _("Are you sure you want to remove this question?"));"""
     )
     vars["removeQuestionInput"] = WUtils.createInput(
         type="image",
         name="remove",
         alt="remove",
         src=Config.getInstance().getSystemIconURL("remove"))
     #return
     return vars
Exemplo n.º 55
0
    def _setFakeConfig(self, custom):
        """
        Sets a fake configuration for the current process, using a temporary directory
        """
        config = Config.getInstance()
        test_config = TestConfig.getInstance()

        temp = tempfile.mkdtemp(prefix="indico_")
        self._info('Using %s as temporary dir' % temp)

        os.mkdir(os.path.join(temp, 'log'))
        os.mkdir(os.path.join(temp, 'archive'))

        indicoDist = pkg_resources.get_distribution('indico')
        htdocsDir = indicoDist.get_resource_filename('indico', 'indico/htdocs')
        etcDir = indicoDist.get_resource_filename('indico', 'etc')

        # minimal defaults
        defaults = {
            'BaseURL': 'http://localhost:8000/indico',
            'BaseSecureURL': '',
            'UseXSendFile': False,
            'AuthenticatorList': ['Local'],
            'SmtpServer': ('localhost', 58025),
            'SmtpUseTLS': 'no',
            'DBConnectionParams': ('localhost', TestConfig.getInstance().getFakeDBPort()),
            'LogDir': os.path.join(temp, 'log'),
            'XMLCacheDir': os.path.join(temp, 'cache'),
            'HtdocsDir': htdocsDir,
            'ArchiveDir': os.path.join(temp, 'archive'),
            'UploadedFilesTempDir': os.path.join(temp, 'tmp'),
            'ConfigurationDir': etcDir
            }

        defaults.update(custom)

        # set defaults
        config.reset(defaults)

        Config.setInstance(config)
        self._cfg = config

        # re-configure logging and template generator, so that paths are updated
        from MaKaC.common import TemplateExec
        from MaKaC.common.logger import Logger
        TemplateExec.mako = TemplateExec._define_lookup()
        Logger.reset()
Exemplo n.º 56
0
class VideoFactory(MaterialFactory):

    _id = "video"
    _title = "Video"
    _iconURL = Config.getInstance().getSystemIconURL("video")
    _creationWC = WVideoCreation
    _materialKlasses = [conference.Video]
    _needsCreationPage = False

    def get(owner):
        """returns the material"""
        return owner.getVideo()

    get = staticmethod(get)

    def remove(owner):
        """performs the deletion of the video from the owner"""
        owner.removeVideo()

    remove = staticmethod(remove)

    def canAdd(target):
        #only one video can be added to a contribution
        return target.getVideo() == None

    canAdd = staticmethod(canAdd)

    def canDelete(target):
        #only a video which is already set in a contribution can be deleted
        return target.getVideo() != None

    canDelete = staticmethod(canDelete)

    def getModificationURL(cls, mat):
        """returns the URL for accessing to the modification view of the 
            material"""
        return urlHandlers.UHMaterialModification.getURL(mat)

    getModificationURL = classmethod(getModificationURL)

    def create(cls, target):
        m = conference.Video()
        m.setTitle(cls.getTitle())
        target.setVideo(m)
        return m

    create = classmethod(create)
Exemplo n.º 57
0
    def _process( self ):
        filename = "%s-Categ.ics"%self._target.getName().replace("/","")

        hook = CategoryEventHook({}, 'categ', {'idlist':self._target.getId(), 'dformat': 'ics'})
        res = hook(self.getAW(), self._req)
        resultFossil = {'results': res[0]}

        serializer = Serializer.create('ics')
        data = serializer(resultFossil)

        self._req.headers_out["Content-Length"] = "%s"%len(data)
        cfg = Config.getInstance()
        mimetype = cfg.getFileTypeMimeType( "ICAL" )
        self._req.content_type = """%s"""%(mimetype)
        self._req.headers_out["Content-Disposition"] = """inline; filename="%s\""""%cleanHTMLHeaderFilename(filename)

        return data
Exemplo n.º 58
0
    def getVars(self):
        vars = wcomponents.WTemplated.getVars(self)

        vars["name"] = self._target.getName()
        vars["img"] = Config.getInstance().getSystemIconURL("category")
        vars["description"] = "&nbsp;"
        vars["conferenceList"] = urlHandlers.UHCategoryDisplay.getURL(
            self._target)
        vars["taskList"] = urlHandlers.UHTaskList.getURL(self._target)
        vars["taskCommentTitle"] = vars.get("taskCommentTitle",
                                            _("Task Comment Details"))
        vars["taskDetailsAction"] = vars.get("taskDetailsAction", "")

        mgrs = []
        from MaKaC.user import Avatar
        for mgr in self._target.getManagerList():
            if isinstance(mgr, Avatar):
                mgrs.append(mgr.getAbrName())
        vars["managers"] = ""
        if mgrs != []:
            vars["managers"] = _(
                """(<b> _("Managers")</b>: %s)""") % "; ".join(mgrs)

        taskObject = self._target.getTask(vars["taskId"])
        vars["taskTitle"] = taskObject.getTitle()
        vars["taskStatus"] = taskObject.getCurrentStatus().getStatusName()
        vars["taskDescription"] = taskObject.getDescription()
        vars["createdBy"] = taskObject.getCreatedBy().getFullName()
        vars["creatorId"] = taskObject.getCreatedBy().getId()

        responsibleList = []
        for r in taskObject.getResponsibleList():
            responsibleList.append(r.getFullName())
        vars["responsibleList"] = ", ".join(responsibleList)

        commentedBy = ""
        commentText = ""
        if vars.get("commentKey", None) is not None:
            commentBy = taskObject.getCommentHistry()[
                vars["commentKey"]].getCommentAuthor().getFullName()
            commentText = taskObject.getCommentHistry()[
                vars["commentKey"]].getCommentText()
        vars["commentedBy"] = vars.get("commentedBy", commentedBy)
        vars["commentText"] = vars.get("commentText", commentText)

        return vars
Exemplo n.º 59
0
    def __init__(self, booking):
        VidyoOwnerNotificationBase.__init__(self)
        self._booking = booking
        self._owner = booking.getOwnerObject()

        self.setFromAddr("Indico Mailer <%s>" %
                         Config.getInstance().getSupportEmail())
        self.setContentType("text/html")

        event = booking.getConference()

        self.setToList([self._owner.getEmail()])

        self.setSubject(
            """[Indico] You are the owner of a Vidyo public room attached to the event: %s"""
            % event.getTitle())

        self.setBody("""Dear %s%s,<br />
<br />
A new Vidyo room was created in <a href="%s">Indico</a> for the event <a href="%s">%s</a>.<br />
You have been chosen as Owner of this Vidyo public room.<br />
<br />
This means you can manage the room through the Vidyo Desktop application and you will be able to:<br />
 - Invite other users to the room,<br />
 - Lock or unlock the room,<br />
 - Fix a maximum number of attendees,<br />
 - Expel people out of the room,<br />
 - and other similar actions.<br />
<br />
You will not be able, however, to remove or modify the room from Indico, unless you also have management rights for the event.<br />
<br />
<a href="%s">Click here</a> to join the Vidyo room.<br />
<br />
Name of the room: %s<br />
Extension: %s<br />
PIN: %s<br />
Description: %s<br />
<br />
Thank you for using our system.<br />
""" % (self._getOwnerTitleText(), self._owner.getStraightFullName(),
        MailTools.getServerName(),
        urlHandlers.UHConferenceDisplay.getURL(event), event.getTitle(),
        booking.getURL(), booking.getBookingParamByName("roomName"),
        str(booking.getExtension()), self._getPinText(),
        booking.getBookingParamByName("roomDescription")))
Exemplo n.º 60
0
    def __init__(self, rh):
        config = Config.getInstance()
        self._rh = rh
        self._locTZ = ""

        self._asset_env = Environment(config.getHtdocsDir(), '/')

        # This is done in order to avoid the problem sending the error report because the DB is not connected.
        if DBMgr.getInstance().isConnected():
            info = HelperMaKaCInfo.getMaKaCInfoInstance()
            self._asset_env.debug = info.isDebugActive()

        # register existing assets
        assets.register_all_js(self._asset_env)

        #store page specific CSS and JS
        self._extraCSS = []
        self._extraJS = []