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)
def _checkCSRF(self): token = request.headers.get('X-CSRF-Token', request.form.get('csrf_token')) if self.CSRF_ENABLED and request.method != 'GET' and token != session.csrf_token: msg = _(u"It looks like there was a problem with your current session. Please use your browser's back " u"button, reload the page and try again.") raise BadRequest(msg) elif not self.CSRF_ENABLED and current_app.debug and request.method != 'GET': # Warn if CSRF is not enabled for a RH in new code module = self.__class__.__module__ if module.startswith('indico.modules.') or module.startswith('indico.core.'): msg = (u'{} request sent to {} which has no CSRF checks. Set `CSRF_ENABLED = True` in the class to ' u'enable them.').format(request.method, self.__class__.__name__) warnings.warn(msg, RuntimeWarning) # legacy csrf check (referer-based): # Check referer for POST requests. We do it here so we can properly use indico's error handling if Config.getInstance().getCSRFLevel() < 3 or request.method != 'POST': return referer = request.referrer # allow empty - otherwise we might lock out paranoid users blocking referers if not referer: return # valid http referer if referer.startswith(Config.getInstance().getBaseURL()): return # valid https referer - if https is enabled base_secure = Config.getInstance().getBaseSecureURL() if base_secure and referer.startswith(base_secure): return raise BadRefererError('This operation is not allowed from an external referer.')
def _prepare(self, check = True): # Date checks... if check: from MaKaC.conference import ConferenceHolder if not ConferenceHolder().hasKey(self.conf.getId()): self.getLogger().warning("Conference %s no longer exists! " "Deleting alarm." % self.conf.getId()) self.conf.removeAlarm(self) self.suicide() elif self.conf.getStartDate() <= self._getCurrentDateTime(): self.getLogger().warning("Conference %s already started. " "Deleting alarm." % self.conf.getId()) self.conf.removeAlarm(self) self.suicide() return False # Email startDateTime = format_datetime(self.conf.getAdjustedStartDate(), format="short") self.setUpSubject() try: locationText = self.conf.getLocation().getName() if self.conf.getLocation().getAddress() != "": locationText += ", %s" % self.conf.getLocation().getAddress() if self.conf.getRoom().getName() != "": locationText += " (%s)" % self.conf.getRoom().getName() except: locationText = "" if locationText != "": locationText = " %s: %s" % ( _("Location"), locationText) if self.getToAllParticipants() : if self.conf.getType() == "conference": for r in self.conf.getRegistrantsList(): self.addToUser(r) else: for p in self.conf.getParticipation().getParticipantList() : self.addToUser(p) from MaKaC.webinterface import urlHandlers if Config.getInstance().getShortEventURL() != "": url = "%s%s" % (Config.getInstance().getShortEventURL(),self.conf.getId()) else: url = urlHandlers.UHConferenceDisplay.getURL(self.conf) self.setText("""Hello, Please note that the event "%s" will start on %s (%s). %s You can access the full event here: %s Best Regards """ % (self.conf.getTitle(),\ startDateTime,\ self.conf.getTimezone(),\ locationText,\ url,\ )) self._setMailText() return True
def _process(self): flower_url = Config.getInstance().getFlowerURL() notset = object() overridden_tasks = Config.getInstance().getScheduledTaskOverride() tasks = [] for entry in celery.conf['CELERYBEAT_SCHEDULE'].values(): override = overridden_tasks.get(entry['task'], notset) custom_schedule = None disabled = False if override is notset: pass elif not override: disabled = True elif isinstance(override, dict): custom_schedule = override.get('schedule') else: custom_schedule = override tasks.append({'name': entry['task'], 'schedule': entry['schedule'], 'custom_schedule': custom_schedule, 'disabled': disabled}) tasks.sort(key=itemgetter('disabled', 'name')) return WPCelery.render_template('celery_tasks.html', flower_url=flower_url, tasks=tasks, timedelta=timedelta)
def _connect(self): """Connect to the CacheClient. This method must be called before accessing ``self._client``. """ # Maybe we already have a client in this instance if self._client is not None: return # If not, we might have one from another instance self._client = ContextManager.get('GenericCacheClient', None) if self._client is not None: return # If not, create a new one backend = Config.getInstance().getCacheBackend() if backend == 'memcached': self._client = MemcachedCacheClient(Config.getInstance().getMemcachedServers()) elif backend == 'redis': self._client = RedisCacheClient(Config.getInstance().getRedisCacheURL()) elif backend == 'files': self._client = FileCacheClient(Config.getInstance().getXMLCacheDir()) else: self._client = NullCacheClient() ContextManager.set('GenericCacheClient', self._client)
def _processUnexpectedError(self, e): """Unexpected errors""" self._responseUtil.redirect = None if Config.getInstance().getEmbeddedWebserver() or Config.getInstance().getPropagateAllExceptions(): raise return errors.WPUnexpectedError(self).display()
def pytest_configure(config): # Load all the plugins defined in pytest_plugins config.pluginmanager.consider_module(sys.modules[__name__]) config.indico_temp_dir = py.path.local(tempfile.mkdtemp(prefix='indicotesttmp.')) plugins = filter(None, [x.strip() for x in re.split(r'[\s,;]+', config.getini('indico_plugins'))]) # Throw away all indico.conf options early Config.getInstance().reset({ 'DBConnectionParams': ('localhost', 0), # invalid port - just so we never connect to a real ZODB! 'SmtpServer': ('localhost', 0), # invalid port - just in case so we NEVER send emails! 'CacheBackend': 'null', 'Loggers': [], 'UploadedFilesTempDir': config.indico_temp_dir.strpath, 'XMLCacheDir': config.indico_temp_dir.strpath, 'ArchiveDir': config.indico_temp_dir.strpath, 'StorageBackends': {'default': config.indico_temp_dir}, 'AttachmentStorage': 'default', 'Plugins': plugins, 'SecretKey': os.urandom(16) }) # Make sure we don't write any log files (or worse: send emails) Logger.reset() del logging.root.handlers[:] logging.root.addHandler(logging.NullHandler()) # Silence the annoying pycountry logger import pycountry.db pycountry.db.logger.addHandler(logging.NullHandler())
def run(self, template_name, **kwargs): template_dir = os.path.join(Config.getInstance().getTPLDir(), 'latex') template = tpl_render(os.path.join(template_dir, template_name), kwargs) self._dir = tempfile.mkdtemp(prefix="indico-texgen-", dir=Config.getInstance().getTempDir()) source_filename = os.path.join(self._dir, template_name + '.tex') target_filename = os.path.join(self._dir, template_name + '.pdf') log_filename = os.path.join(self._dir, 'output.log') log_file = open(log_filename, 'a+') with open(source_filename, 'w') as f: f.write(template) try: self.run_latex(source_filename, log_file) if self.has_toc: self.run_latex(source_filename, log_file) finally: log_file.close() if not os.path.exists(target_filename): report_no = self._save_error_report(source_filename, log_filename) # something went terribly wrong, no LaTeX file was produced raise LaTeXRuntimeException(source_filename, log_filename, report_no, kwargs) return target_filename
def sanitizationCheck(target, params, accessWrapper, doNotSanitize=[]): # first make sure all params are utf-8 Sanitization._encodeUnicode(params) # then check the security level of data sent to the server # if no user logged in, then no html allowed if accessWrapper.getUser(): level = Config.getInstance().getSanitizationLevel() elif target and hasattr(target, "canModify") and target.canModify(accessWrapper): # not logged user, but use a modification key level = Config.getInstance().getSanitizationLevel() else: level = 0 if level not in range(4): level = 1 if level == 0: #Escape all HTML tags Sanitization._escapeHTML(params, doNotSanitize) elif level in [1, 2]: #level 1 or default: raise error if script or style detected #level 2: raise error if script but style accepted Sanitization._sanitize(params, level, doNotSanitize) elif level == 3: # Absolutely no checks return
def _send(msgData): server = smtplib.SMTP(*Config.getInstance().getSmtpServer()) if Config.getInstance().getSmtpUseTLS(): server.ehlo() (code, errormsg) = server.starttls() if code != 220: raise MaKaCError(_("Can't start secure connection to SMTP server: %d, %s") % (code, errormsg)) if Config.getInstance().getSmtpLogin(): login = Config.getInstance().getSmtpLogin() password = Config.getInstance().getSmtpPassword() (code, errormsg) = server.login(login, password) if code != 235: raise MaKaCError(_("Can't login on SMTP server: %d, %s") % (code, errormsg)) to_addrs = msgData["toList"] | msgData["ccList"] | msgData["bccList"] try: Logger.get("mail").info( "Sending email: To: {} / CC: {} / BCC: {}".format( ", ".join(msgData["toList"]) or "None", ", ".join(msgData["ccList"]) or "None", ", ".join(msgData["bccList"]) or "None", ) ) server.sendmail(msgData["fromAddr"], to_addrs, msgData["msg"]) except smtplib.SMTPRecipientsRefused as e: raise MaKaCError("Email address is not valid: {}".format(e.recipients)) finally: server.quit() Logger.get("mail").info("Mail sent to {}".format(", ".join(to_addrs)))
def __getAvailableTemplates(self): tplDir = Config.getInstance().getTPLDir() tplRE = re.compile('^([^\.]+)\.([^\.]+)\.tpl$') templates = {} fnames = os.listdir(tplDir); for fname in fnames: m = tplRE.match(fname) if m: templates[m.group(2)] = None tplRE = re.compile('^([^\.]+)\.([^\.]+)\.wohl$') fnames = os.listdir(os.path.join(tplDir, 'chelp')) for fname in fnames: m = tplRE.match(fname) if m: templates[m.group(2)] = None cssRE = re.compile('Default.([^\.]+)\.css$') fnames = os.listdir(Config.getInstance().getCssDir()) for fname in fnames: m = cssRE.match(fname) if m: templates[m.group(1)] = None return templates.keys()
def deleted(self, obj, oldOwner): print "****DELETING OBJ=",obj, oldOwner objClass = type(oldOwner).__name__ objClassTitle = oldOwner.getTitle().lower() if objClass == 'Poster': objType = obj.getFileType().lower() objName = obj.getFileName().lower() if objName.find('poster') > -1 and objType == 'pdf' and objName.find('list_of_poster') == -1 and objName.find('session') == -1: # If POSTER is present, remove it tempDir = Config.getInstance().getSharedTempDir() postersDir = tempDir+"/posters" if os.path.isdir(postersDir): confId = str(oldOwner.owner.getId()) thumbPath = postersDir + "/poster_" + confId if os.path.isfile(thumbPath): os.remove(thumbPath) else: if (objClassTitle.find('photo') > -1 or objClassTitle.find('picture') > -1 or objClassTitle.find('group') > -1): objType = obj.getFileType().lower() objName = obj.getFileName().lower() if (objType == 'jpg'): # If Group Photo is present, remove it tempDir = Config.getInstance().getSharedTempDir() photoDir = tempDir+"/photos" if os.path.isdir(photoDir): confId = str(oldOwner.owner.getId()) thumbPath = photoDir + "/photo_" + confId + "_" + objName if os.path.isfile(thumbPath): os.remove(thumbPath) return
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)
def _sendReport( self ): cfg = Config.getInstance() # if no e-mail address was specified, # add a default one if self._userMail: fromAddr = self._userMail else: fromAddr = '*****@*****.**' toAddr = Config.getInstance().getSupportEmail() Logger.get('errorReport').debug('mailing %s' % toAddr) subject = "[Indico@%s] Error report"%cfg.getBaseURL() request_info = self._requestInfo or '' if isinstance(request_info, (dict, list)): request_info = pformat(request_info) # build the message body body = [ "-" * 20, "Error details\n", self._code, self._message, "Inner error: " + str(self._inner), request_info, "-" * 20 ] maildata = {"fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body)} GenericMailer.send(GenericNotification(maildata))
def _getHTMLHeader( self ): from MaKaC.webinterface.rh.base import RHModificationBaseProtected from MaKaC.webinterface.rh.admins import RHAdminBase area="" if self.MANAGEMENT or isinstance(self._rh, RHModificationBaseProtected): area=i18nformat(""" - _("Management area")""") elif isinstance(self._rh, RHAdminBase): area=i18nformat(""" - _("Administrator area")""") plugin_css = values_from_signal(signals.plugin.inject_css.send(self.__class__), as_list=True, multi_value_types=list) plugin_js = values_from_signal(signals.plugin.inject_js.send(self.__class__), as_list=True, multi_value_types=list) return wcomponents.WHTMLHeader().getHTML({ "area": area, "baseurl": self._getBaseURL(), "conf": Config.getInstance(), "page": self, "printCSS": map(self._fix_path, self.getPrintCSSFiles()), "extraCSS": map(self._fix_path, self.getCSSFiles() + plugin_css + self.get_extra_css_files()), "extraJSFiles": map(self._fix_path, self.getJSFiles() + plugin_js), "language": session.lang or Config.getInstance().getDefaultLocale(), # XXX: Remove SOCIAL_ENABLED once this is moved out of ZODB "social": HelperMaKaCInfo().getMaKaCInfoInstance().getSocialAppConfig() if self.SOCIAL_ENABLED else {}, "assets": self._asset_env })
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 ""}
def _processUnexpectedError(self, e): """Unexpected errors""" if Config.getInstance().getEmbeddedWebserver() or Config.getInstance().getPropagateAllExceptions(): # Re-raise to get the nice werkzeug exception view raise return errors.WPUnexpectedError(self).display()
def set_best_lang(check_session=True): """ Get the best language/locale for the current user. This means that first the session will be checked, and then in the absence of an explicitly-set language, we will try to guess it from the browser settings and only after that fall back to the server's default. """ from indico.core.config import Config if not has_request_context(): return 'en_GB' if current_app.config['TESTING'] else Config.getInstance().getDefaultLocale() elif 'lang' in g: return g.lang elif check_session and session.lang is not None: return session.lang # try to use browser language preferred = [x.replace('-', '_') for x in request.accept_languages.values()] resolved_lang = negotiate_locale(preferred, list(get_all_locales()), aliases=LOCALE_ALIASES) if not resolved_lang: if current_app.config['TESTING']: return 'en_GB' # fall back to server default resolved_lang = Config.getInstance().getDefaultLocale() # As soon as we looked up a language, cache it during the request. # This will be returned when accessing `session.lang` since there's code # which reads the language from there and might fail (e.g. by returning # lazy strings) if it's not set. g.lang = resolved_lang return resolved_lang
def getVars( self ): vars = wcomponents.WTemplated.getVars( self ) vars["types"] = "<br>".join( self._getTypeFilterItemList() ) vars["status"] = "<br>".join( self._getStatusFilterItemList() ) vars["others"] = "<br>".join( self._getOthersFilterItemList() ) vars["accTypes"] = "<br>".join( self._getAccTypeFilterItemList() ) f = filters.SimpleFilter(self._filterCrit,self._sortingCrit) al = [] abstractsToPrint = [] self._checked = "" if vars["selectAll"]: self._checked = " checked" abstractList = f.apply( self._track.getAbstractList() ) for abstract in abstractList: al.append( self._getAbstractHTML( abstract ) ) abstractsToPrint.append("""<input type="hidden" name="abstracts" value="%s">"""%abstract.getId()) vars["filteredNumberAbstracts"] = str(len(abstractList)) vars["totalNumberAbstracts"] = str(len(self._track.getAbstractList())) if self._order == "up": al.reverse() vars["abstracts"] = "".join( al ) vars["abstractsToPrint"] = "\n".join(abstractsToPrint) sortingField = self._sortingCrit.getField() vars["currentSorting"] = "" for crit in ["type", "status", "number", "date", "rating"]: url = self._getURL() vars["%sImg" % crit] = "" url.addParam("sortBy", crit) if sortingField.getId() == crit: vars["currentSorting"] = '<input type="hidden" name="sortBy" value="%s">' % crit if self._order == "down": vars["%sImg" % crit] = """<img src="%s" alt="">"""%(Config.getInstance().getSystemIconURL("downArrow")) url.addParam("order","up") elif self._order == "up": vars["%sImg" % crit] = """<img src="%s" alt="">"""%(Config.getInstance().getSystemIconURL("upArrow")) url.addParam("order","down") vars["%sSortingURL" % crit] = str(url) url = urlHandlers.UHTrackModifAbstracts.getURL( self._track ) url.addParam("order", self._order) url.addParam("OK", "1") url.setSegment( "abstracts" ) vars["filterPostURL"]=quoteattr(str(url)) vars["accessAbstract"] = quoteattr(str(urlHandlers.UHTrackAbstractDirectAccess.getURL(self._track))) vars["allAbstractsURL"] = str(urlHandlers.UHConfAbstractManagment.getURL(self._conf)) l = [] for tpl in self._conf.getAbstractMgr().getNotificationTplList(): l.append("""<option value="%s">%s</option>"""%(tpl.getId(), tpl.getName())) vars["notifTpls"] = "\n".join(l) vars["actionURL"]=quoteattr(str(urlHandlers.UHAbstractsTrackManagerAction.getURL(self._track))) vars["selectURL"]=quoteattr(str(urlHandlers.UHTrackModifAbstracts.getURL(self._track))) vars["filterUsed"] = self._filterUsed vars["resetFiltersURL"] = str(urlHandlers.UHTrackModifAbstracts.getURL(self._track)) vars["pdfIconURL"] = quoteattr(str(Config.getInstance().getSystemIconURL("pdf"))) vars["canModify"] = self._canModify return vars
def generate_public_auth_request(apiKey, path, params=None): apiMode = api_settings.get('security_mode') if params is None: params = {} if apiKey: key = apiKey.token secret_key = apiKey.secret persistent = apiKey.is_persistent_allowed and api_settings.get('allow_persistent') else: key = secret_key = None persistent = False if api_settings.get('require_https'): baseURL = Config.getInstance().getBaseSecureURL() else: baseURL = Config.getInstance().getBaseURL() publicRequestsURL = None authRequestURL = None if apiMode == APIMode.KEY: publicRequestsURL = build_indico_request(path, params) authRequestURL = build_indico_request(path, params, key) if key else None elif apiMode == APIMode.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 == APIMode.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 == APIMode.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 == APIMode.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 ""}
def getVars( self ): from indico.web.http_api.util import generate_public_auth_request vars = WHeader.getVars( self ) vars["categurl"] = self._conf.as_event.category.url vars["conf"] = vars["target"] = self._conf vars["imgLogo"] = Config.getInstance().getSystemIconURL("miniLogo") vars["MaKaCHomeURL"] = self._conf.as_event.category.url # Default values to avoid NameError while executing the template styles = theme_settings.get_themes_for("conference") vars["viewoptions"] = [{'id': theme_id, 'name': data['title']} for theme_id, data in sorted(styles.viewitems(), key=lambda x: x[1]['title'])] vars["SelectedStyle"] = "" vars["pdfURL"] = "" vars["displayURL"] = str(urlHandlers.UHConferenceOtherViews.getURL(self._conf)) # Setting the buttons that will be displayed in the header menu vars["showFilterButton"] = False vars["showMoreButton"] = True vars["showExportToICal"] = True vars["showExportToPDF"] = False vars["showDLMaterial"] = True vars["showLayout"] = True vars["displayNavigationBar"] = layout_settings.get(self._conf, 'show_nav_bar') # This is basically the same WICalExportBase, but we need some extra # logic in order to have the detailed URLs apiMode = api_settings.get('security_mode') vars["icsIconURL"] = str(Config.getInstance().getSystemIconURL("ical_grey")) vars["apiMode"] = apiMode vars["signingEnabled"] = apiMode in {APIMode.SIGNED, APIMode.ONLYKEY_SIGNED, APIMode.ALL_SIGNED} vars["persistentAllowed"] = api_settings.get('allow_persistent') user = self._aw.getUser() apiKey = user.api_key if user else None topURLs = generate_public_auth_request(apiKey, '/export/event/%s.ics' % self._conf.getId()) urls = generate_public_auth_request(apiKey, '/export/event/%s.ics' % self._conf.getId(), {'detail': 'contributions'}) vars["requestURLs"] = { 'publicRequestURL': topURLs["publicRequestURL"], 'authRequestURL': topURLs["authRequestURL"], 'publicRequestDetailedURL': urls["publicRequestURL"], 'authRequestDetailedURL': urls["authRequestURL"] } vars["persistentUserEnabled"] = apiKey.is_persistent_allowed if apiKey else False vars["apiActive"] = apiKey is not None vars["userLogged"] = user is not None tpl = get_template_module('api/_messages.html') vars['apiKeyUserAgreement'] = tpl.get_ical_api_key_msg() vars['apiPersistentUserAgreement'] = tpl.get_ical_persistent_msg() return vars
def process(self): """ Processes the request, analyzing the parameters, and feeding them to the _getAnswer() method (implemented by derived classes) """ ContextManager.set('currentRH', self) self._checkParams() self._checkProtection() if self.CHECK_HTML: try: security.Sanitization.sanitizationCheck(self._target, self._params, self._aw, ['requestInfo']) except HtmlForbiddenTag as e: raise HTMLSecurityError('ERR-X0', 'HTML Security problem. {}'.format(e)) if self._doProcess: if Config.getInstance().getProfile(): import profile, pstats, random proffilename = os.path.join(Config.getInstance().getTempDir(), "service%s.prof" % random.random()) result = [None] profile.runctx("result[0] = self._getAnswer()", globals(), locals(), proffilename) answer = result[0] rep = Config.getInstance().getTempDir() stats = pstats.Stats(proffilename) stats.strip_dirs() stats.sort_stats('cumulative', 'time', 'calls') stats.dump_stats(os.path.join(rep, "IndicoServiceRequestProfile.log")) os.remove(proffilename) else: answer = self._getAnswer() self._deleteTempFiles() return answer
def _send(msgData): server=smtplib.SMTP(*Config.getInstance().getSmtpServer()) if Config.getInstance().getSmtpUseTLS(): server.ehlo() (code, errormsg) = server.starttls() if code != 220: raise MaKaCError( _("Can't start secure connection to SMTP server: %d, %s")%(code, errormsg)) if Config.getInstance().getSmtpLogin(): login = Config.getInstance().getSmtpLogin() password = Config.getInstance().getSmtpPassword() (code, errormsg) = server.login(login, password) if code != 235: raise MaKaCError( _("Can't login on SMTP server: %d, %s")%(code, errormsg)) to_addrs = msgData['toList'] | msgData['ccList'] | msgData['bccList'] try: Logger.get('mail').info('Sending email: To: {} / CC: {} / BCC: {}'.format( ', '.join(msgData['toList']) or 'None', ', '.join(msgData['ccList']) or 'None', ', '.join(msgData['bccList']) or 'None')) server.sendmail(msgData['fromAddr'], to_addrs, msgData['msg']) except smtplib.SMTPRecipientsRefused as e: raise MaKaCError('Email address is not valid: {}'.format(e.recipients)) finally: server.quit() Logger.get('mail').info('Mail sent to {}'.format(', '.join(to_addrs)))
def pytest_configure(config): # Load all the plugins defined in pytest_plugins config.pluginmanager.consider_module(sys.modules[__name__]) config.indico_temp_dir = py.path.local(tempfile.mkdtemp(prefix="indicotesttmp.")) plugins = filter(None, [x.strip() for x in re.split(r"[\s,;]+", config.getini("indico_plugins"))]) # Throw away all indico.conf options early Config.getInstance().reset( { "DBConnectionParams": ("localhost", 0), # invalid port - just so we never connect to a real ZODB! "SmtpServer": ("localhost", 0), # invalid port - just in case so we NEVER send emails! "CacheBackend": "null", "Loggers": [], "UploadedFilesTempDir": config.indico_temp_dir.strpath, "XMLCacheDir": config.indico_temp_dir.strpath, "ArchiveDir": config.indico_temp_dir.strpath, "StorageBackends": {"default": config.indico_temp_dir}, "AttachmentStorage": "default", "Plugins": plugins, "SecretKey": os.urandom(16), } ) # Make sure we don't write any log files (or worse: send emails) Logger.reset() del logging.root.handlers[:] logging.root.addHandler(logging.NullHandler()) # Silence the annoying pycountry logger import pycountry.db pycountry.db.logger.addHandler(logging.NullHandler())
def getVars(self): vars = wcomponents.WTemplated.getVars( self ) vars["logo"] = "" if self._conf.getLogo(): vars["logo"] = "<img src=\"%s\" alt=\"%s\" border=\"0\">"%(vars["logoURL"], self._conf.getTitle()) vars["confTitle"] = self._conf.getTitle() vars["displayURL"] = urlHandlers.UHConferenceDisplay.getURL(self._conf) vars["imgConferenceRoom"] = Config.getInstance().getSystemIconURL( "conferenceRoom" ) ################################# # Fermi timezone awareness # ################################# vars["confDateInterval"] = i18nformat("""_("from") %s _("to") %s""")%(format_date(self._conf.getStartDate(), format='long'), format_date(self._conf.getEndDate(), format='long')) if self._conf.getStartDate().strftime("%d%B%Y") == \ self._conf.getEndDate().strftime("%d%B%Y"): vars["confDateInterval"] = format_date(self._conf.getStartDate(), format='long') elif self._conf.getStartDate().month == self._conf.getEndDate().month: vars["confDateInterval"] = "%s-%s %s"%(self._conf.getStartDate().day, self._conf.getEndDate().day, format_date(self._conf.getStartDate(), format='MMMM yyyy')) ################################# # Fermi timezone awareness(end) # ################################# vars["body"] = self._body vars["confLocation"] = "" if self._conf.getLocationList(): vars["confLocation"] = self._conf.getLocationList()[0].getName() vars["supportEmail"] = "" if self._conf.getSupportInfo().hasEmail(): mailto = quoteattr("""mailto:%s?subject=%s"""%(self._conf.getSupportInfo().getEmail(), urllib.quote( self._conf.getTitle() ) )) vars["supportEmail"] = _("""<a href=%s class="confSupportEmail"><img src="%s" border="0" alt="email"> %s</a>""")%(mailto, Config.getInstance().getSystemIconURL("mail"), self._conf.getSupportInfo().getCaption()) format = displayMgr.ConfDisplayMgrRegistery().getDisplayMgr(self._conf).getFormat() vars["bgColorCode"] = format.getFormatOption("titleBgColor")["code"] vars["textColorCode"] = format.getFormatOption("titleTextColor")["code"] return vars
def _process_POST(self): if User.query.has_rows(): return redirect(url_for_index()) setup_form = BootstrapForm(request.form) if not setup_form.validate(): flash(_("Some fields are invalid. Please, correct them and submit the form again."), 'error') return redirect(url_for('bootstrap.index')) # Creating new user user = User() user.first_name = to_unicode(setup_form.first_name.data) user.last_name = to_unicode(setup_form.last_name.data) user.affiliation = to_unicode(setup_form.affiliation.data) user.email = to_unicode(setup_form.email.data) user.is_admin = True identity = Identity(provider='indico', identifier=setup_form.username.data, password=setup_form.password.data) user.identities.add(identity) db.session.add(user) db.session.flush() user.settings.set('timezone', Config.getInstance().getDefaultTimezone()) user.settings.set('lang', session.lang or Config.getInstance().getDefaultLocale()) login_user(user, identity) full_name = user.full_name # needed after the session closes transaction.commit() # Configuring server's settings minfo = HelperMaKaCInfo.getMaKaCInfoInstance() minfo.setOrganisation(setup_form.affiliation.data) message = get_template_module('bootstrap/flash_messages.html').bootstrap_success(name=full_name) flash(Markup(message), 'success') # Activate instance tracking if setup_form.enable_tracking.data: contact_name = setup_form.contact_name.data contact_email = setup_form.contact_email.data try: register_instance(contact_name, contact_email) except (HTTPError, ValueError) as err: message = get_template_module('bootstrap/flash_messages.html').community_error(err=err) category = 'error' except Timeout: message = get_template_module('bootstrap/flash_messages.html').community_timeout() category = 'error' except RequestException as exc: message = get_template_module('bootstrap/flash_messages.html').community_exception(exc=exc) category = 'error' else: message = get_template_module('bootstrap/flash_messages.html').community_success() category = 'success' flash(Markup(message), category) return redirect(url_for_index())
def _getAnswer(self): self._target.getReportNumberHolder().addReportNumber(self._reportNumberSystem, self._reportNumber) if self._reportNumberSystem in Config.getInstance().getReportNumberSystems().keys(): reportNumberId="s%sr%s"%(self._reportNumberSystem, self._reportNumber) name = Config.getInstance().getReportNumberSystems()[self._reportNumberSystem]["name"] return {"id":reportNumberId, "name":name , "system":self._reportNumberSystem, "number": self._reportNumber} else: return {}
def smtp(disallow_emails, smtpserver): """Wrapper for the `smtpserver` fixture which updates the Indico config and disables the SMTP autofail logic for that smtp server. """ old_smtp_server = Config.getInstance().getSmtpServer() Config.getInstance().update(SmtpServer=smtpserver.addr) disallow_emails.add(smtpserver.addr) # whitelist our smtp server yield smtpserver Config.getInstance().update(SmtpServer=old_smtp_server)
def __init__(self, plugin_name, plugin_dir, url_path): config = Config.getInstance() url_base_path = urlparse(config.getBaseURL()).path output_dir = os.path.join(config.getHtdocsDir(), 'static', 'assets', 'plugins', plugin_name) url = '{0}/static/assets/plugins/{1}'.format(url_base_path, url_path) super(PluginEnvironment, self).__init__(output_dir, url) self.debug = Config.getInstance().getDebug() self.append_path(os.path.join(plugin_dir, 'htdocs'), url=os.path.join(url_base_path, url_path))
def create(self, static_site_id): config = Config.getInstance() self._fileHandler = ZIPFileHandler() # create the home page html self._create_home() # Create main and static folders self._mainPath = self._normalize_path(u"OfflineWebsite-{}".format(self._conf.getTitle().decode("utf-8"))) 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() return self._save_file(self._fileHandler.getPath(), static_site_id)
def __init__(self, user, role, contribution): conference = contribution.event_new.as_legacy GenericNotification.__init__(self) self.setFromAddr("Indico <%s>" % Config.getInstance().getNoReplyEmail()) self.setToList([user.email]) self.setSubject("""An author has submitted a paper for "%s" """% conference.getTitle()) if role == 'Referee': url = url_for('event_mgmt.confListContribToJudge', conference, _external=True) elif role == 'Layout Reviewer': url = url_for('event_mgmt.confListContribToJudge-asEditor', conference, _external=True) elif role == 'Content Reviewer': url = url_for('event_mgmt.confListContribToJudge-asReviewer', conference, _external=True) self.setBody("""Dear %s, An author has submitted a paper entitled "%s" (id: %s) for the conference "%s". You can now start the reviewing process as a %s: %s Kind regards, Indico on behalf of "%s" """ % ( user.full_name, contribution.title, str(contribution.friendly_id), conference.getTitle(), role, url, conference.getTitle()))
def __init__(self, post_url=None, max_file_size=None, max_files=10, add_remove_links=True, accepted_file_types=None, param_name='file', submit_if_empty=True, submit_form=False, handle_flashes=False): super(DropzoneWidget, self).__init__('forms/dropzone_widget.html') config = Config.getInstance() if max_file_size is None: max_file_size = min(config.getMaxUploadFileSize() or 10240, config.getMaxUploadFilesTotalSize() or 10240) # in MB self.options = { 'url': post_url, 'uploadMultiple': max_files > 1, 'maxFilesize': max_file_size, 'maxFiles': max_files, 'addRemoveLinks': add_remove_links, 'acceptedFiles': accepted_file_types, 'paramName': param_name, 'submitForm': submit_form, 'submitIfEmpty': submit_if_empty, 'parallelUploads': max_files, 'handleFlashes': handle_flashes }
class TestMaterialRepository(IndicoTestCase): """ Tests the basic functionalities of the MaterialLocalRepository file repository. """ _requires = ["db.DummyUser"] def setUp(self): super(TestMaterialRepository, self).setUp() self._archivePath = os.path.join(os.getcwd(), "tmpArchive") #create a directory where the archive will be set up try: os.mkdir(self._archivePath) except OSError, e: #print e pass #the MaterialLocalRepository takes the repository base path from # the system configuration so we have to set it up to the new dir from indico.core.config import Config cfg = Config.getInstance() #we overrride the system repository path with the temp one cfg._archivePath = self._archivePath
def _setup(args): cfg = Config.getInstance() # logging setup handler = logging.handlers.TimedRotatingFileHandler( os.path.join(cfg.getLogDir(), 'scheduler.log'), 'midnight') handler.setFormatter( logging.Formatter( "%(asctime)s %(process)s %(name)s: %(levelname)-8s %(message)s")) if 'log' not in args.__dict__: args.log = 'INFO' level = getattr(logging, args.log) root_logger = logging.getLogger('') root_logger.addHandler(handler) root_logger.setLevel(level) mp_logger = multiprocessing.get_logger() mp_logger.setLevel(level) mp_logger.addHandler(handler)
def get_storage(backend_name): """Returns an FS object for the given backend. The backend must be defined in the StorageBackends dict in the indico config. Once a backend has been used it is assumed to stay there forever or at least as long as it is referenced somewhere. Each backend definition uses the ``name:data`` notation, e.g. ``fs:/some/folder/`` or ``foo:host=foo.host,token=secret``. """ try: definition = Config.getInstance().getStorageBackends()[backend_name] except KeyError: raise RuntimeError( 'Storage backend does not exist: {}'.format(backend_name)) name, data = definition.split(':', 1) try: backend = get_storage_backends()[name] except KeyError: raise RuntimeError('Storage backend {} has invalid type {}'.format( backend_name, name)) return backend(data)
def _getIcalExportParams(self, user, url, params=None): apiMode = api_settings.get('security_mode') apiKey = user.api_key if user else None urls = generate_public_auth_request(apiKey, url, params) tpl = get_template_module('api/_messages.html') return { 'currentUser': user, 'icsIconURL': str(Config.getInstance().getSystemIconURL("ical_grey")), 'apiMode': apiMode, 'signingEnabled': apiMode in {APIMode.SIGNED, APIMode.ONLYKEY_SIGNED, APIMode.ALL_SIGNED}, 'persistentAllowed': api_settings.get('allow_persistent'), 'requestURLs': urls, 'persistentUserEnabled': apiKey.is_persistent_allowed if apiKey else False, 'apiActive': apiKey is not None, 'userLogged': user is not None, 'apiKeyUserAgreement': tpl.get_ical_api_key_msg(), 'apiPersistentUserAgreement': tpl.get_ical_persistent_msg() }
def configure_multipass(app): cfg = Config.getInstance() app.config['MULTIPASS_AUTH_PROVIDERS'] = cfg.getAuthProviders() app.config['MULTIPASS_IDENTITY_PROVIDERS'] = cfg.getIdentityProviders() app.config['MULTIPASS_PROVIDER_MAP'] = cfg.getProviderMap() or { x: x for x in cfg.getAuthProviders() } if 'indico' in app.config[ 'MULTIPASS_AUTH_PROVIDERS'] or 'indico' in app.config[ 'MULTIPASS_IDENTITY_PROVIDERS']: raise ValueError( 'The name `indico` is reserved and cannot be used as an Auth/Identity provider name.' ) if cfg.getLocalIdentities(): configure_multipass_local(app) app.config['MULTIPASS_IDENTITY_INFO_KEYS'] = { 'first_name', 'last_name', 'email', 'affiliation', 'phone', 'address' } app.config['MULTIPASS_LOGIN_ENDPOINT'] = 'auth.login' app.config['MULTIPASS_LOGIN_URLS'] = None # registered in a blueprint app.config['MULTIPASS_SUCCESS_ENDPOINT'] = 'misc.index' app.config['MULTIPASS_FAILURE_MESSAGE'] = _(u'Login failed: {error}')
def _process(self): form = CephalopodForm(obj=FormDefaults( **cephalopod_settings.get_all())) if form.validate_on_submit(): return self._process_form(form) config = Config.getInstance() hub_url = url_join( config.getCommunityHubURL(), 'api/instance/{}'.format(cephalopod_settings.get('uuid'))) cephalopod_settings.set('show_migration_message', False) return WPCephalopod.render_template( 'cephalopod.html', 'cephalopod', affiliation=core_settings.get('site_organization'), enabled=cephalopod_settings.get('joined'), form=form, indico_version=indico.__version__, instance_url=config.getBaseURL(), language=config.getDefaultLocale(), operating_system=get_os(), postgres_version=get_postgres_version(), python_version=platform.python_version(), hub_url=hub_url)
def _create_user(self, form, handler, pending_user): data = form.data if pending_user: user = pending_user user.is_pending = False else: user = User() form.populate_obj(user, skip={'email'}) if form.email.data in user.secondary_emails: # This can happen if there's a pending user who has a secondary email # for some weird reason which should now become the primary email... user.make_email_primary(form.email.data) else: user.email = form.email.data identity = handler.create_identity(data) user.identities.add(identity) user.secondary_emails |= handler.get_all_emails(form) - {user.email} user.favorite_users.add(user) db.session.add(user) minfo = HelperMaKaCInfo.getMaKaCInfoInstance() timezone = session.timezone if timezone == 'LOCAL': timezone = Config.getInstance().getDefaultTimezone() user.settings.set('timezone', timezone) user.settings.set('lang', session.lang or minfo.getLang()) handler.update_user(user, form) db.session.flush() # notify everyone of user creation signals.users.registered.send(user) login_user(user, identity) msg = _('You have sucessfully registered your Indico profile. ' 'Check <a href="{url}">your profile</a> for further details and settings.') flash(Markup(msg).format(url=url_for('users.user_profile')), 'success') db.session.flush() return handler.redirect_success()
def convertLinkedTo(dbi, prevVersion): """Convert Avatar.linkedTo structure to use OOTreeSets and import linkedTo information into Redis (if enabled)""" print 'Note: Some links might point to broken objects which will be skipped automatically.' use_redis = Config.getInstance().getRedisConnectionURL() if use_redis: pipe = redis_client.pipeline(transaction=False) for i, avatar in enumerate(AvatarHolder()._getIdx().itervalues()): avatar.updateLinkedTo() # just in case some avatars do not have all fields linkedTo = avatar.linkedTo avatar.resetLinkedTo() # nuke old links for field, data in avatar.linkedToMap.iteritems(): for role in data['roles']: if not linkedTo[field][role]: continue todo = set(linkedTo[field][role]) # We have broken objects in the database which will fail in the getConference() call. If the current # object type has such a method call it on each object and skip it in case it raises an AttributeError if hasattr(linkedTo[field][role][0], 'getConference'): for obj in linkedTo[field][role]: try: obj.getConference() except AttributeError, e: print ' \tSkipping broken object in %s/%s/%s: %r' % (avatar.getId(), field, role, obj) todo.remove(obj) avatar.linkedTo[field][role].update(todo) if use_redis: avatar_links.init_links(avatar, client=pipe) if i % 1000 == 0: if use_redis: pipe.execute() dbi.commit() print '\r %d' % i, sys.stdout.flush()
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() return wcomponents.WHTMLHeader().getHTML({ "area": area, "baseurl": self._getBaseURL(), "conf": Config.getInstance(), "page": self, "extraCSS": map(self._fix_path, self.getCSSFiles()), "extraJSFiles": map(self._fix_path, self.getJSFiles()), "extraJS": self._extraJS, "language": session.lang, "social": info.getSocialAppConfig(), "assets": self._asset_env })
def sync_instance(contact, email): contact = contact or cephalopod_settings.get('contact_name') email = email or cephalopod_settings.get('contact_email') # registration needed if the instance does not have a uuid if not cephalopod_settings.get('uuid'): logger.warn('unable to synchronise: missing uuid, registering the server instead') register_instance(contact, email) return payload = {'enabled': True, 'url': Config.getInstance().getBaseURL(), 'contact': contact, 'email': email, 'organisation': core_settings.get('site_organization')} url = url_join(_get_url(), cephalopod_settings.get('uuid')) response = requests.patch(url, data=json.dumps(payload), headers=HEADERS, timeout=TIMEOUT) try: response.raise_for_status() except HTTPError as err: if err.response.status_code == 404: logger.warn('unable to synchronise: the server was not registered, registering the server now') register_instance(contact, email) else: logger.error('failed to synchronise the server with the community hub, got: %s', err.message) raise except Timeout: logger.error('failed to synchronise: timeout while contacting the community hub') raise except RequestException as err: logger.error('unexpected exception while synchronizing the server with the Community Hub: %s', err.message) raise else: cephalopod_settings.set_multi({ 'joined': True, 'contact_name': payload['contact'], 'contact_email': payload['email']}) logger.info('successfully synchronized the server with the community hub')
def setTemplate(self, name, description, format, fd, id, extension=".template"): """ Stores a template. There can be 1 template for any format. """ cfg = Config.getInstance() tempPath = cfg.getUploadedFilesTempDir() tempFileName = tempfile.mkstemp(suffix="MaKaC.tmp", dir=tempPath)[1] f = open(tempFileName, "wb") f.write(fd.read()) f.close() #id = self.getNewTemplateId() fileName = "Contribution_template_" + id + "_c" + self._conference.id + extension file = conference.LocalFile() file.setName(fileName) file.setDescription("Paper reviewing template with id " + id + "with format: " + format + " of the conference " + self._conference.id) file.setFileName(fileName) file.setFilePath(tempFileName) file.setOwner(self._conference) file.setId(fileName) file.archive(self._conference._getRepository()) self._templates[id] = Template(id, self._conference, name, description, format, file) self.notifyModification()
def default_settings(self): return dict( VCPluginMixin.default_settings, **{ 'support_email': Config.getInstance().getSupportEmail(), 'username': '******', 'password': None, 'admin_api_wsdl': 'https://yourvidyoportal/services/v1_1/VidyoPortalAdminService?wsdl', 'user_api_wsdl': 'https://yourvidyoportal/services/v1_1/VidyoPortalUserService?wsdl', 'indico_room_prefix': 10, 'room_group_name': 'Indico', # we skip identity providers in the default list if they don't support get_identity. # these providers (local accounts, oauth) are unlikely be the correct ones to integrate # with the vidyo infrastructure. 'authenticators': ', '.join(p.name for p in multipass.identity_providers.itervalues() if p.supports_get), 'num_days_old': 365, 'max_rooms_warning': 5000, 'vidyo_phone_link': None, 'creation_email_footer': None, 'client_chooser_url': None })
def shell_cmd(verbose, with_req_context): try: from IPython.terminal.ipapp import TerminalIPythonApp except ImportError: click.echo(cformat('%{red!}You need to `pip install ipython` to use the Indico shell')) sys.exit(1) current_app.config['REPL'] = True # disables e.g. memoize_request request_stats_request_started() context, info = _make_shell_context() banner = cformat('%{yellow!}Indico v{} is ready for your commands').format(indico.__version__) if verbose: banner = '\n'.join(info + ['', banner]) ctx = current_app.make_shell_context() ctx.update(context) clearCache() stack = ExitStack() if with_req_context: stack.enter_context(current_app.test_request_context(base_url=Config.getInstance().getBaseURL())) with stack: ipython_app = TerminalIPythonApp.instance(user_ns=ctx, display_banner=False) ipython_app.initialize(argv=[]) ipython_app.shell.show_banner(banner) ipython_app.start()
def format_time(t, format='short', locale=None, timezone=None, server_tz=False): """ Basically a wrapper around Babel's own format_time """ inject_unicode = True if format == 'code': format = 'HH:mm' inject_unicode = False if not locale: locale = get_current_locale() if not timezone and t.tzinfo: timezone = DisplayTZ().getDisplayTZ() elif server_tz: timezone = Config.getInstance().getDefaultTimezone() if timezone: timezone = get_timezone(timezone) rv = _format_time(t, format=format, locale=locale, tzinfo=timezone) return inject_unicode_debug( rv, 2).encode('utf-8') if inject_unicode else rv.encode('utf-8')
def _sidemenu_items(sender, event, **kwargs): # Some legacy handling of menu items # Once those parts are modularized, we will be able to include them # conditionally from their respective modules. can_modify = event.can_manage(session.user) rb_active = Config.getInstance().getIsRoomBookingActive() event_type = event.as_legacy.getType() is_conference = event_type == 'conference' paper_review = event.as_legacy.getConfPaperReview() is_review_staff = paper_review.isInReviewingTeam(session.avatar) if can_modify: yield SideMenuItem('general', _('General settings'), url_for('event_mgmt.conferenceModification', event), 90, icon='settings') if rb_active: yield SideMenuItem('room_booking', _('Room Booking'), url_for('event_mgmt.rooms_booking_list', event), 50, icon='location') if is_conference: if can_modify or is_review_staff: yield SideMenuItem('paper_reviewing', _('Paper Reviewing'), url_for('event_mgmt.confModifReviewing-access', event), section='organization') if can_modify: yield SideMenuItem('utilities', _('Utilities'), url_for('event_mgmt.confModifTools', event), section='advanced') yield SideMenuItem('protection', _('Protection'), url_for('event_management.protection', event), 60, icon='shield')
def _getIcalExportParams(self, user, url, params={}): minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance() apiMode = minfo.getAPIMode() apiKey = user.getAPIKey() if user else None urls = generate_public_auth_request( apiMode, apiKey, url, params, minfo.isAPIPersistentAllowed() and (apiKey.isPersistentAllowed() if apiKey else False), minfo.isAPIHTTPSRequired()) return { 'currentUser': user, 'icsIconURL': str(Config.getInstance().getSystemIconURL("ical_grey")), 'apiMode': apiMode, 'signingEnabled': apiMode in (API_MODE_SIGNED, API_MODE_ONLYKEY_SIGNED, API_MODE_ALL_SIGNED), 'persistentAllowed': minfo.isAPIPersistentAllowed(), 'requestURLs': urls, 'persistentUserEnabled': apiKey.isPersistentAllowed() if apiKey else False, 'apiActive': apiKey != None, 'userLogged': user != None, 'apiKeyUserAgreement': minfo.getAPIKeyUserAgreement(), 'apiPersistentUserAgreement': minfo.getAPIPersistentUserAgreement() }
def check(self): errors = [] if self.title.strip() == "": errors.append(_("Abstract title cannot be empty")) for f in self._afm.getFields(): value = self._otherFields.get(f.getId(), "") errors += f.check(value) if not self.origin == "management": if not self._prAuthorsListParam: errors.append( _("No primary author has been specified. You must define at least one primary author" )) if not self._checkSpeaker() and self._absMgr.showSelectAsSpeaker( ) and self._absMgr.isSelectSpeakerMandatory(): errors.append(_("At least one presenter must be specified")) if not self.tracks and self._absMgr.areTracksMandatory(): # check if there are tracks, otherwise the user cannot select at least one if len(self._absMgr.getConference().getTrackList()) != 0: errors.append(_("At least one track must be seleted")) if self._hasExceededTotalSize(): errors.append( _("The maximum size allowed for the attachments (%sMB) has been exceeded." ) % Config.getInstance().getMaxUploadFilesTotalSize()) return errors
def _get_static_files(self, html): config = Config.getInstance() soup = BeautifulSoup(html) scripts = set( _fix_url_path(x['src']) for x in soup.select('script[src]')) styles = set( _fix_url_path(x['href']) for x in soup.select('link[rel="stylesheet"]')) for path in itertools.chain(scripts, styles): src_path = os.path.join(config.getHtdocsDir(), path) dst_path = os.path.join(self._staticPath, path) if path in styles: self._css_files.add(path) if not os.path.isfile(src_path): self._failed_paths.add(path) elif path not in styles: self._addFileFromSrc(dst_path, src_path) for script in soup.select('script[src]'): script['src'] = os.path.join('static', _fix_url_path(script['src'])) for style in soup.select('link[rel="stylesheet"]'): style['href'] = os.path.join('static', _fix_url_path(style['href'])) return str(soup)
def _process_GET(self): defaults = FormDefaults(**cephalopod_settings.get_all()) form = CephalopodForm(request.form, obj=defaults) enabled = cephalopod_settings.get('joined') config = Config.getInstance() instance_url = config.getBaseURL() language = config.getDefaultLocale() tracker_url = urljoin( config.getTrackerURL(), 'api/instance/{}'.format(cephalopod_settings.get('uuid'))) return WPCephalopod.render_template( 'cephalopod.html', 'cephalopod', affiliation=core_settings.get('site_organization'), enabled=enabled, form=form, indico_version=indico.__version__, instance_url=instance_url, language=language, operating_system=get_os(), postgres_version=get_postgres_version(), python_version=platform.python_version(), tracker_url=tracker_url)
def __init__(self, booking, oldOwner): VidyoOwnerNotificationBase.__init__(self) self._owner = oldOwner self.setFromAddr("Indico Mailer <%s>" % Config.getInstance().getSupportEmail()) self.setContentType("text/html") event = booking.getConference() self.setToList([oldOwner.getEmail()]) self.setSubject( """[Indico] You are no longer the owner of a Vidyo public room attached to the event: %s""" % event.getTitle()) self.setBody("""Dear %s%s,<br /> <br /> This is an automatic email to inform you that you are no longer the owner of the Vidyo room with name "%s" in the event <a href="%s">%s</a>. The new owner is %s.<br /> <br /> Thank you for using our system.<br /> """ % (self._getOwnerTitleText(), oldOwner.getStraightFullName(), booking.getBookingParamByName("roomName"), urlHandlers.UHConferenceDisplay.getURL(event), event.getTitle(), booking.getOwner()["name"]))
def __init__(self, user, role, contribution): GenericNotification.__init__(self) conference = contribution.event_new.as_legacy self.setFromAddr("Indico <%s>" % Config.getInstance().getNoReplyEmail()) self.setToList([user.email]) self.setSubject("""You have been chosen as a %s for "%s" """% (role, conference.getTitle())) if role == 'Referee': url = url_for('event_mgmt.confListContribToJudge', conference, _external=True) elif role == 'Layout Reviewer': url = url_for('event_mgmt.confListContribToJudge-asEditor', conference, _external=True) elif role == 'Content Reviewer': url = url_for('event_mgmt.confListContribToJudge-asReviewer', conference, _external=True) self.setBody("""Dear %s, You have been chosen as a %s for the paper entitled "%s" (id: %s) for the conference "%s". Please find the %s utilities here: %s Kind regards, Indico on behalf of "%s" """ % ( user.full_name, role, contribution.title, str(contribution.friendly_id), conference.getTitle(), role, url, conference.getTitle()))
def __init__(self, user, judgement, contribution): GenericNotification.__init__(self) conference = contribution.event_new.as_legacy self.setFromAddr("Indico <%s>" % Config.getInstance().getNoReplyEmail()) self.setToList([user.email]) self.setBCCList([judgement.getAuthor().getEmail()]) if isinstance(judgement, RefereeJudgement): typeR = "Referee" elif isinstance(judgement, EditorJudgement): typeR = "Layout Reviewer" elif isinstance(judgement, ReviewerJudgement): typeR = "Content Reviewer" self.setSubject(""""%s" has been put back into reviewing by the %s """ % (contribution.title, typeR)) self.setBody("""Dear %s, Your paper entitled "%s" (id: %s) submitted for "%s" has been put back into reviewing by the assigned %s: %s Kind regards, Indico on behalf of "%s" """ % (user.full_name, contribution.title, str(contribution.friendly_id), conference.getTitle(), typeR, url_for('contributions.display_contribution', contribution, _external=True), conference.getTitle()))
def getVars(self): vars = wcomponents.WTemplated.getVars(self) minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance() vars["title"] = minfo.getTitle() vars["organisation"] = minfo.getOrganisation() vars['supportEmail'] = Config.getInstance().getSupportEmail() vars['publicSupportEmail'] = Config.getInstance( ).getPublicSupportEmail() vars['noReplyEmail'] = Config.getInstance().getNoReplyEmail() vars["lang"] = minfo.getLang() vars["address"] = "" if minfo.getCity() != "": vars["address"] = minfo.getCity() if minfo.getCountry() != "": if vars["address"] != "": vars["address"] = "%s (%s)" % (vars["address"], minfo.getCountry()) else: vars["address"] = "%s" % minfo.getCountry() try: vars["timezone"] = minfo.getTimezone() except: vars["timezone"] = 'UTC' vars["systemIconAdmins"] = Config.getInstance().getSystemIconURL( "admin") iconDisabled = str( Config.getInstance().getSystemIconURL("disabledSection")) iconEnabled = str( Config.getInstance().getSystemIconURL("enabledSection")) url = urlHandlers.UHAdminSwitchNewsActive.getURL() icon = iconEnabled if minfo.isNewsActive() else iconDisabled vars["features"] = i18nformat( """<a href="%s"><img src="%s" border="0" style="float:left; padding-right: 5px">_("News Pages")</a>""" ) % (url, icon) vars["administrators"] = fossilize( [u.as_avatar for u in User.find(is_admin=True)]) return vars
'js/lib/angular-resource.js', 'js/lib/angular-sanitize.js', 'js/lib/sortable.js', 'js/indico/angular/app.js', 'js/indico/angular/directives.js', 'js/indico/angular/filters.js', 'js/indico/angular/services.js', filters='rjsmin', output='js/angular_%(version)s.min.js') jquery = Bundle(*filter(None, [ 'js/lib/underscore.js', 'js/lib/jquery.js', 'js/lib/jquery.qtip.js', 'js/jquery/jquery-ui.js', 'js/lib/jquery.multiselect.js', 'js/lib/jquery.multiselect.filter.js', 'js/jquery/jquery-migrate-silencer.js' if not Config.getInstance().getDebug() else None ] + namespace('js/jquery', 'jquery-migrate.js', 'jquery.form.js', 'jquery.custom.js', 'jquery.daterange.js', 'jquery.dttbutton.js', 'jquery.colorbox.js', 'jquery.menu.js', 'date.js', 'jquery.colorpicker.js', 'jquery-extra-selectors.js', 'jquery.typewatch.js', 'jstorage.js', 'jquery.watermark.js', 'jquery.placeholder.js')), filters='rjsmin', output='js/jquery_code_%(version)s.min.js') utils = Bundle('js/utils/routing.js', filters='rjsmin', output='js/utils_%(version)s.min.js') calendar = Bundle(*namespace('js/calendar', 'calendar.js', 'calendar-setup.js'),
def __init__(self, XG): # self.categoryRoot = conference.CategoryManager().getRoot() self._user = accessControl.AccessWrapper() self._XMLGen = XG self._config = Config.getInstance() self._outGen = outputGenerator(self._user, self._XMLGen)
def setup_jinja(app): config = Config.getInstance() # Unicode hack app.jinja_env.add_extension(EnsureUnicodeExtension) app.add_template_filter(EnsureUnicodeExtension.ensure_unicode) # Useful (Python) builtins app.add_template_global(dict) # Global functions app.add_template_global(url_for) app.add_template_global(url_for_plugin) app.add_template_global(url_rule_to_js) app.add_template_global(IndicoConfigWrapper(config), 'indico_config') app.add_template_global(config.getSystemIconURL, 'system_icon') app.add_template_global(include_css_assets) app.add_template_global(include_js_assets) app.add_template_global(include_plugin_css_assets) app.add_template_global(include_plugin_js_assets) app.add_template_global(call_template_hook, 'template_hook') app.add_template_global(is_single_line_field, '_is_single_line_field') app.add_template_global(render_field, '_render_field') app.add_template_global(iter_form_fields, '_iter_form_fields') app.add_template_global(format_currency) app.add_template_global(get_currency_name) app.add_template_global(url_for_index) app.add_template_global(url_for_login) app.add_template_global(url_for_logout) app.add_template_global(lambda: unicode(uuid.uuid4()), 'uuid') app.add_template_global(icon_from_mimetype) app.add_template_global(render_sidemenu) app.add_template_global(slugify) app.add_template_global(lambda: date_time_util.now_utc(False), 'now') app.add_template_global(render_session_bar) app.add_template_global(lambda: 'custom_js' in core_env, 'has_custom_js') app.add_template_global(lambda: 'custom_sass' in core_env, 'has_custom_sass') app.add_template_global(get_request_stats) # Global variables app.add_template_global(LocalProxy(get_current_locale), 'current_locale') # Useful constants app.add_template_global('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$', name='time_regex_hhmm') # for input[type=time] # Filters (indico functions returning UTF8) app.add_template_filter( EnsureUnicodeExtension.wrap_func(date_time_util.format_date)) app.add_template_filter( EnsureUnicodeExtension.wrap_func(date_time_util.format_time)) app.add_template_filter( EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime)) app.add_template_filter( EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date)) app.add_template_filter( EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta)) app.add_template_filter( EnsureUnicodeExtension.wrap_func(date_time_util.format_number)) # Filters (new ones returning unicode) app.add_template_filter(date_time_util.format_human_timedelta) app.add_template_filter(date_time_util.format_pretty_date) app.add_template_filter(date_time_util.format_pretty_datetime) app.add_template_filter(lambda d: Markup(html_params(**d)), 'html_params') app.add_template_filter(underline) app.add_template_filter(markdown) app.add_template_filter(dedent) app.add_template_filter(natsort) app.add_template_filter(groupby) app.add_template_filter(any) app.add_template_filter(strip_tags) app.add_template_filter(alpha_enum) app.add_template_filter(crc32) app.add_template_filter(bool) # Tests app.add_template_test( instanceof) # only use this test if you really have to! app.add_template_test( subclassof) # only use this test if you really have to! # i18n app.jinja_env.add_extension('jinja2.ext.i18n') app.jinja_env.install_gettext_callables(gettext_context, ngettext_context, True) # webassets app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension') app.jinja_env.assets_environment = core_env
def _getNewTempFile(self): cfg = Config.getInstance() tempPath = cfg.getUploadedFilesTempDir() tempFileName = tempfile.mkstemp(suffix="Indico.tmp", dir=tempPath)[1] return tempFileName
def __init__(self): self._tempFiles = {} self._repositoryIds = None self._errorList = [] self._cfg = Config.getInstance()