diff --git a/config/invenio.conf b/config/invenio.conf index 5e98c5017..068ed09e2 100644 --- a/config/invenio.conf +++ b/config/invenio.conf @@ -1,2346 +1,2361 @@ ## This file is part of Invenio. ## Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. ################################################### ## About 'invenio.conf' and 'invenio-local.conf' ## ################################################### ## The 'invenio.conf' file contains the vanilla default configuration ## parameters of a Invenio installation, as coming out of the ## distribution. The file should be self-explanatory. Once installed ## in its usual location (usually /opt/invenio/etc), you could in ## principle go ahead and change the values according to your local ## needs, but this is not advised. ## ## If you would like to customize some of these parameters, you should ## rather create a file named 'invenio-local.conf' in the same ## directory where 'invenio.conf' lives and you should write there ## only the customizations that you want to be different from the ## vanilla defaults. ## ## Here is a realistic, minimalist, yet production-ready example of ## what you would typically put there: ## ## $ cat /opt/invenio/etc/invenio-local.conf ## [Invenio] ## CFG_SITE_NAME = John Doe's Document Server ## CFG_SITE_NAME_INTL_fr = Serveur des Documents de John Doe ## CFG_SITE_URL = http://your.site.com ## CFG_SITE_SECURE_URL = https://your.site.com ## CFG_SITE_ADMIN_EMAIL = john.doe@your.site.com ## CFG_SITE_SUPPORT_EMAIL = john.doe@your.site.com ## CFG_WEBALERT_ALERT_ENGINE_EMAIL = john.doe@your.site.com ## CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL = john.doe@your.site.com ## CFG_WEBCOMMENT_DEFAULT_MODERATOR = john.doe@your.site.com ## CFG_DATABASE_HOST = localhost ## CFG_DATABASE_NAME = invenio ## CFG_DATABASE_USER = invenio ## CFG_DATABASE_PASS = my123p$ss ## ## You should override at least the parameters mentioned above and the ## parameters mentioned in the `Part 1: Essential parameters' below in ## order to define some very essential runtime parameters such as the ## name of your document server (CFG_SITE_NAME and ## CFG_SITE_NAME_INTL_*), the visible URL of your document server ## (CFG_SITE_URL and CFG_SITE_SECURE_URL), the email address of the ## local Invenio administrator, comment moderator, and alert engine ## (CFG_SITE_SUPPORT_EMAIL, CFG_SITE_ADMIN_EMAIL, etc), and last but ## not least your database credentials (CFG_DATABASE_*). ## ## The Invenio system will then read both the default invenio.conf ## file and your customized invenio-local.conf file and it will ## override any default options with the ones you have specified in ## your local file. This cascading of configuration parameters will ## ease your future upgrades. [Invenio] ################################### ## Part 1: Essential parameters ## ################################### ## This part defines essential Invenio internal parameters that ## everybody should override, like the name of the server or the email ## address of the local Invenio administrator. ## CFG_DATABASE_* - specify which MySQL server to use, the name of the ## database to use, and the database access credentials. CFG_DATABASE_TYPE = mysql CFG_DATABASE_HOST = localhost CFG_DATABASE_PORT = 3306 CFG_DATABASE_NAME = invenio CFG_DATABASE_USER = invenio CFG_DATABASE_PASS = my123p$ss ## CFG_DATABASE_SLAVE - if you use DB replication, then specify the DB ## slave address credentials. (Assuming the same access rights to the ## DB slave as to the DB master.) If you don't use DB replication, ## then leave this option blank. CFG_DATABASE_SLAVE = ## CFG_SITE_URL - specify URL under which your installation will be ## visible. For example, use "http://your.site.com". Do not leave ## trailing slash. CFG_SITE_URL = http://localhost ## CFG_SITE_SECURE_URL - specify secure URL under which your ## installation secure pages such as login or registration will be ## visible. For example, use "https://your.site.com". Do not leave ## trailing slash. If you don't plan on using HTTPS, then you may ## leave this empty. CFG_SITE_SECURE_URL = https://localhost ## CFG_SITE_NAME -- the visible name of your Invenio installation. CFG_SITE_NAME = Atlantis Institute of Fictive Science ## CFG_SITE_NAME_INTL -- the international versions of CFG_SITE_NAME ## in various languages. (See also CFG_SITE_LANGS below.) CFG_SITE_NAME_INTL_en = Atlantis Institute of Fictive Science CFG_SITE_NAME_INTL_fr = Atlantis Institut des Sciences Fictives CFG_SITE_NAME_INTL_de = Atlantis Institut der fiktiven Wissenschaft CFG_SITE_NAME_INTL_es = Atlantis Instituto de la Ciencia Fictive CFG_SITE_NAME_INTL_ca = Institut Atlantis de Ciència Fictícia CFG_SITE_NAME_INTL_pt = Instituto Atlantis de Ciência Fictícia CFG_SITE_NAME_INTL_it = Atlantis Istituto di Scienza Fittizia CFG_SITE_NAME_INTL_ru = Институт Фиктивных Наук Атлантиды CFG_SITE_NAME_INTL_sk = Atlantis Inštitút Fiktívnych Vied CFG_SITE_NAME_INTL_cs = Atlantis Institut Fiktivních Věd CFG_SITE_NAME_INTL_no = Atlantis Institutt for Fiktiv Vitenskap CFG_SITE_NAME_INTL_sv = Atlantis Institut för Fiktiv Vetenskap CFG_SITE_NAME_INTL_el = Ινστιτούτο Φανταστικών Επιστημών Ατλαντίδος CFG_SITE_NAME_INTL_uk = Інститут вигаданих наук в Атлантісі CFG_SITE_NAME_INTL_ja = Fictive 科学のAtlantis の協会 CFG_SITE_NAME_INTL_pl = Instytut Fikcyjnej Nauki Atlantis CFG_SITE_NAME_INTL_bg = Институт за фиктивни науки Атлантис CFG_SITE_NAME_INTL_hr = Institut Fiktivnih Znanosti Atlantis CFG_SITE_NAME_INTL_zh_CN = 阿特兰提斯虚拟科学学院 CFG_SITE_NAME_INTL_zh_TW = 阿特蘭提斯虛擬科學學院 CFG_SITE_NAME_INTL_hu = Kitalált Tudományok Atlantiszi Intézete CFG_SITE_NAME_INTL_af = Atlantis Instituut van Fiktiewe Wetenskap CFG_SITE_NAME_INTL_gl = Instituto Atlantis de Ciencia Fictive CFG_SITE_NAME_INTL_ro = Institutul Atlantis al Ştiinţelor Fictive CFG_SITE_NAME_INTL_rw = Atlantis Ishuri Rikuru Ry'ubuhanga CFG_SITE_NAME_INTL_ka = ატლანტიდის ფიქტიური მეცნიერების ინსტიტუტი CFG_SITE_NAME_INTL_lt = Fiktyvių Mokslų Institutas Atlantis CFG_SITE_NAME_INTL_ar = معهد أطلنطيس للعلوم الافتراضية ## CFG_SITE_LANG -- the default language of the interface: ' CFG_SITE_LANG = en ## CFG_SITE_LANGS -- list of all languages the user interface should ## be available in, separated by commas. The order specified below ## will be respected on the interface pages. A good default would be ## to use the alphabetical order. Currently supported languages ## include Afrikaans, Arabic, Bulgarian, Catalan, Czech, German, Georgian, ## Greek, English, Spanish, French, Croatian, Hungarian, Galician, ## Italian, Japanese, Kinyarwanda, Lithuanian, Norwegian, Polish, ## Portuguese, Romanian, Russian, Slovak, Swedish, Ukrainian, Chinese ## (China), Chinese (Taiwan), so that the eventual maximum you can ## currently select is ## "af,ar,bg,ca,cs,de,el,en,es,fr,hr,gl,ka,it,rw,lt,hu,ja,no,pl,pt,ro,ru,sk,sv,uk,zh_CN,zh_TW". CFG_SITE_LANGS = af,ar,bg,ca,cs,de,el,en,es,fr,hr,gl,ka,it,rw,lt,hu,ja,no,pl,pt,ro,ru,sk,sv,uk,zh_CN,zh_TW +## CFG_EMAIL_BACKEND -- the backend to use for sending emails. Defaults to +## 'flask.ext.email.backends.smtp.Mail' if CFG_MISCUTIL_SMTP_HOST and +## CFG_MISCUTIL_SMTP_PORT are set. Possible values are: +## - flask.ext.email.backends.console.Mail +## - flask.ext.email.backends.dummy.Mail +## - flask.ext.email.backends.filebased.Mail +## - flask.ext.email.backends.locmem.Mail +## - flask.ext.email.backends.smtp.Mail +## - invenio.mailutils_backend_adminonly.ConsoleMail +## - invenio.mailutils_backend_adminonly.SMTPMail +## * sends email only to the CFG_SITE_ADMIN_EMAIL address using SMTP +CFG_EMAIL_BACKEND = flask.ext.email.backends.smtp.Mail + ## CFG_SITE_SUPPORT_EMAIL -- the email address of the support team for ## this installation: CFG_SITE_SUPPORT_EMAIL = info@invenio-software.org ## CFG_SITE_ADMIN_EMAIL -- the email address of the 'superuser' for ## this installation. Enter your email address below and login with ## this address when using Invenio inistration modules. You ## will then be automatically recognized as superuser of the system. CFG_SITE_ADMIN_EMAIL = info@invenio-software.org ## CFG_SITE_EMERGENCY_EMAIL_ADDRESSES -- list of email addresses to ## which an email should be sent in case of emergency (e.g. bibsched ## queue has been stopped because of an error). Configuration ## dictionary allows for different recipients based on weekday and ## time-of-day. Example: ## ## CFG_SITE_EMERGENCY_EMAIL_ADDRESSES = { ## 'Sunday 22:00-06:00': '0041761111111@email2sms.foo.com', ## '06:00-18:00': 'team-in-europe@foo.com,0041762222222@email2sms.foo.com', ## '18:00-06:00': 'team-in-usa@foo.com', ## '*': 'john.doe.phone@foo.com'} ## ## If you want the emergency email notifications to always go to the ## same address, just use the wildcard line in the above example. CFG_SITE_EMERGENCY_EMAIL_ADDRESSES = {} ## CFG_SITE_ADMIN_EMAIL_EXCEPTIONS -- set this to 0 if you do not want ## to receive any captured exception via email to CFG_SITE_ADMIN_EMAIL ## address. Captured exceptions will still be available in ## var/log/invenio.err file. Set this to 1 if you want to receive ## some of the captured exceptions (this depends on the actual place ## where the exception is captured). Set this to 2 if you want to ## receive all captured exceptions. CFG_SITE_ADMIN_EMAIL_EXCEPTIONS = 1 ## CFG_SITE_RECORD -- what is the URI part representing detailed ## record pages? We recommend to leave the default value `record' ## unchanged. CFG_SITE_RECORD = record ## CFG_SITE_SECRET_KEY --- which secret key should we use? This should be set ## to a random value per Invenio installation and must be kept secret, as it is ## used to protect against e.g. cross-site request forgery and other is the ## basis of other security measures in Invenio. A random value can be generated ## using the following command: ## python -c "import os;import re;print re.escape(os.urandom(24).__repr__()[1:-1])" CFG_SITE_SECRET_KEY = ## CFG_ERRORLIB_RESET_EXCEPTION_NOTIFICATION_COUNTER_AFTER -- set this to ## the number of seconds after which to reset the exception notification ## counter. A given repetitive exception is notified via email with a ## logarithmic strategy: the first time it is seen it is sent via email, ## then the second time, then the fourth, then the eighth and so forth. ## If the number of seconds elapsed since the last time it was notified ## is greater than CFG_ERRORLIB_RESET_EXCEPTION_NOTIFICATION_COUNTER_AFTER ## then the internal counter is reset in order not to have exception ## notification become more and more rare. CFG_ERRORLIB_RESET_EXCEPTION_NOTIFICATION_COUNTER_AFTER = 14400 ## CFG_CERN_SITE -- do we want to enable CERN-specific code? ## Put "1" for "yes" and "0" for "no". CFG_CERN_SITE = 0 ## CFG_INSPIRE_SITE -- do we want to enable INSPIRE-specific code? ## Put "1" for "yes" and "0" for "no". CFG_INSPIRE_SITE = 0 ## CFG_ADS_SITE -- do we want to enable ADS-specific code? ## Put "1" for "yes" and "0" for "no". CFG_ADS_SITE = 0 ## CFG_OPENAIRE_SITE -- do we want to enable OpenAIRE-specific code? ## Put "1" for "yes" and "0" for "no". CFG_OPENAIRE_SITE = 0 ## CFG_FLASK_CACHE_TYPE -- do we want to enable any cache engine? ## 'null', 'redis' or your own e.g. 'invenio.cache.my_cache_engine' ## NOTE: If you disable cache engine it WILL affect some ## functionality such as 'search facets'. CFG_FLASK_CACHE_TYPE = null ## CFG_FLASK_DISABLED_BLUEPRINTS -- do we want to prevent certain blueprints from ## being loaded? CFG_FLASK_DISABLED_BLUEPRINTS = ## CFG_FLASK_SERVE_STATIC_FILES -- do we want Flask to serve static files? ## Normally Apache serves static files, but during development and if you are ## using the Werkzeug standalone development server, you can set this flag to ## "1", to enable static file serving. CFG_FLASK_SERVE_STATIC_FILES = 0 ## Now you can tune whether to integrate with external authentication providers ## through the OpenID and OAuth protocols. ## The following variables let you fine-tune which authentication ## providers you want to authorize. You can override here most of ## the variables in lib/invenio/access_control_config.py. ## In particular you can put in these variable the consumer_key and ## consumer_secret of the desired services. ## Note: some providers don't supply an mail address. ## If you choose them, the users will be registered with a temporary email address. ## CFG_OPENID_PROVIDERS -- Comma-separated list of providers you want to enable ## through the OpenID protocol. ## E.g.: CFG_OPENID_PROVIDERS = google,yahoo,aol,wordpress,myvidoop,openid,verisign,myopenid,myspace,livejournal,blogger CFG_OPENID_PROVIDERS = ## CFG_OAUTH1_PROVIDERS -- Comma-separated list of providers you want to enable ## through the OAuth1 protocol. ## Note: OAuth1 is in general deprecated in favour of OAuth2. ## E.g.: CFG_OAUTH1_PROVIDERS = twitter,linkedin,flickr, CFG_OAUTH1_PROVIDERS = ## CFG_OAUTH2_PROVIDERS -- Comma-separated list of providers you want to enable ## through the OAuth2 protocol. ## Note: if you enable the "orcid" provider the full profile of the user ## in Orcid will be imported. ## E.g.: CFG_OAUTH2_PROVIDERS = facebook,yammer,foursquare,googleoauth2,instagram,orcid CFG_OAUTH2_PROVIDERS = ## CFG_OPENID_CONFIGURATIONS -- Mapping of special parameter to configure the ## desired OpenID providers. Use this variable to override out-of-the-box ## parameters already set in lib/python/invenio/access_control_config.py. ## E.g.: CFG_OPENID_CONFIGURATIONS = {'google': { ## 'identifier': 'https://www.google.com/accounts/o8/id', ## 'trust_email': True}} CFG_OPENID_CONFIGURATIONS = {} ## CFG_OAUTH1_CONFIGURATIONS -- Mapping of special parameter to configure the ## desired OAuth1 providers. Use this variable to override out-of-the-box ## parameters already set in lib/python/invenio/access_control_config.py. ## E.g.: CFG_OAUTH1_CONFIGURATIONS = {'linkedin': { ## 'consumer_key' : 'MY_LINKEDIN_CONSUMER_KEY', ## 'consumer_secret' : 'MY_LINKEDIN_CONSUMER_SECRET'}} CFG_OAUTH1_CONFIGURATIONS = {} ## CFG_OAUTH2_CONFIGURATIONS -- Mapping of special parameter to configure the ## desired OAuth2 providers. Use this variable to override out-of-the-box ## parameters already set in lib/python/invenio/access_control_config.py. ## E.g.: CFG_OAUTH2_CONFIGURATIONS = {'orcid': { ## 'consumer_key' : 'MY_ORCID_CONSUMER_KEY', ## 'consumer_secret' : 'MY_ORCID_CONSUMER_SECRET'}} CFG_OAUTH2_CONFIGURATIONS = {} ################################ ## Part 2: Web page style ## ################################ ## The variables affecting the page style. The most important one is ## the 'template skin' you would like to use and the obfuscation mode ## for your email addresses. Please refer to the WebStyle Admin Guide ## for more explanation. The other variables are listed here mostly ## for backwards compatibility purposes only. ## CFG_WEBSTYLE_TEMPLATE_SKIN -- what template skin do you want to ## use? CFG_WEBSTYLE_TEMPLATE_SKIN = default ## CFG_WEBSTYLE_EMAIL_ADDRESSES_OBFUSCATION_MODE. How do we "protect" ## email addresses from undesired automated email harvesters? This ## setting will not affect 'support' and 'admin' emails. ## NOTE: there is no ultimate solution to protect against email ## harvesting. All have drawbacks and can more or less be ## circumvented. Choose you preferred mode ([t] means "transparent" ## for the user): ## -1: hide all emails. ## [t] 0 : no protection, email returned as is. ## foo@example.com => foo@example.com ## 1 : basic email munging: replaces @ by [at] and . by [dot] ## foo@example.com => foo [at] example [dot] com ## [t] 2 : transparent name mangling: characters are replaced by ## equivalent HTML entities. ## foo@example.com => foo@example.com ## [t] 3 : javascript insertion. Requires Javascript enabled on client ## side. ## 4 : replaces @ and . characters by gif equivalents. ## foo@example.com => foo [at] example [dot] com CFG_WEBSTYLE_EMAIL_ADDRESSES_OBFUSCATION_MODE = 2 ## (deprecated) CFG_WEBSTYLE_CDSPAGEBOXLEFTTOP -- eventual global HTML ## left top box: CFG_WEBSTYLE_CDSPAGEBOXLEFTTOP = ## (deprecated) CFG_WEBSTYLE_CDSPAGEBOXLEFTBOTTOM -- eventual global ## HTML left bottom box: CFG_WEBSTYLE_CDSPAGEBOXLEFTBOTTOM = ## (deprecated) CFG_WEBSTYLE_CDSPAGEBOXRIGHTTOP -- eventual global ## HTML right top box: CFG_WEBSTYLE_CDSPAGEBOXRIGHTTOP = ## (deprecated) CFG_WEBSTYLE_CDSPAGEBOXRIGHTBOTTOM -- eventual global ## HTML right bottom box: CFG_WEBSTYLE_CDSPAGEBOXRIGHTBOTTOM = ## CFG_WEBSTYLE_HTTP_STATUS_ALERT_LIST -- when certain HTTP status ## codes are raised to the WSGI handler, the corresponding exceptions ## and error messages can be sent to the system administrator for ## inspecting. This is useful to detect and correct errors. The ## variable represents a comma-separated list of HTTP statuses that ## should alert admin. Wildcards are possible. If the status is ## followed by an "r", it means that a referer is required to exist ## (useful to distinguish broken known links from URL typos when 404 ## errors are raised). CFG_WEBSTYLE_HTTP_STATUS_ALERT_LIST = 404r,400,5*,41* ## CFG_WEBSTYLE_HTTP_USE_COMPRESSION -- whether to enable deflate ## compression of your HTTP/HTTPS connections. This will affect the Apache ## configuration snippets created by inveniocfg --create-apache-conf and ## the OAI-PMH Identify response. CFG_WEBSTYLE_HTTP_USE_COMPRESSION = 0 ## CFG_WEBSTYLE_REVERSE_PROXY_IPS -- if you are setting a multinode ## environment where an HTTP proxy such as mod_proxy is sitting in ## front of the Invenio web application and is forwarding requests to ## worker nodes, set here the the list of IP addresses of the allowed ## HTTP proxies. This is needed in order to avoid IP address spoofing ## when worker nodes are also available on the public Internet and ## might receive forged HTTP requests. Only HTTP requests coming from ## the specified IP addresses will be considered as forwarded from a ## reverse proxy. E.g. set this to '123.123.123.123'. CFG_WEBSTYLE_REVERSE_PROXY_IPS = ################################## ## Part 3: WebSearch parameters ## ################################## ## This section contains some configuration parameters for WebSearch ## module. Please note that WebSearch is mostly configured on ## run-time via its WebSearch Admin web interface. The parameters ## below are the ones that you do not probably want to modify very ## often during the runtime. (Note that you may modify them ## afterwards too, though.) ## CFG_WEBSEARCH_SEARCH_CACHE_SIZE -- do you want to enable search ## caching in global search cache engine (e.g. Redis)? This cache is ## used mainly for "next/previous page" functionality, but it caches ## "popular" user queries too if more than one user happen to search ## for the same thing. Note that if you disable the search caching ## features like "facets" will not work. We recommend a value to be ## kept at CFG_WEBSEARCH_SEARCH_CACHE_SIZE = 1. CFG_WEBSEARCH_SEARCH_CACHE_SIZE = 1 ## CFG_WEBSEARCH_SEARCH_CACHE_TIMEOUT -- how long should we keep a ## search result in the cache. The value should be more than 0 and ## the unit is second. [600 s = 10 minutes] CFG_WEBSEARCH_SEARCH_CACHE_TIMEOUT = 600 ## CFG_WEBSEARCH_FIELDS_CONVERT -- if you migrate from an older ## system, you may want to map field codes of your old system (such as ## 'ti') to Invenio/MySQL ("title"). Use Python dictionary syntax ## for the translation table, e.g. {'wau':'author', 'wti':'title'}. ## Usually you don't want to do that, and you would use empty dict {}. CFG_WEBSEARCH_FIELDS_CONVERT = {} ## CFG_WEBSEARCH_LIGHTSEARCH_PATTERN_BOX_WIDTH -- width of the ## search pattern window in the light search interface, in ## characters. CFG_WEBSEARCH_LIGHTSEARCH_PATTERN_BOX_WIDTH = 60 CFG_WEBSEARCH_LIGHTSEARCH_PATTERN_BOX_WIDTH = 60 ## CFG_WEBSEARCH_SIMPLESEARCH_PATTERN_BOX_WIDTH -- width of the search ## pattern window in the simple search interface, in characters. CFG_WEBSEARCH_SIMPLESEARCH_PATTERN_BOX_WIDTH = 40 ## CFG_WEBSEARCH_ADVANCEDSEARCH_PATTERN_BOX_WIDTH -- width of the ## search pattern window in the advanced search interface, in ## characters. CFG_WEBSEARCH_ADVANCEDSEARCH_PATTERN_BOX_WIDTH = 30 ## CFG_WEBSEARCH_NB_RECORDS_TO_SORT -- how many records do we still ## want to sort? For higher numbers we print only a warning and won't ## perform any sorting other than default 'latest records first', as ## sorting would be very time consuming then. We recommend a value of ## not more than a couple of thousands. CFG_WEBSEARCH_NB_RECORDS_TO_SORT = 1000 ## CFG_WEBSEARCH_CALL_BIBFORMAT -- if a record is being displayed but ## it was not preformatted in the "HTML brief" format, do we want to ## call BibFormatting on the fly? Put "1" for "yes" and "0" for "no". ## Note that "1" will display the record exactly as if it were fully ## preformatted, but it may be slow due to on-the-fly processing; "0" ## will display a default format very fast, but it may not have all ## the fields as in the fully preformatted HTML brief format. Note ## also that this option is active only for old (PHP) formats; the new ## (Python) formats are called on the fly by default anyway, since ## they are much faster. When usure, please set "0" here. CFG_WEBSEARCH_CALL_BIBFORMAT = 0 ## CFG_WEBSEARCH_USE_ALEPH_SYSNOS -- do we want to make old SYSNOs ## visible rather than MySQL's record IDs? You may use this if you ## migrate from a different e-doc system, and you store your old ## system numbers into 970__a. Put "1" for "yes" and "0" for ## "no". Usually you don't want to do that, though. CFG_WEBSEARCH_USE_ALEPH_SYSNOS = 0 ## CFG_WEBSEARCH_I18N_LATEST_ADDITIONS -- Put "1" if you want the ## "Latest Additions" in the web collection pages to show ## internationalized records. Useful only if your brief BibFormat ## templates contains internationalized strings. Otherwise put "0" in ## order not to slow down the creation of latest additions by WebColl. CFG_WEBSEARCH_I18N_LATEST_ADDITIONS = 0 ## CFG_WEBSEARCH_INSTANT_BROWSE -- the number of records to display ## under 'Latest Additions' in the web collection pages. CFG_WEBSEARCH_INSTANT_BROWSE = 10 ## CFG_WEBSEARCH_INSTANT_BROWSE_RSS -- the number of records to ## display in the RSS feed. CFG_WEBSEARCH_INSTANT_BROWSE_RSS = 25 ## CFG_WEBSEARCH_RSS_I18N_COLLECTIONS -- comma-separated list of ## collections that feature an internationalized RSS feed on their ## main seach interface page created by webcoll. Other collections ## will have RSS feed using CFG_SITE_LANG. CFG_WEBSEARCH_RSS_I18N_COLLECTIONS = ## CFG_WEBSEARCH_RSS_TTL -- number of minutes that indicates how long ## a feed cache is valid. CFG_WEBSEARCH_RSS_TTL = 360 ## CFG_WEBSEARCH_RSS_MAX_CACHED_REQUESTS -- maximum number of request kept ## in cache. If the cache is filled, following request are not cached. CFG_WEBSEARCH_RSS_MAX_CACHED_REQUESTS = 1000 ## CFG_WEBSEARCH_AUTHOR_ET_AL_THRESHOLD -- up to how many author names ## to print explicitely; for more print "et al". Note that this is ## used in default formatting that is seldomly used, as usually ## BibFormat defines all the format. The value below is only used ## when BibFormat fails, for example. CFG_WEBSEARCH_AUTHOR_ET_AL_THRESHOLD = 3 ## CFG_WEBSEARCH_NARROW_SEARCH_SHOW_GRANDSONS -- whether to show or ## not collection grandsons in Narrow Search boxes (sons are shown by ## default, grandsons are configurable here). Use 0 for no and 1 for ## yes. CFG_WEBSEARCH_NARROW_SEARCH_SHOW_GRANDSONS = 1 ## CFG_WEBSEARCH_CREATE_SIMILARLY_NAMED_AUTHORS_LINK_BOX -- shall we ## create help links for Ellis, Nick or Ellis, Nicholas and friends ## when Ellis, N was searched for? Useful if you have one author ## stored in the database under several name formats, namely surname ## comma firstname and surname comma initial cataloging policy. Use 0 ## for no and 1 for yes. CFG_WEBSEARCH_CREATE_SIMILARLY_NAMED_AUTHORS_LINK_BOX = 1 ## CFG_WEBSEARCH_USE_MATHJAX_FOR_FORMATS -- MathJax is a JavaScript ## library that renders (La)TeX mathematical formulas in the client ## browser. This parameter must contain a comma-separated list of ## output formats for which to apply the MathJax rendering, for example ## "hb,hd". If the list is empty, MathJax is disabled. CFG_WEBSEARCH_USE_MATHJAX_FOR_FORMATS = ## CFG_WEBSEARCH_EXTERNAL_COLLECTION_SEARCH_TIMEOUT -- when searching ## external collections (e.g. SPIRES, CiteSeer, etc), how many seconds ## do we wait for reply before abandonning? CFG_WEBSEARCH_EXTERNAL_COLLECTION_SEARCH_TIMEOUT = 5 ## CFG_WEBSEARCH_EXTERNAL_COLLECTION_SEARCH_MAXRESULTS -- how many ## results do we fetch? CFG_WEBSEARCH_EXTERNAL_COLLECTION_SEARCH_MAXRESULTS = 10 ## CFG_WEBSEARCH_SPLIT_BY_COLLECTION -- do we want to split the search ## results by collection or not? Use 0 for not, 1 for yes. CFG_WEBSEARCH_SPLIT_BY_COLLECTION = 1 ## CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS -- the default number of ## records to display per page in the search results pages. CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS = 10 ## CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS -- in order to limit denial of ## service attacks the total number of records per group displayed as a ## result of a search query will be limited to this number. Only the superuser ## queries will not be affected by this limit. CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS = 200 ## CFG_WEBSEARCH_SHOW_COMMENT_COUNT -- do we want to show the 'N comments' ## links on the search engine pages? (useful only when you have allowed ## commenting) CFG_WEBSEARCH_SHOW_COMMENT_COUNT = 1 ## CFG_WEBSEARCH_SHOW_REVIEW_COUNT -- do we want to show the 'N reviews' ## links on the search engine pages? (useful only when you have allowed ## reviewing) CFG_WEBSEARCH_SHOW_REVIEW_COUNT = 1 ## CFG_WEBSEARCH_FULLTEXT_SNIPPETS_GENERATOR -- how do we want to generate ## fulltext? Can be generated by 'native' Invenio or 'SOLR' CFG_WEBSEARCH_FULLTEXT_SNIPPETS_GENERATOR = native ## CFG_WEBSEARCH_FULLTEXT_SNIPPETS -- how many full-text snippets do ## we want to display for full-text searches? If you want to specify ## different values for different document status types, please add ## more items into this dictionary. (Unless specified, the empty ## value will be used as default.) This is useful if you have ## restricted files of different types with various restrictions on ## what we can show. CFG_WEBSEARCH_FULLTEXT_SNIPPETS = { '': 4, } ## CFG_WEBSEARCH_FULLTEXT_SNIPPETS_CHARS -- what is the maximum size ## of a snippet to display around the pattern found in the full-text? ## If you want to specify different values for different document ## status types, please add more items into this dictionary. (Unless ## specified, the empty value will be used as default.) This is ## useful if you have restricted files of different types with various ## restrictions on what we can show. CFG_WEBSEARCH_FULLTEXT_SNIPPETS_CHARS = { '': 100, } ## CFG_WEBSEARCH_WILDCARD_LIMIT -- some of the queries, wildcard ## queries in particular (ex: cern*, a*), but also regular expressions ## (ex: [a-z]+), may take a long time to respond due to the high ## number of hits. You can limit the number of terms matched by a ## wildcard by setting this variable. A negative value or zero means ## that none of the queries will be limited (which may be wanted by ## also prone to denial-of-service kind of attacks). CFG_WEBSEARCH_WILDCARD_LIMIT = 50000 ## CFG_WEBSEARCH_SYNONYM_KBRS -- defines which knowledge bases are to ## be used for which index in order to provide runtime synonym lookup ## of user-supplied terms, and what massaging function should be used ## upon search pattern before performing the KB lookup. (Can be one ## of `exact', 'leading_to_comma', `leading_to_number'.) CFG_WEBSEARCH_SYNONYM_KBRS = { 'journal': ['SEARCH-SYNONYM-JOURNAL', 'leading_to_number'], } ## CFG_SOLR_URL -- optionally, you may use Solr to serve full-text ## queries and ranking. If so, please specify the URL of your Solr instance. ## Example: http://localhost:8983/solr (default solr port) CFG_SOLR_URL = ## CFG_XAPIAN_ENABLED -- optionally, you may use Xapian to serve full-text ## queries and ranking. If so, please enable it: 1 = enabled CFG_XAPIAN_ENABLED = ## CFG_WEBSEARCH_PREV_NEXT_HIT_LIMIT -- specify the limit when ## the previous/next/back hit links are to be displayed on detailed record pages. ## In order to speeding up list manipulations, if a search returns lots of hits, ## more than this limit, then do not loose time calculating next/previous/back ## hits at all, but display page directly without these. ## Note also that Invenio installations that do not like ## to have the next/previous hit link functionality would be able to set this ## variable to zero and not see anything. CFG_WEBSEARCH_PREV_NEXT_HIT_LIMIT = 1000 ## CFG_WEBSEARCH_PREV_NEXT_HIT_FOR_GUESTS -- Set this to 0 if you want ## to disable the previous/next/back hit link functionality for guests ## users. ## Since the previous/next/back hit link functionality is causing the allocation ## of user session in the database even for guests users, it might be useful to ## be able to disable it e.g. when your site is bombarded by web request ## (a.k.a. Slashdot effect). CFG_WEBSEARCH_PREV_NEXT_HIT_FOR_GUESTS = 1 ## CFG_WEBSEARCH_VIEWRESTRCOLL_POLICY -- when a record belongs to more than one ## restricted collection, if the viewrestcoll policy is set to "ALL" (default) ## then the user must be authorized to all the restricted collections, in ## order to be granted access to the specific record. If the policy is set to ## "ANY", then the user need to be authorized to only one of the collections ## in order to be granted access to the specific record. CFG_WEBSEARCH_VIEWRESTRCOLL_POLICY = ANY ## CFG_WEBSEARCH_SPIRES_SYNTAX -- variable to configure the use of the ## SPIRES query syntax in searches. Values: 0 = SPIRES syntax is ## switched off; 1 = leading 'find' is required; 9 = leading 'find' is ## not required (leading SPIRES operator, space-operator-space, etc ## are also accepted). CFG_WEBSEARCH_SPIRES_SYNTAX = 1 ## CFG_WEBSEARCH_DISPLAY_NEAREST_TERMS -- when user search does not ## return any direct result, what do we want to display? Set to 0 in ## order to display a generic message about search returning no hits. ## Set to 1 in order to display list of nearest terms from the indexes ## that may match user query. Note: this functionality may be slow, ## so you may want to disable it on bigger sites. CFG_WEBSEARCH_DISPLAY_NEAREST_TERMS = 1 ## CFG_WEBSEARCH_DETAILED_META_FORMAT -- the output format to use for ## detailed meta tags containing metadata as configured in the tag ## table. Default output format should be 'hdm', included. This ## format will be included in the header of /record/ pages. For ## efficiency this format should be pre-cached with BibReformat. See ## also CFG_WEBSEARCH_ENABLE_GOOGLESCHOLAR and ## CFG_WEBSEARCH_ENABLE_GOOGLESCHOLAR. CFG_WEBSEARCH_DETAILED_META_FORMAT = hdm ## CFG_WEBSEARCH_ENABLE_GOOGLESCHOLAR -- decides if meta tags for ## Google Scholar shall be included in the detailed record page ## header, when using the standard formatting templates/elements. See ## also CFG_WEBSEARCH_DETAILED_META_FORMAT and ## CFG_WEBSEARCH_ENABLE_OPENGRAPH. When this variable is changed and ## output format defined in CFG_WEBSEARCH_DETAILED_META_FORMAT is ## cached, a bibreformat must be run for the cached records. CFG_WEBSEARCH_ENABLE_GOOGLESCHOLAR = True ## CFG_WEBSEARCH_ENABLE_OPENGRAPH -- decides if meta tags for the Open ## Graph protocol shall be included in the detailed record page ## header, when using the standard formatting templates/elements. See ## also CFG_WEBSEARCH_DETAILED_META_FORMAT and ## CFG_WEBSEARCH_ENABLE_GOOGLESCHOLAR. When this variable is changed ## and output format defined in CFG_WEBSEARCH_DETAILED_META_FORMAT is ## cached, a bibreformat must be run for the cached records. Note that ## enabling Open Graph produces invalid XHTML/HTML5 markup. CFG_WEBSEARCH_ENABLE_OPENGRAPH = False ## CFG_WEBSEARCH_CITESUMMARY_SELFCITES_THRESHOLD -- switches off ## self-citations computation if the number records in the citesummary ## is above the threshold CFG_WEBSEARCH_CITESUMMARY_SELFCITES_THRESHOLD = 2000 ####################################### ## Part 4: BibHarvest OAI parameters ## ####################################### ## This part defines parameters for the Invenio OAI gateway. ## Useful if you are running Invenio as OAI data provider. ## CFG_OAI_ID_FIELD -- OAI identifier MARC field: CFG_OAI_ID_FIELD = 909COo ## CFG_OAI_SET_FIELD -- OAI set MARC field: CFG_OAI_SET_FIELD = 909COp ## CFG_OAI_SET_FIELD -- previous OAI set MARC field: CFG_OAI_PREVIOUS_SET_FIELD = 909COq ## CFG_OAI_DELETED_POLICY -- OAI deletedrecordspolicy ## (no/transient/persistent): CFG_OAI_DELETED_POLICY = persistent ## CFG_OAI_ID_PREFIX -- OAI identifier prefix: CFG_OAI_ID_PREFIX = atlantis.cern.ch ## CFG_OAI_SAMPLE_IDENTIFIER -- OAI sample identifier: CFG_OAI_SAMPLE_IDENTIFIER = oai:atlantis.cern.ch:123 ## CFG_OAI_IDENTIFY_DESCRIPTION -- description for the OAI Identify verb: CFG_OAI_IDENTIFY_DESCRIPTION = %(CFG_SITE_URL)s Free and unlimited use by anybody with obligation to refer to original record Full content, i.e. preprints may not be harvested by robots Submission restricted. Submitted documents are subject of approval by OAI repository admins. ## CFG_OAI_LOAD -- OAI number of records in a response: CFG_OAI_LOAD = 500 ## CFG_OAI_EXPIRE -- OAI resumptionToken expiration time: CFG_OAI_EXPIRE = 90000 ## CFG_OAI_SLEEP -- service unavailable between two consecutive ## requests for CFG_OAI_SLEEP seconds: CFG_OAI_SLEEP = 2 ## CFG_OAI_METADATA_FORMATS -- mapping between accepted metadataPrefixes and ## the corresponding output format to use, its schema and its metadataNamespace. CFG_OAI_METADATA_FORMATS = { 'marcxml': ('XOAIMARC', 'http://www.openarchives.org/OAI/1.1/dc.xsd', 'http://purl.org/dc/elements/1.1/'), 'oai_dc': ('XOAIDC', 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', 'http://www.loc.gov/MARC21/slim'), } ## CFG_OAI_FRIENDS -- list of OAI baseURL of friend repositories. See: ## CFG_OAI_FRIENDS = http://cds.cern.ch/oai2d,http://openaire.cern.ch/oai2d,http://export.arxiv.org/oai2 ## The following subfields are a completition to ## CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG. If CFG_OAI_PROVENANCE_BASEURL_SUBFIELD is ## set for a record, then the corresponding field is considered has being ## harvested via OAI-PMH ## CFG_OAI_PROVENANCE_BASEURL_SUBFIELD -- baseURL of the originDescription or a ## record CFG_OAI_PROVENANCE_BASEURL_SUBFIELD = u ## CFG_OAI_PROVENANCE_DATESTAMP_SUBFIELD -- datestamp of the originDescription ## or a record CFG_OAI_PROVENANCE_DATESTAMP_SUBFIELD = d ## CFG_OAI_PROVENANCE_METADATANAMESPACE_SUBFIELD -- metadataNamespace of the ## originDescription or a record CFG_OAI_PROVENANCE_METADATANAMESPACE_SUBFIELD = m ## CFG_OAI_PROVENANCE_ORIGINDESCRIPTION_SUBFIELD -- originDescription of the ## originDescription or a record CFG_OAI_PROVENANCE_ORIGINDESCRIPTION_SUBFIELD = d ## CFG_OAI_PROVENANCE_HARVESTDATE_SUBFIELD -- harvestDate of the ## originDescription or a record CFG_OAI_PROVENANCE_HARVESTDATE_SUBFIELD = h ## CFG_OAI_PROVENANCE_ALTERED_SUBFIELD -- altered flag of the ## originDescription or a record CFG_OAI_PROVENANCE_ALTERED_SUBFIELD = t ## CFG_OAI_FAILED_HARVESTING_STOP_QUEUE -- when harvesting OAI sources ## fails, shall we report an error with the task and stop BibSched ## queue, or simply wait for the next run of the task? A value of 0 ## will stop the task upon errors, 1 will let the queue run if the ## next run of the oaiharvest task can safely recover the failure ## (this means that the queue will stop if the task is not set to run ## periodically) CFG_OAI_FAILED_HARVESTING_STOP_QUEUE = 1 ## CFG_OAI_FAILED_HARVESTING_EMAILS_ADMIN -- when ## CFG_OAI_FAILED_HARVESTING_STOP_QUEUE is set to leave the queue ## running upon errors, shall we send an email to admin to notify ## about the failure? CFG_OAI_FAILED_HARVESTING_EMAILS_ADMIN = True ## NOTE: the following parameters are experimental ## ----------------------------------------------------------------------------- ## CFG_OAI_RIGHTS_FIELD -- MARC field dedicated to storing Copyright information CFG_OAI_RIGHTS_FIELD = 542__ ## CFG_OAI_RIGHTS_HOLDER_SUBFIELD -- MARC subfield dedicated to storing the ## Copyright holder information CFG_OAI_RIGHTS_HOLDER_SUBFIELD = d ## CFG_OAI_RIGHTS_DATE_SUBFIELD -- MARC subfield dedicated to storing the ## Copyright date information CFG_OAI_RIGHTS_DATE_SUBFIELD = g ## CFG_OAI_RIGHTS_URI_SUBFIELD -- MARC subfield dedicated to storing the URI ## (URL or URN, more detailed statement about copyright status) information CFG_OAI_RIGHTS_URI_SUBFIELD = u ## CFG_OAI_RIGHTS_CONTACT_SUBFIELD -- MARC subfield dedicated to storing the ## Copyright holder contact information CFG_OAI_RIGHTS_CONTACT_SUBFIELD = e ## CFG_OAI_RIGHTS_STATEMENT_SUBFIELD -- MARC subfield dedicated to storing the ## Copyright statement as presented on the resource CFG_OAI_RIGHTS_STATEMENT_SUBFIELD = f ## CFG_OAI_LICENSE_FIELD -- MARC field dedicated to storing terms governing ## use and reproduction (license) CFG_OAI_LICENSE_FIELD = 540__ ## CFG_OAI_LICENSE_TERMS_SUBFIELD -- MARC subfield dedicated to storing the ## Terms governing use and reproduction, e.g. CC License CFG_OAI_LICENSE_TERMS_SUBFIELD = a ## CFG_OAI_LICENSE_PUBLISHER_SUBFIELD -- MARC subfield dedicated to storing the ## person or institution imposing the license (author, publisher) CFG_OAI_LICENSE_PUBLISHER_SUBFIELD = b ## CFG_OAI_LICENSE_URI_SUBFIELD -- MARC subfield dedicated to storing the URI ## URI CFG_OAI_LICENSE_URI_SUBFIELD = u ##------------------------------------------------------------------------------ ################################### ## Part 5: BibDocFile parameters ## ################################### ## This section contains some configuration parameters for BibDocFile ## module. ## CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_DOCTYPES -- this is the list of ## doctypes (like 'Main' or 'Additional') and their description that admins ## can choose from when adding new files via the Document File Manager ## admin interface. ## - When no value is provided, admins cannot add new ## file (they can only revise/delete/add format) ## - When a single value is given, it is used as ## default doctype for all new documents ## ## Order is relevant ## Eg: ## [('main', 'Main document'), ('additional', 'Figure, schema. etc')] CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_DOCTYPES = [ ('Main', 'Main document'), ('LaTeX', 'LaTeX'), ('Source', 'Source'), ('Additional', 'Additional File'), ('Audio', 'Audio file'), ('Video', 'Video file'), ('Script', 'Script'), ('Data', 'Data'), ('Figure', 'Figure'), ('Schema', 'Schema'), ('Graph', 'Graph'), ('Image', 'Image'), ('Drawing', 'Drawing'), ('Slides', 'Slides')] ## CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_RESTRICTIONS -- this is the ## list of restrictions (like 'Restricted' or 'No Restriction') and their ## description that admins can choose from when adding or revising files. ## Restrictions can then be configured at the level of WebAccess. ## - When no value is provided, no restriction is ## applied ## - When a single value is given, it is used as ## default resctriction for all documents. ## - The first value of the list is used as default ## restriction if the user if not given the ## choice of the restriction. Order is relevant ## ## Eg: ## [('', 'No restriction'), ('restr', 'Restricted')] CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_RESTRICTIONS = [ ('', 'Public'), ('restricted', 'Restricted')] ## CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_MISC -- set here the other ## default flags and attributes to tune the Document File Manager admin ## interface. ## See the docstring of bibdocfile_managedocfiles.create_file_upload_interface ## to have a description of the available parameters and their syntax. ## In general you will rarely need to change this variable. CFG_BIBDOCFILE_DOCUMENT_FILE_MANAGER_MISC = { 'can_revise_doctypes': ['*'], 'can_comment_doctypes': ['*'], 'can_describe_doctypes': ['*'], 'can_delete_doctypes': ['*'], 'can_keep_doctypes': ['*'], 'can_rename_doctypes': ['*'], 'can_add_format_to_doctypes': ['*'], 'can_restrict_doctypes': ['*'], } ## CFG_BIBDOCFILE_FILESYSTEM_BIBDOC_GROUP_LIMIT -- the fulltext ## documents are stored under "/opt/invenio/var/data/files/gX/Y" ## directories where X is 0,1,... and Y stands for bibdoc ID. Thusly ## documents Y are grouped into directories X and this variable ## indicates the maximum number of documents Y stored in each ## directory X. This limit is imposed solely for filesystem ## performance reasons in order not to have too many subdirectories in ## a given directory. CFG_BIBDOCFILE_FILESYSTEM_BIBDOC_GROUP_LIMIT = 5000 ## CFG_BIBDOCFILE_ADDITIONAL_KNOWN_FILE_EXTENSIONS -- a comma-separated ## list of document extensions not listed in Python standard mimetype ## library that should be recognized by Invenio. CFG_BIBDOCFILE_ADDITIONAL_KNOWN_FILE_EXTENSIONS = hpg,link,lis,llb,mat,mpp,msg,docx,docm,xlsx,xlsm,xlsb,pptx,pptm,ppsx,ppsm ## CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES -- a mapping of additional ## mimetypes that could be served or have to be recognized by this instance ## of Invenio (this is useful in order to patch old versions of the ## mimetypes Python module). CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES = { "application/xml-dtd": ".dtd", } ## CFG_BIBDOCFILE_DESIRED_CONVERSIONS -- a dictionary having as keys ## a format and as values the corresponding list of desired converted ## formats. CFG_BIBDOCFILE_DESIRED_CONVERSIONS = { 'pdf' : ('pdf;pdfa', ), 'ps.gz' : ('pdf;pdfa', ), 'djvu' : ('pdf', ), 'sxw': ('doc', 'odt', 'pdf;pdfa', ), 'docx' : ('doc', 'odt', 'pdf;pdfa', ), 'doc' : ('odt', 'pdf;pdfa', 'docx'), 'rtf' : ('pdf;pdfa', 'odt', ), 'odt' : ('pdf;pdfa', 'doc', ), 'pptx' : ('ppt', 'odp', 'pdf;pdfa', ), 'ppt' : ('odp', 'pdf;pdfa', 'pptx'), 'sxi': ('odp', 'pdf;pdfa', ), 'odp' : ('pdf;pdfa', 'ppt', ), 'xlsx' : ('xls', 'ods', 'csv'), 'xls' : ('ods', 'csv'), 'ods' : ('xls', 'xlsx', 'csv'), 'sxc': ('xls', 'xlsx', 'csv'), 'tiff' : ('pdf;pdfa', ), 'tif' : ('pdf;pdfa', ),} ## CFG_BIBDOCFILE_USE_XSENDFILE -- if your web server supports ## XSendfile header, you may want to enable this feature in order for ## to Invenio tell the web server to stream files for download (after ## proper authorization checks) by web server's means. This helps to ## liberate Invenio worker processes from being busy with sending big ## files to clients. The web server will take care of that. Note: ## this feature is still somewhat experimental. Note: when enabled ## (set to 1), then you have to also regenerate Apache vhost conf ## snippets (inveniocfg --update-config-py --create-apache-conf). CFG_BIBDOCFILE_USE_XSENDFILE = 0 ## CFG_BIBDOCFILE_MD5_CHECK_PROBABILITY -- a number between 0 and ## 1 that indicates probability with which MD5 checksum will be ## verified when streaming bibdocfile-managed files. (0.1 will cause ## the check to be performed once for every 10 downloads) CFG_BIBDOCFILE_MD5_CHECK_PROBABILITY = 0.1 ## CFG_BIBDOCFILE_BEST_FORMATS_TO_EXTRACT_TEXT_FROM -- a comma-separated ## list of document extensions in decrescent order of preference ## to suggest what is considered the best format to extract text from. CFG_BIBDOCFILE_BEST_FORMATS_TO_EXTRACT_TEXT_FROM = ('txt', 'html', 'xml', 'odt', 'doc', 'docx', 'djvu', 'pdf', 'ps', 'ps.gz') ## CFG_BIBDOCFILE_ENABLE_BIBDOCFSINFO_CACHE -- whether to use the ## database table bibdocfsinfo as reference for filesystem ## information. The default is 0. Switch this to 1 ## after you have run bibdocfile --fix-bibdocfsinfo-cache ## or on an empty system. CFG_BIBDOCFILE_ENABLE_BIBDOCFSINFO_CACHE = 0 ## CFG_OPENOFFICE_SERVER_HOST -- the host where an OpenOffice Server is ## listening to. If localhost an OpenOffice server will be started ## automatically if it is not already running. ## Note: if you set this to an empty value this will disable the usage of ## OpenOffice for converting documents. ## If you set this to something different than localhost you'll have to take ## care to have an OpenOffice server running on the corresponding host and ## to install the same OpenOffice release both on the client and on the server ## side. ## In order to launch an OpenOffice server on a remote machine, just start ## the usual 'soffice' executable in this way: ## $> soffice -headless -nologo -nodefault -norestore -nofirststartwizard \ ## .. -accept=socket,host=HOST,port=PORT;urp;StarOffice.ComponentContext CFG_OPENOFFICE_SERVER_HOST = localhost ## CFG_OPENOFFICE_SERVER_PORT -- the port where an OpenOffice Server is ## listening to. CFG_OPENOFFICE_SERVER_PORT = 2002 ## CFG_OPENOFFICE_USER -- the user that will be used to launch the OpenOffice ## client. It is recommended to set this to a user who don't own files, like ## e.g. 'nobody'. You should also authorize your Apache server user to be ## able to become this user, e.g. by adding to your /etc/sudoers the following ## line: ## "apache ALL=(nobody) NOPASSWD: ALL" ## provided that apache is the username corresponding to the Apache user. ## On some machine this might be apache2 or www-data. CFG_OPENOFFICE_USER = nobody ################################# ## Part 6: BibIndex parameters ## ################################# ## This section contains some configuration parameters for BibIndex ## module. Please note that BibIndex is mostly configured on run-time ## via its BibIndex Admin web interface. The parameters below are the ## ones that you do not probably want to modify very often during the ## runtime. ## CFG_BIBINDEX_FULLTEXT_INDEX_LOCAL_FILES_ONLY -- when fulltext indexing, do ## you want to index locally stored files only, or also external URLs? ## Use "0" to say "no" and "1" to say "yes". CFG_BIBINDEX_FULLTEXT_INDEX_LOCAL_FILES_ONLY = 1 ## CFG_BIBINDEX_REMOVE_STOPWORDS -- when indexing, do we want to remove ## stopwords? Use "0" to say "no" and "1" to say "yes". CFG_BIBINDEX_REMOVE_STOPWORDS = 0 ## CFG_BIBINDEX_CHARS_ALPHANUMERIC_SEPARATORS -- characters considered as ## alphanumeric separators of word-blocks inside words. You probably ## don't want to change this. CFG_BIBINDEX_CHARS_ALPHANUMERIC_SEPARATORS = \!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\:\;\<\=\>\?\@\[\\\]\^\_\`\{\|\}\~ ## CFG_BIBINDEX_CHARS_PUNCTUATION -- characters considered as punctuation ## between word-blocks inside words. You probably don't want to ## change this. CFG_BIBINDEX_CHARS_PUNCTUATION = \.\,\:\;\?\!\" ## CFG_BIBINDEX_REMOVE_HTML_MARKUP -- should we attempt to remove HTML markup ## before indexing? Use 1 if you have HTML markup inside metadata ## (e.g. in abstracts), use 0 otherwise. CFG_BIBINDEX_REMOVE_HTML_MARKUP = 0 ## CFG_BIBINDEX_REMOVE_LATEX_MARKUP -- should we attempt to remove LATEX markup ## before indexing? Use 1 if you have LATEX markup inside metadata ## (e.g. in abstracts), use 0 otherwise. CFG_BIBINDEX_REMOVE_LATEX_MARKUP = 0 ## CFG_BIBINDEX_MIN_WORD_LENGTH -- minimum word length allowed to be added to ## index. The terms smaller then this amount will be discarded. ## Useful to keep the database clean, however you can safely leave ## this value on 0 for up to 1,000,000 documents. CFG_BIBINDEX_MIN_WORD_LENGTH = 0 ## CFG_BIBINDEX_URLOPENER_USERNAME and CFG_BIBINDEX_URLOPENER_PASSWORD -- ## access credentials to access restricted URLs, interesting only if ## you are fulltext-indexing files located on a remote server that is ## only available via username/password. But it's probably better to ## handle this case via IP or some convention; the current scheme is ## mostly there for demo only. CFG_BIBINDEX_URLOPENER_USERNAME = mysuperuser CFG_BIBINDEX_URLOPENER_PASSWORD = mysuperpass ## CFG_INTBITSET_ENABLE_SANITY_CHECKS -- ## Enable sanity checks for integers passed to the intbitset data ## structures. It is good to enable this during debugging ## and to disable this value for speed improvements. CFG_INTBITSET_ENABLE_SANITY_CHECKS = False ## CFG_BIBINDEX_PERFORM_OCR_ON_DOCNAMES -- regular expression that matches ## docnames for which OCR is desired (set this to .* in order to enable ## OCR in general, set this to empty in order to disable it.) CFG_BIBINDEX_PERFORM_OCR_ON_DOCNAMES = scan-.* ## CFG_BIBINDEX_SPLASH_PAGES -- key-value mapping where the key corresponds ## to a regular expression that matches the URLs of the splash pages of ## a given service and the value is a regular expression of the set of URLs ## referenced via tags in the HTML content of the splash pages that are ## referring to documents that need to be indexed. ## NOTE: for backward compatibility reasons you can set this to a simple ## regular expression that will directly be used as the unique key of the ## map, with corresponding value set to ".*" (in order to match any URL) CFG_BIBINDEX_SPLASH_PAGES = { "http://documents\.cern\.ch/setlink\?.*": ".*", "http://ilcagenda\.linearcollider\.org/subContributionDisplay\.py\?.*|http://ilcagenda\.linearcollider\.org/contributionDisplay\.py\?.*": "http://ilcagenda\.linearcollider\.org/getFile\.py/access\?.*|http://ilcagenda\.linearcollider\.org/materialDisplay\.py\?.*", } ## CFG_BIBINDEX_AUTHOR_WORD_INDEX_EXCLUDE_FIRST_NAMES -- do we want ## the author word index to exclude first names to keep only last ## names? If set to True, then for the author `Bernard, Denis', only ## `Bernard' will be indexed in the word index, not `Denis'. Note ## that if you change this variable, you have to re-index the author ## index via `bibindex -w author -R'. CFG_BIBINDEX_AUTHOR_WORD_INDEX_EXCLUDE_FIRST_NAMES = False ## CFG_BIBINDEX_SYNONYM_KBRS -- defines which knowledge bases are to ## be used for which index in order to provide index-time synonym ## lookup, and what massaging function should be used upon search ## pattern before performing the KB lookup. (Can be one of `exact', ## 'leading_to_comma', `leading_to_number'.) CFG_BIBINDEX_SYNONYM_KBRS = { 'global': ['INDEX-SYNONYM-TITLE', 'exact'], 'title': ['INDEX-SYNONYM-TITLE', 'exact'], } ####################################### ## Part 7: Access control parameters ## ####################################### ## This section contains some configuration parameters for the access ## control system. Please note that WebAccess is mostly configured on ## run-time via its WebAccess Admin web interface. The parameters ## below are the ones that you do not probably want to modify very ## often during the runtime. (If you do want to modify them during ## runtime, for example te deny access temporarily because of backups, ## you can edit access_control_config.py directly, no need to get back ## here and no need to redo the make process.) ## CFG_ACCESS_CONTROL_LEVEL_SITE -- defines how open this site is. ## Use 0 for normal operation of the site, 1 for read-only site (all ## write operations temporarily closed), 2 for site fully closed, ## 3 for also disabling any database connection. ## Useful for site maintenance. CFG_ACCESS_CONTROL_LEVEL_SITE = 0 ## CFG_ACCESS_CONTROL_LEVEL_GUESTS -- guest users access policy. Use ## 0 to allow guest users, 1 not to allow them (all users must login). CFG_ACCESS_CONTROL_LEVEL_GUESTS = 0 ## CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS -- account registration and ## activation policy. When 0, users can register and accounts are ## automatically activated. When 1, users can register but admin must ## activate the accounts. When 2, users cannot register nor update ## their email address, only admin can register accounts. When 3, ## users cannot register nor update email address nor password, only ## admin can register accounts. When 4, the same as 3 applies, nor ## user cannot change his login method. When 5, then the same as 4 ## applies, plus info about how to get an account is hidden from the ## login page. CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS = 0 ## CFG_ACCESS_CONTROL_LIMIT_REGISTRATION_TO_DOMAIN -- limit account ## registration to certain email addresses? If wanted, give domain ## name below, e.g. "cern.ch". If not wanted, leave it empty. CFG_ACCESS_CONTROL_LIMIT_REGISTRATION_TO_DOMAIN = ## CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS -- send a ## notification email to the administrator when a new account is ## created? Use 0 for no, 1 for yes. CFG_ACCESS_CONTROL_NOTIFY_ADMIN_ABOUT_NEW_ACCOUNTS = 0 ## CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT -- send a ## notification email to the user when a new account is created in order to ## to verify the validity of the provided email address? Use ## 0 for no, 1 for yes. CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_NEW_ACCOUNT = 1 ## CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION -- send a ## notification email to the user when a new account is activated? ## Use 0 for no, 1 for yes. CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_ACTIVATION = 0 ## CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION -- send a ## notification email to the user when a new account is deleted or ## account demand rejected? Use 0 for no, 1 for yes. CFG_ACCESS_CONTROL_NOTIFY_USER_ABOUT_DELETION = 0 ## CFG_APACHE_PASSWORD_FILE -- the file where Apache user credentials ## are stored. Must be an absolute pathname. If the value does not ## start by a slash, it is considered to be the filename of a file ## located under prefix/var/tmp directory. This is useful for the ## demo site testing purposes. For the production site, if you plan ## to restrict access to some collections based on the Apache user ## authentication mechanism, you should put here an absolute path to ## your Apache password file. CFG_APACHE_PASSWORD_FILE = demo-site-apache-user-passwords ## CFG_APACHE_GROUP_FILE -- the file where Apache user groups are ## defined. See the documentation of the preceding config variable. CFG_APACHE_GROUP_FILE = demo-site-apache-user-groups ################################### ## Part 8: WebSession parameters ## ################################### ## This section contains some configuration parameters for tweaking ## session handling. ## CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT -- number of days after which a session ## and the corresponding cookie is considered expired. CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT = 2 ## CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER -- number of days after which a session ## and the corresponding cookie is considered expired, when the user has ## requested to permanently stay logged in. CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER = 365 ## CFG_WEBSESSION_RESET_PASSWORD_EXPIRE_IN_DAYS -- when user requested ## a password reset, for how many days is the URL valid? CFG_WEBSESSION_RESET_PASSWORD_EXPIRE_IN_DAYS = 3 ## CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS -- when an account ## activation email was sent, for how many days is the URL valid? CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS = 3 ## CFG_WEBSESSION_NOT_CONFIRMED_EMAIL_ADDRESS_EXPIRE_IN_DAYS -- when ## user won't confirm his email address and not complete ## registeration, after how many days will it expire? CFG_WEBSESSION_NOT_CONFIRMED_EMAIL_ADDRESS_EXPIRE_IN_DAYS = 10 ## CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS -- when set to 1, the session ## system allocates the same uid=0 to all guests users regardless of where they ## come from. 0 allocate a unique uid to each guest. CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS = 0 ## CFG_WEBSESSION_IPADDR_CHECK_SKIP_BITS -- to prevent session cookie ## stealing, Invenio checks that the IP address of a connection is the ## same as that of the connection which created the initial session. ## This variable let you decide how many bits should be skipped during ## this check. Set this to 0 in order to enable full IP address ## checking. Set this to 32 in order to disable IP address checking. ## Intermediate values (say 8) let you have some degree of security so ## that you can trust your local network only while helping to solve ## issues related to outside clients that configured their browser to ## use a web proxy for HTTP connection but not for HTTPS, thus ## potentially having two different IP addresses. In general, if use ## HTTPS in order to serve authenticated content, you can safely set ## CFG_WEBSESSION_IPADDR_CHECK_SKIP_BITS to 32. CFG_WEBSESSION_IPADDR_CHECK_SKIP_BITS = 0 ################################ ## Part 9: BibRank parameters ## ################################ ## This section contains some configuration parameters for the ranking ## system. ## CFG_BIBRANK_SHOW_READING_STATS -- do we want to show reading ## similarity stats? ('People who viewed this page also viewed') CFG_BIBRANK_SHOW_READING_STATS = 1 ## CFG_BIBRANK_SHOW_DOWNLOAD_STATS -- do we want to show the download ## similarity stats? ('People who downloaded this document also ## downloaded') CFG_BIBRANK_SHOW_DOWNLOAD_STATS = 1 ## CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS -- do we want to show download ## history graph? (0=no | 1=classic/gnuplot | 2=flot) CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS = 1 ## CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS_CLIENT_IP_DISTRIBUTION -- do we ## want to show a graph representing the distribution of client IPs ## downloading given document? (0=no | 1=classic/gnuplot | 2=flot) CFG_BIBRANK_SHOW_DOWNLOAD_GRAPHS_CLIENT_IP_DISTRIBUTION = 0 ## CFG_BIBRANK_SHOW_CITATION_LINKS -- do we want to show the 'Cited ## by' links? (useful only when you have citations in the metadata) CFG_BIBRANK_SHOW_CITATION_LINKS = 1 ## CFG_BIBRANK_SHOW_CITATION_STATS -- de we want to show citation ## stats? ('Cited by M recors', 'Co-cited with N records') CFG_BIBRANK_SHOW_CITATION_STATS = 1 ## CFG_BIBRANK_SHOW_CITATION_GRAPHS -- do we want to show citation ## history graph? (0=no | 1=classic/gnuplot | 2=flot) CFG_BIBRANK_SHOW_CITATION_GRAPHS = 1 ## CFG_BIBRANK_SELFCITES_USE_BIBAUTHORID -- use authorids for computing ## self-citations ## falls back to hashing the author string CFG_BIBRANK_SELFCITES_USE_BIBAUTHORID = 0 ## CFG_BIBRANK_SELFCITES_PRECOMPUTE -- use precomputed self-citations ## when displaying itesummary. Precomputing citations allows use to ## speed up things CFG_BIBRANK_SELFCITES_PRECOMPUTE = 0 #################################### ## Part 10: WebComment parameters ## #################################### ## This section contains some configuration parameters for the ## commenting and reviewing facilities. ## CFG_WEBCOMMENT_ALLOW_COMMENTS -- do we want to allow users write ## public comments on records? CFG_WEBCOMMENT_ALLOW_COMMENTS = 1 ## CFG_WEBCOMMENT_ALLOW_REVIEWS -- do we want to allow users write ## public reviews of records? CFG_WEBCOMMENT_ALLOW_REVIEWS = 1 ## CFG_WEBCOMMENT_ALLOW_SHORT_REVIEWS -- do we want to allow short ## reviews, that is just the attribution of stars without submitting ## detailed review text? CFG_WEBCOMMENT_ALLOW_SHORT_REVIEWS = 0 ## CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN -- if users ## report a comment to be abusive, how many they have to be before the ## site admin is alerted? CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN = 5 ## CFG_WEBCOMMENT_NB_COMMENTS_IN_DETAILED_VIEW -- how many comments do ## we display in the detailed record page upon welcome? CFG_WEBCOMMENT_NB_COMMENTS_IN_DETAILED_VIEW = 1 ## CFG_WEBCOMMENT_NB_REVIEWS_IN_DETAILED_VIEW -- how many reviews do ## we display in the detailed record page upon welcome? CFG_WEBCOMMENT_NB_REVIEWS_IN_DETAILED_VIEW = 1 ## CFG_WEBCOMMENT_ADMIN_NOTIFICATION_LEVEL -- do we notify the site ## admin after every comment? CFG_WEBCOMMENT_ADMIN_NOTIFICATION_LEVEL = 1 ## CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_COMMENTS_IN_SECONDS -- how many ## elapsed seconds do we consider enough when checking for possible ## multiple comment submissions by a user? CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_COMMENTS_IN_SECONDS = 20 ## CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_REVIEWS_IN_SECONDS -- how many ## elapsed seconds do we consider enough when checking for possible ## multiple review submissions by a user? CFG_WEBCOMMENT_TIMELIMIT_PROCESSING_REVIEWS_IN_SECONDS = 20 ## CFG_WEBCOMMENT_USE_RICH_EDITOR -- enable the WYSIWYG ## Javascript-based editor when user edits comments? CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR = False ## CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL -- the email address from which the ## alert emails will appear to be sent: CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL = info@invenio-software.org ## CFG_WEBCOMMENT_DEFAULT_MODERATOR -- if no rules are ## specified to indicate who is the comment moderator of ## a collection, this person will be used as default CFG_WEBCOMMENT_DEFAULT_MODERATOR = info@invenio-software.org ## CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS -- do we want to allow the use ## of MathJax plugin to render latex input in comments? CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS = 1 ## CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION -- allow comment author to ## delete its own comment? CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION = 1 # CFG_WEBCOMMENT_EMAIL_REPLIES_TO -- which field of the record define # email addresses that should be notified of newly submitted comments, # and for which collection. Use collection names as keys, and list of # tags as values CFG_WEBCOMMENT_EMAIL_REPLIES_TO = { 'Articles': ['506__d', '506__m'], } # CFG_WEBCOMMENT_RESTRICTION_DATAFIELD -- which field of the record # define the restriction (must be linked to WebAccess # 'viewrestrcomment') to apply to newly submitted comments, and for # which collection. Use collection names as keys, and one tag as value CFG_WEBCOMMENT_RESTRICTION_DATAFIELD = { 'Articles': '5061_a', 'Pictures': '5061_a', 'Theses': '5061_a', } # CFG_WEBCOMMENT_ROUND_DATAFIELD -- which field of the record define # the current round of comment for which collection. Use collection # name as key, and one tag as value CFG_WEBCOMMENT_ROUND_DATAFIELD = { 'Articles': '562__c', 'Pictures': '562__c', } # CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE -- max file size per attached # file, in bytes. Choose 0 if you don't want to limit the size CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE = 5242880 # CFG_WEBCOMMENT_MAX_ATTACHED_FILES -- maxium number of files that can # be attached per comment. Choose 0 if you don't want to limit the # number of files. File uploads can be restricted with action # "attachcommentfile". CFG_WEBCOMMENT_MAX_ATTACHED_FILES = 5 # CFG_WEBCOMMENT_MAX_COMMENT_THREAD_DEPTH -- how many levels of # indentation discussions can be. This can be used to ensure that # discussions will not go into deep levels of nesting if users don't # understand the difference between "reply to comment" and "add # comment". When the depth is reached, any "reply to comment" is # conceptually converted to a "reply to thread" (i.e. reply to this # parent's comment). Use -1 for no limit, 0 for unthreaded (flat) # discussions. CFG_WEBCOMMENT_MAX_COMMENT_THREAD_DEPTH = 1 ################################## ## Part 11: BibSched parameters ## ################################## ## This section contains some configuration parameters for the ## bibliographic task scheduler. ## CFG_BIBSCHED_REFRESHTIME -- how often do we want to refresh ## bibsched monitor? (in seconds) CFG_BIBSCHED_REFRESHTIME = 5 ## CFG_BIBSCHED_LOG_PAGER -- what pager to use to view bibsched task ## logs? CFG_BIBSCHED_LOG_PAGER = /usr/bin/less ## CFG_BIBSCHED_EDITOR -- what editor to use to edit the marcxml ## code of the locked records CFG_BIBSCHED_EDITOR = /usr/bin/vim ## CFG_BIBSCHED_GC_TASKS_OLDER_THAN -- after how many days to perform the ## gargbage collector of BibSched queue (i.e. removing/moving task to archive). CFG_BIBSCHED_GC_TASKS_OLDER_THAN = 30 ## CFG_BIBSCHED_GC_TASKS_TO_REMOVE -- list of BibTask that can be safely ## removed from the BibSched queue once they are DONE. CFG_BIBSCHED_GC_TASKS_TO_REMOVE = bibindex,bibreformat,webcoll,bibrank,inveniogc ## CFG_BIBSCHED_GC_TASKS_TO_ARCHIVE -- list of BibTasks that should be safely ## archived out of the BibSched queue once they are DONE. CFG_BIBSCHED_GC_TASKS_TO_ARCHIVE = bibupload,oairepositoryupdater ## CFG_BIBSCHED_MAX_NUMBER_CONCURRENT_TASKS -- maximum number of BibTasks ## that can run concurrently. ## NOTE: concurrent tasks are still considered as an experimental ## feature. Please keep this value set to 1 on production environments. CFG_BIBSCHED_MAX_NUMBER_CONCURRENT_TASKS = 1 ## CFG_BIBSCHED_PROCESS_USER -- bibsched and bibtask processes must ## usually run under the same identity as the Apache web server ## process in order to share proper file read/write privileges. If ## you want to force some other bibsched/bibtask user, e.g. because ## you are using a local `invenio' user that belongs to your ## `www-data' Apache user group and so shares writing rights with your ## Apache web server process in this way, then please set its username ## identity here. Otherwise we shall check whether your ## bibsched/bibtask processes are run under the same identity as your ## Apache web server process (in which case you can leave the default ## empty value here). CFG_BIBSCHED_PROCESS_USER = ## CFG_BIBSCHED_NODE_TASKS -- specific nodes may be configured to ## run only specific tasks; if you want this, then this variable is a ## dictionary of the form {'hostname1': ['task1', 'task2']}. The ## default is that any node can run any task. CFG_BIBSCHED_NODE_TASKS = {} ## CFG_BIBSCHED_MAX_ARCHIVED_ROWS_DISPLAY -- number of tasks displayed ## CFG_BIBSCHED_MAX_ARCHIVED_ROWS_DISPLAY = 500 ################################### ## Part 12: WebBasket parameters ## ################################### ## CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS -- a safety limit for ## a maximum number of displayed baskets CFG_WEBBASKET_MAX_NUMBER_OF_DISPLAYED_BASKETS = 20 ## CFG_WEBBASKET_USE_RICH_TEXT_EDITOR -- enable the WYSIWYG ## Javascript-based editor when user edits comments in WebBasket? CFG_WEBBASKET_USE_RICH_TEXT_EDITOR = False ################################## ## Part 13: WebAlert parameters ## ################################## ## This section contains some configuration parameters for the ## automatic email notification alert system. ## CFG_WEBALERT_ALERT_ENGINE_EMAIL -- the email address from which the ## alert emails will appear to be sent: CFG_WEBALERT_ALERT_ENGINE_EMAIL = info@invenio-software.org ## CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL -- how many records ## at most do we send in an outgoing alert email? CFG_WEBALERT_MAX_NUM_OF_RECORDS_IN_ALERT_EMAIL = 20 ## CFG_WEBALERT_MAX_NUM_OF_CHARS_PER_LINE_IN_ALERT_EMAIL -- number of ## chars per line in an outgoing alert email? CFG_WEBALERT_MAX_NUM_OF_CHARS_PER_LINE_IN_ALERT_EMAIL = 72 ## CFG_WEBALERT_SEND_EMAIL_NUMBER_OF_TRIES -- when sending alert ## emails fails, how many times we retry? CFG_WEBALERT_SEND_EMAIL_NUMBER_OF_TRIES = 3 ## CFG_WEBALERT_SEND_EMAIL_SLEEPTIME_BETWEEN_TRIES -- when sending ## alert emails fails, what is the sleeptime between tries? (in ## seconds) CFG_WEBALERT_SEND_EMAIL_SLEEPTIME_BETWEEN_TRIES = 300 #################################### ## Part 14: WebMessage parameters ## #################################### ## CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE -- how large web messages do we ## allow? CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE = 20000 ## CFG_WEBMESSAGE_MAX_NB_OF_MESSAGES -- how many messages for a ## regular user do we allow in its inbox? CFG_WEBMESSAGE_MAX_NB_OF_MESSAGES = 30 ## CFG_WEBMESSAGE_DAYS_BEFORE_DELETE_ORPHANS -- how many days before ## we delete orphaned messages? CFG_WEBMESSAGE_DAYS_BEFORE_DELETE_ORPHANS = 60 ################################## ## Part 15: MiscUtil parameters ## ################################## ## CFG_MISCUTIL_SQL_USE_SQLALCHEMY -- whether to use SQLAlchemy.pool ## in the DB engine of Invenio. It is okay to enable this flag ## even if you have not installed SQLAlchemy. Note that Invenio will ## loose some perfomance if this option is enabled. CFG_MISCUTIL_SQL_USE_SQLALCHEMY = False ## CFG_MISCUTIL_SQL_RUN_SQL_MANY_LIMIT -- how many queries can we run ## inside run_sql_many() in one SQL statement? The limit value ## depends on MySQL's max_allowed_packet configuration. CFG_MISCUTIL_SQL_RUN_SQL_MANY_LIMIT = 10000 ## CFG_MISCUTIL_SMTP_HOST -- which server to use as outgoing mail server to ## send outgoing emails generated by the system, for example concerning ## submissions or email notification alerts. CFG_MISCUTIL_SMTP_HOST = localhost ## CFG_MISCUTIL_SMTP_PORT -- which port to use on the outgoing mail server ## defined in the previous step. CFG_MISCUTIL_SMTP_PORT = 25 ## CFG_MISCUTIL_SMTP_USER -- which username to use on the outgoing mail server ## defined in CFG_MISCUTIL_SMTP_HOST. If either CFG_MISCUTIL_SMTP_USER or ## CFG_MISCUTIL_SMTP_PASS are empty Invenio won't attempt authentication. CFG_MISCUTIL_SMTP_USER = ## CFG_MISCUTIL_SMTP_PASS -- which password to use on the outgoing mail ## server defined in CFG_MISCUTIL_SMTP_HOST. If either CFG_MISCUTIL_SMTP_USER ## or CFG_MISCUTIL_SMTP_PASS are empty Invenio won't attempt authentication. CFG_MISCUTIL_SMTP_PASS = ## CFG_MISCUTIL_SMTP_TLS -- whether to use a TLS (secure) connection when ## talking to the SMTP server defined in CFG_MISCUTIL_SMTP_HOST. CFG_MISCUTIL_SMTP_TLS = False ## CFG_MISCUTILS_DEFAULT_PROCESS_TIMEOUT -- the default number of seconds after ## which a process launched trough shellutils.run_process_with_timeout will ## be killed. This is useful to catch runaway processes. CFG_MISCUTIL_DEFAULT_PROCESS_TIMEOUT = 300 ## CFG_MATHJAX_HOSTING -- if you plan to use MathJax to display TeX ## formulas on HTML web pages, you can specify whether you wish to use ## 'local' hosting or 'cdn' hosting of MathJax libraries. (If set to ## 'local', you have to run 'make install-mathjax-plugin' as described ## in the INSTALL guide.) If set to 'local', users will use your site ## to download MathJax sources. If set to 'cdn', users will use ## centralized MathJax CDN servers instead. Please note that using ## CDN is suitable only for small institutions or for MathJax ## sponsors; see the MathJax website for more details. (Also, please ## note that if you plan to use MathJax on your site, you have to ## adapt CFG_WEBSEARCH_USE_MATHJAX_FOR_FORMATS and ## CFG_WEBCOMMENT_USE_MATHJAX_IN_COMMENTS configuration variables ## elsewhere in this file.) CFG_MATHJAX_HOSTING = local ################################# ## Part 16: BibEdit parameters ## ################################# ## CFG_BIBEDIT_TIMEOUT -- when a user edits a record, this record is ## locked to prevent other users to edit it at the same time. ## How many seconds of inactivity before the locked record again will be free ## for other people to edit? CFG_BIBEDIT_TIMEOUT = 3600 ## CFG_BIBEDIT_LOCKLEVEL -- when a user tries to edit a record which there ## is a pending bibupload task for in the queue, this shouldn't be permitted. ## The lock level determines how thouroughly the queue should be investigated ## to determine if this is the case. ## Level 0 - always permits editing, doesn't look at the queue ## (unsafe, use only if you know what you are doing) ## Level 1 - permits editing if there are no queued bibedit tasks for this record ## (safe with respect to bibedit, but not for other bibupload maintenance jobs) ## Level 2 - permits editing if there are no queued bibupload tasks of any sort ## (safe, but may lock more than necessary if many cataloguers around) ## Level 3 - permits editing if no queued bibupload task concerns given record ## (safe, most precise locking, but slow, ## checks for 001/EXTERNAL_SYSNO_TAG/EXTERNAL_OAIID_TAG) ## The recommended level is 3 (default) or 2 (if you use maintenance jobs often). CFG_BIBEDIT_LOCKLEVEL = 3 ## CFG_BIBEDIT_PROTECTED_FIELDS -- a comma-separated list of fields that BibEdit ## will not allow to be added, edited or deleted. Wildcards are not supported, ## but conceptually a wildcard is added at the end of every field specification. ## Examples: ## 500A - protect all MARC fields with tag 500 and first indicator A ## 5 - protect all MARC fields in the 500-series. ## 909C_a - protect subfield a in tag 909 with first indicator C and empty ## second indicator ## Note that 001 is protected by default, but if protection of other ## identifiers or automated fields is a requirement, they should be added to ## this list. CFG_BIBEDIT_PROTECTED_FIELDS = ## CFG_BIBEDIT_QUEUE_CHECK_METHOD -- how do we want to check for ## possible queue locking situations to prevent cataloguers from ## editing a record that may be waiting in the queue? Use 'bibrecord' ## for exact checking (always works, but may be slow), use 'regexp' ## for regular expression based checking (very fast, but may be ## inaccurate). When unsure, use 'bibrecord'. CFG_BIBEDIT_QUEUE_CHECK_METHOD = bibrecord ## CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE -- a dictionary ## containing which collections will be extended with a given template ## while being displayed in BibEdit UI. The collection corresponds with ## the value written in field 980 CFG_BIBEDIT_EXTEND_RECORD_WITH_COLLECTION_TEMPLATE = { 'POETRY' : 'record_poem'} ## CFG_BIBEDIT_KB_SUBJECTS - Name of the KB used in the field 65017a ## to automatically convert codes into extended version. e.g ## a - Astrophysics CFG_BIBEDIT_KB_SUBJECTS = Subjects ## CFG_BIBEDIT_KB_INSTITUTIONS - Name of the KB used for institution ## autocomplete. To be applied in fields defined in ## CFG_BIBEDIT_AUTOCOMPLETE_INSTITUTIONS_FIELDS CFG_BIBEDIT_KB_INSTITUTIONS = InstitutionsCollection ## CFG_BIBEDIT_AUTOCOMPLETE_INSTITUTIONS_FIELDS - list of fields to ## be autocompleted with the KB CFG_BIBEDIT_KB_INSTITUTIONS CFG_BIBEDIT_AUTOCOMPLETE_INSTITUTIONS_FIELDS = 100__u,700__u,701__u,502__c ## CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING -- maximum number of records ## that can be modified instantly using the multi-record editor. Above ## this limit, modifications will only be executed in limited hours. CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING = 2000 ## CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING -- maximum number of records ## that can be send for modification without having a superadmin role. ## If the number of records is between CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING ## and this number, the modifications will take place only in limited hours. CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING = 20000 ## CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME -- Allowed time to ## execute modifications on records, when the number exceeds ## CFG_BIBEDITMULTI_LIMIT_INSTANT_PROCESSING. CFG_BIBEDITMULTI_LIMIT_DELAYED_PROCESSING_TIME = 22:00-05:00 ################################### ## Part 17: BibUpload parameters ## ################################### ## CFG_BIBUPLOAD_REFERENCE_TAG -- where do we store references? CFG_BIBUPLOAD_REFERENCE_TAG = 999 ## CFG_BIBUPLOAD_EXTERNAL_SYSNO_TAG -- where do we store external ## system numbers? Useful for matching when our records come from an ## external digital library system. CFG_BIBUPLOAD_EXTERNAL_SYSNO_TAG = 970__a ## CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG -- where do we store OAI ID tags ## of harvested records? Useful for matching when we harvest stuff ## via OAI that we do not want to reexport via Invenio OAI; so records ## may have only the source OAI ID stored in this tag (kind of like ## external system number too). CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG = 035__a ## CFG_BIBUPLOAD_EXTERNAL_OAIID_PROVENANCE_TAG -- where do we store OAI SRC ## tags of harvested records? Useful for matching when we harvest stuff ## via OAI that we do not want to reexport via Invenio OAI; so records ## may have only the source OAI SRC stored in this tag (kind of like ## external system number too). Note that the field should be the same of ## CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG. CFG_BIBUPLOAD_EXTERNAL_OAIID_PROVENANCE_TAG = 035__9 ## CFG_BIBUPLOAD_STRONG_TAGS -- a comma-separated list of tags that ## are strong enough to resist the replace mode. Useful for tags that ## might be created from an external non-metadata-like source, ## e.g. the information about the number of copies left. CFG_BIBUPLOAD_STRONG_TAGS = 964 ## CFG_BIBUPLOAD_CONTROLLED_PROVENANCE_TAGS -- a comma-separated list ## of tags that contain provenance information that should be checked ## in the bibupload correct mode via matching provenance codes. (Only ## field instances of the same provenance information would be acted ## upon.) Please specify the whole tag info up to subfield codes. CFG_BIBUPLOAD_CONTROLLED_PROVENANCE_TAGS = 6531_9 ## CFG_BIBUPLOAD_FFT_ALLOWED_LOCAL_PATHS -- a comma-separated list of system ## paths from which it is allowed to take fulltextes that will be uploaded via ## FFT (CFG_TMPDIR is included by default). CFG_BIBUPLOAD_FFT_ALLOWED_LOCAL_PATHS = /tmp,/home ## CFG_BIBUPLOAD_FFT_ALLOWED_EXTERNAL_URLS -- a dictionary containing ## external URLs that can be accessed by Invenio and specific HTTP ## headers that will be used for each URL. The keys of the dictionary ## are regular expressions matching a set of URLs, the values are ## dictionaries of headers as consumed by urllib2.Request. If a ## regular expression matching all URLs is created at the end of the ## list, it means that Invenio will download all URLs. Otherwise ## Invenio will just download authorized URLs. Note: by default, a ## User-Agent built after the current Invenio version, site name, and ## site URL will be used. The values of the header dictionary can ## also contain a call to a python function, in the form of a ## disctionary with two entries: the name of the function to be called ## as a value for the 'fnc' key, and the arguments to this function, ## as a value for the 'args' key (in the form of a dictionary). ## CFG_BIBUPLOAD_FFT_ALLOWED_EXTERNAL_URLS = [ ## ('http://myurl.com/.*', {'User-Agent': 'Me'}), ## ('http://yoururl.com/.*', {'User-Agent': 'You', 'Accept': 'text/plain'}), ## ('http://thisurl.com/.*', {'Cookie': {'fnc':'read_cookie', 'args':{'cookiefile':'/tmp/cookies.txt'}}}) ## ('http://.*', {'User-Agent': 'Invenio'}), ## ] CFG_BIBUPLOAD_FFT_ALLOWED_EXTERNAL_URLS = [ ('http(s)?://.*', {}), ] ## CFG_BIBUPLOAD_SERIALIZE_RECORD_STRUCTURE -- do we want to serialize ## internal representation of records (Pythonic record structure) into ## the database? This can improve internal processing speed of some ## operations at the price of somewhat bigger disk space usage. ## If you change this value after some records have already been added ## to your installation, you may want to run: ## $ /opt/invenio/bin/inveniocfg --reset-recstruct-cache ## in order to either erase the cache thus freeing database space, ## or to fill the cache for all records that have not been cached yet. CFG_BIBUPLOAD_SERIALIZE_RECORD_STRUCTURE = 1 ## CFG_BIBUPLOAD_DELETE_FORMATS -- which formats do we want bibupload ## to delete when a record is ingested? Enter comma-separated list of ## formats. For example, 'hb,hd' will delete pre-formatted HTML brief ## and defailed formats from cache, so that search engine will ## generate them on-the-fly. Useful to always present latest data of ## records upon record display, until the periodical bibreformat job ## runs next and updates the cache. CFG_BIBUPLOAD_DELETE_FORMATS = hb ## CFG_BATCHUPLOADER_FILENAME_MATCHING_POLICY -- a comma-separated list ## indicating which fields match the file names of the documents to be ## uploaded. ## The matching will be done in the same order as the list provided. CFG_BATCHUPLOADER_FILENAME_MATCHING_POLICY = reportnumber,recid ## CFG_BATCHUPLOADER_DAEMON_DIR -- Directory where the batchuploader daemon ## will look for the subfolders metadata and document by default. ## If path is relative, CFG_PREFIX will be joined as a prefix CFG_BATCHUPLOADER_DAEMON_DIR = var/batchupload ## CFG_BATCHUPLOADER_WEB_ROBOT_AGENTS -- Regular expression to specify the ## agents permitted when calling batch uploader web interface ## cds.cern.ch/batchuploader/robotupload ## if using a curl, eg: curl xxx -A invenio CFG_BATCHUPLOADER_WEB_ROBOT_AGENTS = invenio_webupload|Invenio-.* ## CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS -- Access list specifying for each ## IP address, which collections are allowed using batch uploader robot ## interface. CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS = { '127.0.0.1': ['*'], # useful for testing '127.0.1.1': ['*'], # useful for testing '10.0.0.1': ['BOOK', 'REPORT'], # Example 1 '10.0.0.2': ['POETRY', 'PREPRINT'], # Example 2 } #################################### ## Part 18: BibCatalog parameters ## #################################### ## CFG_BIBCATALOG_SYSTEM -- set desired catalog system. For example, RT. CFG_BIBCATALOG_SYSTEM = ## RT CONFIGURATION ## CFG_BIBCATALOG_SYSTEM_RT_CLI -- path to the RT CLI client CFG_BIBCATALOG_SYSTEM_RT_CLI = /usr/bin/rt ## CFG_BIBCATALOG_SYSTEM_RT_URL -- Base URL of the remote RT system CFG_BIBCATALOG_SYSTEM_RT_URL = http://localhost/rt3 ## CFG_BIBCATALOG_SYSTEM_RT_DEFAULT_USER -- Set the username for a default RT account ## on remote system, with limited privileges, in order to only create and modify own tickets. CFG_BIBCATALOG_SYSTEM_RT_DEFAULT_USER = ## CFG_BIBCATALOG_SYSTEM_RT_DEFAULT_PWD -- Set the password for the default RT account ## on remote system. CFG_BIBCATALOG_SYSTEM_RT_DEFAULT_PWD = #################################### ## Part 19: BibFormat parameters ## #################################### ## CFG_BIBFORMAT_HIDDEN_TAGS -- comma-separated list of MARC tags that ## are not shown to users not having cataloging authorizations. CFG_BIBFORMAT_HIDDEN_TAGS = 595 ## CFG_BIBFORMAT_HIDDEN_FILE_FORMATS -- comma-separated list of file formats ## that are not shown explicitly to user not having cataloging authorizations. ## e.g. pdf;pdfa,xml CFG_BIBFORMAT_HIDDEN_FILE_FORMATS = ## CFG_BIBFORMAT_ADDTHIS_ID -- if you want to use the AddThis service from ## , set this value to the pubid parameter as ## provided by the service (e.g. ra-4ff80aae118f4dad), and add a call to ## formatting element in your formats, for example ## Default_HTML_detailed.bft. CFG_BIBFORMAT_ADDTHIS_ID = ## CFG_BIBFORMAT_DISABLE_I18N_FOR_CACHED_FORMATS -- For each output ## format BibReformat currently creates a cache for only one language ## (CFG_SITE_LANG) per record. This means that visitors having set a ## different language than CFG_SITE_LANG will be served an on-the-fly ## output using the language of their choice. You can disable this ## behaviour by specifying below for which output format you would ## like to force the cache to be used whatever language is ## requested. If your format templates do not provide ## internationalization, you can optimize your site by setting for ## eg. hb,hd to always serve the precached output (if it exists) in ## the CFG_SITE_LANG CFG_BIBFORMAT_DISABLE_I18N_FOR_CACHED_FORMATS = #################################### ## Part 20: BibMatch parameters ## #################################### ## CFG_BIBMATCH_LOCAL_SLEEPTIME -- Determines the amount of seconds to sleep ## between search queries on LOCAL system. CFG_BIBMATCH_LOCAL_SLEEPTIME = 0.0 ## CFG_BIBMATCH_REMOTE_SLEEPTIME -- Determines the amount of seconds to sleep ## between search queries on REMOTE systems. CFG_BIBMATCH_REMOTE_SLEEPTIME = 2.0 ## CFG_BIBMATCH_FUZZY_WORDLIMITS -- Determines the amount of words to extract ## from a certain fields value during fuzzy matching mode. Add/change field ## and appropriate number to the dictionary to configure this. CFG_BIBMATCH_FUZZY_WORDLIMITS = { '100__a': 2, '245__a': 4 } ## CFG_BIBMATCH_FUZZY_EMPTY_RESULT_LIMIT -- Determines the amount of empty results ## to accept during fuzzy matching mode. CFG_BIBMATCH_FUZZY_EMPTY_RESULT_LIMIT = 1 ## CFG_BIBMATCH_QUERY_TEMPLATES -- Here you can set the various predefined querystrings ## used to standardize common matching queries. By default the following templates ## are given: ## title - standard title search. Taken from 245__a (default) ## title-author - title and author search (i.e. this is a title AND author a) ## Taken from 245__a and 100__a ## reportnumber - reportnumber search (i.e. reportnumber:REP-NO-123). CFG_BIBMATCH_QUERY_TEMPLATES = { 'title' : '[title]', 'title-author' : '[title] [author]', 'reportnumber' : 'reportnumber:[reportnumber]' } ## CFG_BIBMATCH_MATCH_VALIDATION_RULESETS -- Here you can define the various rulesets for ## validating search results done by BibMatch. Each ruleset contains a certain pattern mapped ## to a tuple defining a "matching-strategy". ## ## The rule-definitions must come in two parts: ## ## * The first part is a string containing a regular expression ## that is matched against the textmarc representation of each record. ## If a match is found, the final rule-set is updated with ## the given "sub rule-set", where identical tag rules are replaced. ## ## * The second item is a list of key->value mappings (dict) that indicates specific ## strategy parameters with corresponding validation rules. ## ## This strategy consists of five items: ## ## * MARC TAGS: ## These MARC tags represents the fields taken from original record and any records from search ## results. When several MARC tags are specified with a given match-strategy, all the fields ## associated with these tags are matched together (i.e. with key "100__a,700__a", all 100__a ## and 700__a fields are matched together. Which is useful when first-author can vary for ## certain records on different systems). ## ## * COMPARISON THRESHOLD: ## a value between 0.0 and 1.0 specifying the threshold for string matches ## to determine if it is a match or not (using normalized string-distance). ## Normally 0.8 (80% match) is considered to be a close match. ## ## * COMPARISON MODE: ## the parse mode decides how the record datafields are compared: ## - 'strict' : all (sub-)fields are compared, and all must match. Order is significant. ## - 'normal' : all (sub-)fields are compared, and all must match. Order is ignored. ## - 'lazy' : all (sub-)fields are compared with each other and at least one must match ## - 'ignored': the tag is ignored in the match. Used to disable previously defined rules. ## ## * MATCHING MODE: ## the comparison mode decides how the fieldvalues are matched: ## - 'title' : uses a method specialized for comparing titles, e.g. looking for subtitles ## - 'author' : uses a special authorname comparison. Will take initials into account. ## - 'identifier' : special matching for identifiers, stripping away punctuation ## - 'date': matches dates by extracting and comparing the year ## - 'normal': normal string comparison. ## Note: Fields are considered matching when all its subfields or values match. ## ## * RESULT MODE: ## the result mode decides how the results from the comparisons are handled further: ## - 'normal' : a failed match will cause the validation to immediately exit as a failure. ## a successful match will cause the validation to continue on other rules (if any) ## - 'final' : a failed match will cause the validation to immediately exit as a failure. ## a successful match will cause validation to immediately exit as a success. ## - 'joker' : a failed match will cause the validation to continue on other rules (if any). ## a successful match will cause validation to immediately exit as a success. ## ## You can add your own rulesets in the dictionary below. The 'default' ruleset is always applied, ## and should therefore NOT be removed, but can be changed. The tag-rules can also be overwritten ## by other rulesets. ## ## WARNING: Beware that the validation quality is only as good as given rules, so matching results ## are never guaranteed to be accurate, as it is very content-specific. CFG_BIBMATCH_MATCH_VALIDATION_RULESETS = [('default', [{ 'tags' : '245__%,242__%', 'threshold' : 0.8, 'compare_mode' : 'lazy', 'match_mode' : 'title', 'result_mode' : 'normal' }, { 'tags' : '037__a,088__a', 'threshold' : 1.0, 'compare_mode' : 'lazy', 'match_mode' : 'identifier', 'result_mode' : 'final' }, { 'tags' : '100__a,700__a', 'threshold' : 0.8, 'compare_mode' : 'normal', 'match_mode' : 'author', 'result_mode' : 'normal' }, { 'tags' : '773__a', 'threshold' : 1.0, 'compare_mode' : 'lazy', 'match_mode' : 'title', 'result_mode' : 'normal' }]), ('980__ \$\$a(THESIS|Thesis)', [{ 'tags' : '100__a', 'threshold' : 0.8, 'compare_mode' : 'strict', 'match_mode' : 'author', 'result_mode' : 'normal' }, { 'tags' : '700__a,701__a', 'threshold' : 1.0, 'compare_mode' : 'lazy', 'match_mode' : 'author', 'result_mode' : 'normal' }, { 'tags' : '100__a,700__a', 'threshold' : 0.8, 'compare_mode' : 'ignored', 'match_mode' : 'author', 'result_mode' : 'normal' }]), ('260__', [{ 'tags' : '260__c', 'threshold' : 0.8, 'compare_mode' : 'lazy', 'match_mode' : 'date', 'result_mode' : 'normal' }]), ('0247_', [{ 'tags' : '0247_a', 'threshold' : 1.0, 'compare_mode' : 'lazy', 'match_mode' : 'identifier', 'result_mode' : 'final' }]), ('020__', [{ 'tags' : '020__a', 'threshold' : 1.0, 'compare_mode' : 'lazy', 'match_mode' : 'identifier', 'result_mode' : 'joker' }]) ] ## CFG_BIBMATCH_FUZZY_MATCH_VALIDATION_LIMIT -- Determines the minimum percentage of the ## amount of rules to be positively matched when comparing two records. Should the number ## of matches be lower than required matches but equal to or above this limit, ## the match will be considered fuzzy. CFG_BIBMATCH_FUZZY_MATCH_VALIDATION_LIMIT = 0.65 ## CFG_BIBMATCH_SEARCH_RESULT_MATCH_LIMIT -- Determines the maximum amount of search results ## a single search can return before acting as a non-match. CFG_BIBMATCH_SEARCH_RESULT_MATCH_LIMIT = 15 ###################################### ## Part 21: BibAuthorID parameters ## ###################################### # CFG_BIBAUTHORID_MAX_PROCESSES is the max number of processes # that may be spawned by the disambiguation algorithm CFG_BIBAUTHORID_MAX_PROCESSES = 12 # CFG_BIBAUTHORID_PERSONID_SQL_MAX_THREADS is the max number of threads # to parallelize sql queries during personID tables updates CFG_BIBAUTHORID_PERSONID_SQL_MAX_THREADS = 12 # CFG_BIBAUTHORID_EXTERNAL_CLAIMED_RECORDS_KEY defines the user info # keys for externally claimed records in an remote-login scenario--e.g. from arXiv.org # e.g. "external_arxivids" for arXiv SSO CFG_BIBAUTHORID_EXTERNAL_CLAIMED_RECORDS_KEY = # CFG_BIBAUTHORID_AID_ENABLED # Globally enable AuthorID Interfaces. # If False: No guest, user or operator will have access to the system. CFG_BIBAUTHORID_ENABLED = True # CFG_BIBAUTHORID_AID_ON_AUTHORPAGES # Enable AuthorID information on the author pages. CFG_BIBAUTHORID_ON_AUTHORPAGES = True # CFG_BIBAUTHORID_AUTHOR_TICKET_ADMIN_EMAIL defines the eMail address # all ticket requests concerning authors will be sent to. CFG_BIBAUTHORID_AUTHOR_TICKET_ADMIN_EMAIL = info@invenio-software.org #CFG_BIBAUTHORID_UI_SKIP_ARXIV_STUB_PAGE defines if the optional arXive stub page is skipped CFG_BIBAUTHORID_UI_SKIP_ARXIV_STUB_PAGE = False ######################################### ## Part 22: BibCirculation parameters ## ######################################### ## CFG_BIBCIRCULATION_ITEM_STATUS_OPTIONAL -- comma-separated list of statuses # Example: missing, order delayed, not published # You can allways add a new status here, but you may want to run some script # to update the database if you remove some statuses. CFG_BIBCIRCULATION_ITEM_STATUS_OPTIONAL = ## Here you can edit the text of the statuses that have specific roles. # You should run a script to update the database if you change them after having # used the module for some time. ## Item statuses # The book is on loan CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN = on loan # Available for loan CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF = on shelf # The book is being processed by the library (cataloguing, etc.) CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS = in process # The book has been ordered (bought) CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER = on order # The order of the book has been cancelled CFG_BIBCIRCULATION_ITEM_STATUS_CANCELLED = cancelled # The order of the book has not arrived yet CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED = not arrived # The order of the book has not arrived yet and has been claimed CFG_BIBCIRCULATION_ITEM_STATUS_CLAIMED = claimed # The book has been proposed for acquisition and is under review. CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW = under review ## Loan statuses # This status should not be confussed with CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN. # If the item status is CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, then there is # a loan with status CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN or # CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED. # For each copy, there can only be one active loan ('on loan' or 'expired') at # the time, since can be many 'returned' loans for the same copy. CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN = on loan # The due date has come and the item has not been returned CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED = expired # The item has been returned. CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED = returned ## Request statuses # There is at least one copy available, and this is the oldest request. CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING = pending # There are no copies available, or there is another request with more priority. CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING = waiting # The request has become a loan CFG_BIBCIRCULATION_REQUEST_STATUS_DONE = done # The request has been cancelled CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED = cancelled # The request has been generated for a proposed book CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED = proposed # ILL request statuses CFG_BIBCIRCULATION_ILL_STATUS_NEW = new CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED = requested CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN = on loan CFG_BIBCIRCULATION_ILL_STATUS_RETURNED = returned CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED = cancelled CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED = received #Book proposal statuses CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW = proposal-new CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER = proposal-on order CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE = proposal-put aside CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED = proposal-received # Purchase statuses CFG_BIBCIRCULATION_ACQ_STATUS_NEW = new CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER = on order CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT = partial receipt CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED = received CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED = cancelled ## Library types # Normal library where you have your books. I can also be a depot. CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL = internal # external libraries for ILL. CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL = external # The main library is also an internal library. # Since you may have several depots or small sites you can tag one of them as # the main site. CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN = main # It is also an internal library. The copies in this type of library will NOT # be displayed to borrowers. Use this for depots. CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN = hidden ## Amazon access key. You will need your own key. # Example: 1T6P5M3ZDMW9AWJ212R2 CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY = ###################################### ## Part 22: BibClassify parameters ## ###################################### # CFG_BIBCLASSIFY_WEB_MAXKW -- maximum number of keywords to display # in the Keywords tab web page. CFG_BIBCLASSIFY_WEB_MAXKW = 100 ######################################## ## Part 23: Plotextractor parameters ## ######################################## ## CFG_PLOTEXTRACTOR_SOURCE_BASE_URL -- for acquiring source tarballs for plot ## extraction, where should we look? If nothing is set, we'll just go ## to arXiv, but this can be a filesystem location, too CFG_PLOTEXTRACTOR_SOURCE_BASE_URL = http://arxiv.org/ ## CFG_PLOTEXTRACTOR_SOURCE_TARBALL_FOLDER -- for acquiring source tarballs for plot ## extraction, subfolder where the tarballs sit CFG_PLOTEXTRACTOR_SOURCE_TARBALL_FOLDER = e-print/ ## CFG_PLOTEXTRACTOR_SOURCE_PDF_FOLDER -- for acquiring source tarballs for plot ## extraction, subfolder where the pdf sit CFG_PLOTEXTRACTOR_SOURCE_PDF_FOLDER = pdf/ ## CFG_PLOTEXTRACTOR_DOWNLOAD_TIMEOUT -- a float representing the number of seconds ## to wait between each download of pdf and/or tarball from source URL. CFG_PLOTEXTRACTOR_DOWNLOAD_TIMEOUT = 2.0 ## CFG_PLOTEXTRACTOR_CONTEXT_LIMIT -- when extracting context of plots from ## TeX sources, this is the limitation of characters in each direction to extract ## context from. Default 750. CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT = 750 ## CFG_PLOTEXTRACTOR_DISALLOWED_TEX -- when extracting context of plots from TeX ## sources, this is the list of TeX tags that will trigger 'end of context'. CFG_PLOTEXTRACTOR_DISALLOWED_TEX = begin,end,section,includegraphics,caption,acknowledgements ## CFG_PLOTEXTRACTOR_CONTEXT_WORD_LIMIT -- when extracting context of plots from ## TeX sources, this is the limitation of words in each direction. Default 75. CFG_PLOTEXTRACTOR_CONTEXT_WORD_LIMIT = 75 ## CFG_PLOTEXTRACTOR_CONTEXT_SENTENCE_LIMIT -- when extracting context of plots from ## TeX sources, this is the limitation of sentences in each direction. Default 2. CFG_PLOTEXTRACTOR_CONTEXT_SENTENCE_LIMIT = 2 ###################################### ## Part 24: WebStat parameters ## ###################################### # CFG_WEBSTAT_BIBCIRCULATION_START_YEAR defines the start date of the BibCirculation # statistics. Value should have the format 'yyyy'. If empty, take all existing data. CFG_WEBSTAT_BIBCIRCULATION_START_YEAR = ###################################### ## Part 25: Web API Key parameters ## ###################################### # CFG_WEB_API_KEY_ALLOWED_URL defines the web apps that are going to use the web # API key. It has three values, the name of the web app, the time of life for the # secure url and if a time stamp is needed. #CFG_WEB_API_KEY_ALLOWED_URL = [('search/\?', 3600, True), # ('rss', 0, False)] CFG_WEB_API_KEY_ALLOWED_URL = [] ########################################## ## Part 26: WebAuthorProfile parameters ## ########################################## #CFG_WEBAUTHORPROFILE_CACHE_EXPIRED_DELAY_LIVE consider a cached element expired after days #when loading an authorpage, thus recomputing the content live CFG_WEBAUTHORPROFILE_CACHE_EXPIRED_DELAY_LIVE = 7 #CFG_WEBAUTHORPROFILE_CACHE_EXPIRED_DELAY_BIBSCHED consider a cache element expired after days, #thus recompute it, bibsched daemon CFG_WEBAUTHORPROFILE_CACHE_EXPIRED_DELAY_BIBSCHED = 5 #CFG_WEBAUTHORPROFILE_MAX_COLLAB_LIST: limit collaboration list. #Set to 0 to disable limit. CFG_WEBAUTHORPROFILE_MAX_COLLAB_LIST = 100 #CFG_WEBAUTHORPROFILE_MAX_KEYWORD_LIST: limit keywords list #Set to 0 to disable limit. CFG_WEBAUTHORPROFILE_MAX_KEYWORD_LIST = 100 #CFG_WEBAUTHORPROFILE_MAX_AFF_LIST: limit affiliations list #Set to 0 to disable limit. CFG_WEBAUTHORPROFILE_MAX_AFF_LIST = 100 #CFG_WEBAUTHORPROFILE_MAX_COAUTHOR_LIST: limit coauthors list #Set to 0 to disable limit. CFG_WEBAUTHORPROFILE_MAX_COAUTHOR_LIST = 100 #CFG_WEBAUTHORPROFILE_MAX_HEP_CHOICES: limit HepRecords choices #Set to 0 to disable limit. CFG_WEBAUTHORPROFILE_MAX_HEP_CHOICES = 10 #CFG_WEBAUTHORPROFILE_USE_BIBAUTHORID: use bibauthorid or exactauthor CFG_WEBAUTHORPROFILE_USE_BIBAUTHORID = False #################################### ## Part 27: BibSort parameters ## #################################### ## CFG_BIBSORT_BUCKETS -- the number of buckets bibsort should use. ## If 0, then no buckets will be used (bibsort will be inactive). ## If different from 0, bibsort will be used for sorting the records. ## The number of buckets should be set with regards to the size ## of the repository; having a larger number of buckets will increase ## the sorting performance for the top results but will decrease ## the performance for sorting the middle results. ## We recommend to to use 1 in case you have less than about ## 1,000,000 records. ## When modifying this variable, re-run rebalancing for all the bibsort ## methods, for having the database in synch. CFG_BIBSORT_BUCKETS = 1 #################################### ## Part 26: Developer options ## #################################### ## CFG_DEVEL_SITE -- is this a development site? If it is, you might ## prefer that it does not do certain things. For example, you might ## not want WebSubmit to send certain emails or trigger certain ## processes on a development site. Put "0" for "no" (meaning we are ## on production site), put "1" for "yes" (meaning we are on ## development site), or put "9" for "maximum debugging info" (which ## will be displayed to *all* users using Flask DebugToolbar, so ## please beware). +## If you do *NOT* want to send emails to their original recipients +## set up corresponding value to CFG_EMAIL_BACKEND (e.g. dummy, locmem). CFG_DEVEL_SITE = 0 ## CFG_DEVEL_TEST_DATABASE_ENGINES -- do we want to enable different testing ## database engines for testing Flask and SQLAlchemy? This setting ## will allow `*_flask_tests.py` to run on databases defined bellow. ## It uses `CFG_DATABASE_*` config variables as defaults for every ## specified engine. Put following keys to the testing database ## configuration dictionary in order to overwrite default values: ## * `engine`: SQLAlchemy engine + driver ## * `username`: The user name. ## * `password`: The database password. ## * `host`: The name of the host. ## * `port`: The port number. ## * `database`: The database name. ## EXAMPLE: ## CFG_DEVEL_TEST_DATABASE_ENGINES = { ## 'PostgreSQL': {'engine': 'postgresql'}, ## 'SQLite': {'engine': 'sqlite+pysqlite', 'username': None, ## 'password': None, 'host': None, 'database': None} ## } ## } CFG_DEVEL_TEST_DATABASE_ENGINES = {} ## CFG_DEVEL_TOOLS -- list of development tools to enable or disable. ## Currently supported tools are: ## * debug-toolbar: Flask Debug Toolbar ## * werkzeug-debugger: Werkzeug Debugger (for Apache) ## * sql-logger: Logging of run_sql SQL queries ## * inspect-templates: Template inspection (formerly CFG_WEBSTYLE_INSPECT_TEMPLATES) ## * no-https-redirect: Do not redirect HTTP to HTTPS ## * assets-debug: Jinja2 assets debugging (i.e. do not merge JavaScript files) ## * intercept-redirects: Intercept redirects (requires debug-toolbar enabled). ## * winpdb-local: Embedded WinPDB Debugger (default password is Change1Me) ## * winpdb-remote: Remote WinPDB Debugger (default password is Change1Me) ## * pydev: PyDev Remote Debugger ## ## IMPORTANT: For werkzeug-debugger, winpdb and pydev to work with Apache you ## must set WSGIDaemonProcess processes=1 threads=1 in invenio-apache-vhost.conf. CFG_DEVEL_TOOLS = ######################################## ## Part 28: JsTestDriver parameters ## ######################################## ## CFG_JSTESTDRIVER_PORT -- server port where JS tests will be run. CFG_JSTESTDRIVER_PORT = 9876 ############################ ## Part 29: RefExtract ## ############################ ## Refextract can automatically submit tickets (after extracting refereces) ## to CFG_REFEXTRACT_TICKET_QUEUE if it is set CFG_REFEXTRACT_TICKET_QUEUE = None ## Override refextract kbs locations CFG_REFEXTRACT_KBS_OVERRIDE = {} ################################## ## Part 30: CrossRef parameters ## ################################## ## CFG_CROSSREF_USERNAME -- the username used when sending request ## to the Crossref site. CFG_CROSSREF_USERNAME = ## CFG_CROSSREF_PASSWORD -- the password used when sending request ## to the Crossref site. CFG_CROSSREF_PASSWORD = ##################################### ## Part 31: WebLinkback parameters ## ##################################### ## CFG_WEBLINKBACK_TRACKBACK_ENABLED -- whether to enable trackback support ## 1 to enable, 0 to disable it CFG_WEBLINKBACK_TRACKBACK_ENABLED = 0 #################################### ## Part 33: WebSubmit parameters ## #################################### ## CFG_WEBSUBMIT_USE_MATHJAX -- whether to use MathJax and math ## preview panel within submissions (1) or not (0). Customize your ## websubmit_template.tmpl_mathpreview_header() to enable for specific ## fields. ## See also CFG_WEBSEARCH_USE_MATHJAX_FOR_FORMATS CFG_WEBSUBMIT_USE_MATHJAX = 0 ############################ ## Part 34: BibWorkflow ## ############################ ## Setting worker that will be used to execut workflows. ## Allowed options: Celery CFG_BIBWORKFLOW_WORKER = worker_celery ## Messages broker for worker ## RabbitMQ - amqp://guest@localhost// ## Redis - redis://localhost:6379/0 CFG_BROKER_URL = amqp://guest@localhost:5672// ## Broker backend ## RabbitMQ - amqp ## Redis - redis://localhost:6379/0 CFG_CELERY_RESULT_BACKEND = amqp #################################### ## Part 35: BibField parameters ## #################################### ## CFG_BIBFIELD_MASTER_FORMATS -- the name of all the allowed master formats ## that BibField will work with. CFG_BIBFIELD_MASTER_FORMATS = marc ########################## ## THAT's ALL, FOLKS! ## ########################## diff --git a/modules/miscutil/etc/templates/Makefile.am b/modules/miscutil/etc/templates/Makefile.am index b4c20bf18..62cce1772 100644 --- a/modules/miscutil/etc/templates/Makefile.am +++ b/modules/miscutil/etc/templates/Makefile.am @@ -1,26 +1,28 @@ ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. templatesdir = $(sysconfdir)/templates templates_DATA = admin_base.html \ + mail_html.tpl \ + mail_text.tpl \ invenio-apache-vhost.tpl \ invenio-apache-vhost.conf.tpl \ invenio-apache-vhost-ssl.conf.tpl EXTRA_DIST = $(templates_DATA) CLEANFILES = *~ *.tmp diff --git a/modules/miscutil/etc/templates/Makefile.am b/modules/miscutil/etc/templates/mail_html.tpl similarity index 55% copy from modules/miscutil/etc/templates/Makefile.am copy to modules/miscutil/etc/templates/mail_html.tpl index b4c20bf18..923454611 100644 --- a/modules/miscutil/etc/templates/Makefile.am +++ b/modules/miscutil/etc/templates/mail_html.tpl @@ -1,26 +1,42 @@ +{# ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. - -templatesdir = $(sysconfdir)/templates -templates_DATA = admin_base.html \ - invenio-apache-vhost.tpl \ - invenio-apache-vhost.conf.tpl \ - invenio-apache-vhost-ssl.conf.tpl - -EXTRA_DIST = $(templates_DATA) - -CLEANFILES = *~ *.tmp +#} +{%- block mail_header -%} +{% if header %}{{ header }}{% else %}{{ _("Hello:") }}
{% endif %} +{%- endblock %} +{% block mail_content %} +{{ content }} +{% endblock -%} +{%- block mail_footer %} +{% if footer %}{{ footer }}{% else %} +
+
+{{ _("Best regards") }} +
+
+ + {{ config.CFG_SITE_NAME_INTL.get(g.ln, config.CFG_SITE_NAME) }} + + +
+{{ _("Need human intervention? Contact") }} + + {{ config.CFG_SITE_SUPPORT_EMAIL }} + +{% endif %} +{% endblock -%} diff --git a/modules/miscutil/etc/templates/Makefile.am b/modules/miscutil/etc/templates/mail_text.tpl similarity index 62% copy from modules/miscutil/etc/templates/Makefile.am copy to modules/miscutil/etc/templates/mail_text.tpl index b4c20bf18..c13c0db20 100644 --- a/modules/miscutil/etc/templates/Makefile.am +++ b/modules/miscutil/etc/templates/mail_text.tpl @@ -1,26 +1,34 @@ +{# ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. +#} +{%- block mail_header -%} +{% if header %}{{ header }}{% else %}{{ _("Hello:") }}{% endif %} +{% endblock -%} +{%- block mail_content -%} +{{ content }} +{% endblock -%} +{%- block mail_footer %} +{% if footer %}{{ footer }}{% else %} -templatesdir = $(sysconfdir)/templates -templates_DATA = admin_base.html \ - invenio-apache-vhost.tpl \ - invenio-apache-vhost.conf.tpl \ - invenio-apache-vhost-ssl.conf.tpl -EXTRA_DIST = $(templates_DATA) - -CLEANFILES = *~ *.tmp +{{ _("Best regards") }} +-- +{{ config.CFG_SITE_NAME_INTL.get(g.ln, config.CFG_SITE_NAME) }} <{{ config.CFG_SITE_URL }}> +{{ _("Need human intervention? Contact") }} <{{ config.CFG_SITE_SUPPORT_EMAIL }}> +{% endif %} +{% endblock -%} diff --git a/modules/miscutil/lib/Makefile.am b/modules/miscutil/lib/Makefile.am index 7b279b148..ca89524a0 100644 --- a/modules/miscutil/lib/Makefile.am +++ b/modules/miscutil/lib/Makefile.am @@ -1,186 +1,188 @@ ## This file is part of Invenio. ## Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. SUBDIRS = upgrades pylibdir = $(libdir)/python/invenio pylib_DATA = __init__.py \ adminutils.py \ apache_manager.py \ - cache.py \ + cache.py \ errorlib.py \ errorlib_unit_tests.py \ errorlib_model.py \ errorlib_webinterface.py \ errorlib_regression_tests.py \ flask_sslify.py \ config_manager.py \ celery.py \ celery_config.py \ celery_unit_tests.py \ celery_tasks.py \ data_cacher.py \ database_manager.py \ demosite_manager.py \ dbdump.py \ web_api_key.py \ web_api_key_model.py \ web_api_key_unit_tests.py \ dbquery.py \ dbquery_unit_tests.py \ dbquery_regression_tests.py \ dataciteutils.py \ dataciteutils_tester.py \ logicutils.py \ logicutils_unit_tests.py \ mailutils.py \ + mailutils_backend_adminonly.py \ + mailutils_unit_tests.py \ miscutil_config.py \ miscutil_model.py \ messages.py \ messages_unit_tests.py \ signalutils.py \ textutils.py \ textutils_unit_tests.py \ dateutils.py \ dateutils_unit_tests.py \ hashutils.py \ hashutils_unit_tests.py \ htmlutils.py \ htmlutils_unit_tests.py \ testutils.py \ testutils_regression_tests.py \ inveniocfg_upgrader.py \ inveniocfg_upgrader_model.py \ inveniocfg_upgrader_unit_tests.py \ upgrade_manager.py \ invenio_connector.py \ invenio_connector_regression_tests.py \ jinja2utils.py \ urlutils.py \ urlutils_unit_tests.py \ w3c_validator.py \ importutils.py \ importutils_unit_tests.py \ intbitset_unit_tests.py \ intbitset_helper.py \ inveniocfg.py \ inveniomanage.py \ inveniomanage_unit_tests.py \ inveniocfg_unit_tests.py \ scriptutils.py \ settings.py \ shellutils.py \ shellutils_unit_tests.py \ sqlalchemyutils.py \ sqlalchemyutils_mysql.py \ paginationutils.py \ paginationutils_unit_tests.py \ pluginutils.py \ pluginutils_unit_tests.py \ plotextractor.py \ plotextractor_converter.py \ plotextractor_getter.py \ plotextractor_output_utils.py \ plotextractor_unit_tests.py \ plotextractor_regression_tests.py \ plotextractor_config.py \ solrutils_bibindex_indexer.py \ solrutils_bibindex_searcher.py \ solrutils_bibrank_indexer.py \ solrutils_bibrank_searcher.py \ solrutils_config.py \ solrutils_regression_tests.py \ solrutils_unit_tests.py \ xapianutils_bibindex_indexer.py \ xapianutils_bibindex_searcher.py \ xapianutils_bibrank_indexer.py \ xapianutils_bibrank_searcher.py \ xapianutils_config.py \ remote_debugger.py \ remote_debugger_config.py \ remote_debugger_wsgi_reload.py \ jsonutils.py \ jsonutils_unit_tests.py \ - sequtils_cnum.py \ + sequtils_cnum.py \ sequtils.py \ sequtils_model.py \ sequtils_regression_tests.py \ memoiseutils.py \ memoiseutils_unit_tests.py \ crossrefutils.py \ flaskshell.py \ wtforms_utils.py \ sherpa_romeo.py \ sherpa_romeo_testing.py \ orcid.py \ xmlDict.py \ dataciteutils.py \ containerutils.py jsdir=$(localstatedir)/www/js js_DATA = jquery.mathpreview.js noinst_DATA = testimport.py \ kwalitee.py \ pep8.py tmpdir = $(prefix)/var/tmp tmp_DATA = intbitset_example.int EXTRA_DIST = $(pylib_DATA) \ $(tmp_DATA) \ $(js_DATA) \ testimport.py \ kwalitee.py \ pep8.py \ intbitset.pyx \ intbitset.c \ intbitset.h \ intbitset_impl.c \ intbitset_setup.py \ intbitset.pyx \ solrutils \ solrutils/schema.xml \ solrutils/java_sources.txt \ solrutils/org \ solrutils/org/invenio_software \ solrutils/org/invenio_software/solr \ solrutils/org/invenio_software/solr/BitSetFieldCollector.java \ solrutils/org/invenio_software/solr/InvenioFacetComponent.java \ solrutils/org/invenio_software/solr/FieldCollectorBase.java \ solrutils/org/invenio_software/solr/IntFieldCollector.java \ solrutils/org/invenio_software/solr/FieldCollector.java \ solrutils/org/invenio_software/solr/InvenioQueryComponent.java \ solrutils/org/invenio_software/solr/InvenioBitsetStreamResponseWriter.java \ solrutils/org/invenio_software/solr/InvenioBitSet.java \ solrutils/org/invenio_software/solr/StringFieldCollector.java \ solrutils/solrconfig.xml all: $(PYTHON) $(srcdir)/intbitset_setup.py build_ext install-data-hook: $(PYTHON) $(srcdir)/testimport.py ${prefix} @find ${srcdir} -name intbitset.so -exec cp {} ${pylibdir} \; CLEANFILES = *~ *.tmp *.pyc clean-local: rm -rf build diff --git a/modules/miscutil/lib/jinja2utils.py b/modules/miscutil/lib/jinja2utils.py index 9e28377ea..8dc3468c3 100644 --- a/modules/miscutil/lib/jinja2utils.py +++ b/modules/miscutil/lib/jinja2utils.py @@ -1,452 +1,450 @@ # -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from operator import itemgetter from jinja2 import nodes from jinja2.ext import Extension -from flask import _request_ctx_stack +from flask import g, _request_ctx_stack try: from MarkupSafe import Markup as jinja2_Markup, escape as jinja2_escape except ImportError: from jinja2._markupsafe import Markup as jinja2_Markup, \ escape as jinja2_escape ENV_PREFIX = '_collected_' def prepare_tag_bundle(cls, tag): """ Construct function that returns collected data specified in jinja2 template like `{% %}` in correct order. Here is an example that shows the final order when template inheritance is used:: example.html ------------ {%\ extends 'page.html' %} {%\ css 'template2.css' %} {%\ css 'template3.css' %} page.html --------- {%\ css 'template1.css' %} {{ get_css_bundle() }} Output: ------- [template1.css, template2.css, template3.css] """ def get_bundle(key=None, iterate=False): def _get_data_by_key(data_, key_): return map(itemgetter(1), filter(lambda (k, v): k == key_, data_)) data = getattr(cls.environment, ENV_PREFIX+tag) if iterate: bundles = sorted(set(map(itemgetter(0), data))) def _generate_bundles(): for bundle in bundles: cls._reset(tag, bundle) yield cls.environment.new_bundle(tag, _get_data_by_key(data, bundle), bundle) return _generate_bundles() else: if key is not None: data = _get_data_by_key(data, key) else: bundles = sorted(set(map(itemgetter(0), data))) data = [f for bundle in bundles for f in _get_data_by_key(data, bundle)] cls._reset(tag, key) return cls.environment.new_bundle(tag, data, key) return get_bundle class CollectionExtension(Extension): """ CollectionExtension adds new tags `css` and `js` and functions ``get_css_bundle`` and ``get_js_bundle`` for jinja2 templates. The ``new_bundle`` method is used to create bundle from list of file names collected using `css` and `js` tags. Example: simple case {% css 'css/invenio.css' %} {% js 'js/jquery.js' %} {% js 'js/invenio.js' %} ... {% assets get_css_bundle() %} {% endassets %} {% assets get_js_bundle() %} In template, use {{ ASSETS_URL }} for printing file URL. {% endassets %} Example: named bundles record.html: {% extend 'page.html' %} {% css 'css/may-vary.css' %} # default bundle name can be changed in application factory # app.jinja_env.extend(default_bundle_name='90-default') {% css 'css/record.css', '10-record' %} {% css 'css/form.css', '10-record' %} page.html: {% css 'css/bootstrap.css', '00-base' %} {% css 'css/invenio.css', '00-base' %} ... {% for bundle in get_css_bundle(iterate=True) %} {% assets bundle %} {% endassets %} {% endfor %} Output: Note: If you decide not to use assets bundle but directly print stylesheet and script html tags, you MUST define: ``` _app.jinja_env.extend( use_bundle = False, collection_templates = { 'css': '', 'js': '' }) ``` Both callable and string with '%s' are allowed in ``collection_templates``. """ tags = set(['css', 'js']) def __init__(self, environment): super(CollectionExtension, self).__init__(environment) ext = dict(('get_%s_bundle' % tag, prepare_tag_bundle(self, tag)) for tag in self.tags) environment.extend( default_bundle_name='10-default', use_bundle=True, collection_templates=dict((tag, lambda x: x) for tag in self.tags), new_bundle=lambda tag, collection, name: collection, **ext) for tag in self.tags: self._reset(tag) def _reset(self, tag, key=None): """ Empty list of used scripts. """ if key is None: setattr(self.environment, ENV_PREFIX+tag, []) else: data = filter(lambda (k, v): k != key, getattr(self.environment, ENV_PREFIX+tag)) setattr(self.environment, ENV_PREFIX+tag, data) def _update(self, tag, value, key, caller=None): """ Update list of used scripts. """ try: values = getattr(self.environment, ENV_PREFIX+tag) values.append((key, value)) except: values = [(key, value)] setattr(self.environment, ENV_PREFIX+tag, values) return '' def parse(self, parser): """ Parse Jinja statement tag defined in `self.tags` (default: css, js). This accually tries to build corresponding html script tag or collect script file name in jinja2 environment variable. If you use bundles it is important to call ``get_css_bundle`` or ``get_js_bundle`` in template after all occurrences of script tags (e.g. {% css ... %}, {% js ...%}). """ tag = parser.stream.current.value lineno = next(parser.stream).lineno default_bundle_name = u"%s" % (self.environment.default_bundle_name) default_bundle_name.encode('utf-8') bundle_name = nodes.Const(default_bundle_name) #parse filename if parser.stream.current.type != 'block_end': value = parser.parse_expression() # get first optional argument: bundle_name if parser.stream.skip_if('comma'): bundle_name = parser.parse_expression() if isinstance(bundle_name, nodes.Name): bundle_name = nodes.Name(bundle_name.name, 'load') else: value = parser.parse_tuple() args = [nodes.Const(tag), value, bundle_name] # Return html tag with link to corresponding script file. if self.environment.use_bundle is False: value = value.value if callable(self.environment.collection_templates[tag]): node = self.environment.collection_templates[tag](value) else: node = self.environment.collection_templates[tag] % value return nodes.Output([nodes.MarkSafeIfAutoescape(nodes.Const(node))]) # Call :meth:`_update` to collect names of used scripts. return nodes.CallBlock(self.call_method('_update', args=args, lineno=lineno), [], [], '') def render_template_to_string(input, _from_string=False, **context): """Renders a template from the template folder with the given context and return the string. :param input: the string template, or name of the template to be rendered, or an iterable with template names the first one existing will be rendered :param context: the variables that should be available in the context of the template. :note: code based on [https://github.com/mitsuhiko/flask/blob/master/flask/templating.py] """ ctx = _request_ctx_stack.top ctx.app.update_template_context(context) if _from_string: template = ctx.app.jinja_env.from_string(input) else: template = ctx.app.jinja_env.get_or_select_template(input) return template.render(context) -from flask import g -from invenio.bibformat_engine import filter_languages - class LangExtension(Extension): tags = set(['lang']) def parse(self, parser): lineno = parser.stream.next().lineno body = parser.parse_statements(['name:endlang'], drop_needle=True) return nodes.CallBlock(self.call_method('_lang'), [], [], body).set_lineno(lineno) def _lang(self, caller): + from invenio.bibformat_engine import filter_languages return filter_languages('' + caller() + '', g.ln) def hack_jinja2_utf8decoding(): """ Jinja2 requires all strings to be unicode objects. Invenio however operates with UTF8 encoded str objects. Jinja2 will automatically convert non-unicode objects into unicode objects, but via the ascii codec. This function replaces the escape function and Markup class in Jinja2/MarkupSafe, to use the utf8 codec when converting 8-bit str objects into unicode objects. Ideally Jinja2/MarkupSafe should allow specifying which default encoding to use when decoding strings. Other alternatives is to decode any str object into unicode prior to passing the values to Jinja2 methods. This will however require large changes over the entire Invenio codebase, with the risk of introducing many errors. This runtime hack is unfortunately currently the least intrusive way to fix the str to unicode decoding. """ # Jinja2 will try to load escape method and Markup class from a variety of # different modules. First it will try from MarkupSafe package, then from # jinja2._markupsafe._speedup, then jinja2._markupsafe._native. Ideally, we # should only replace the function and class at the implementing module. # However, due to Python's package/module loading behaviour, the function # and class will be imported into other jinja2 modules as soon as we try to # import the module implementing the function and class. Hence, we need to # replace the function and class in the modules where it has already been # imported. import jinja2 import jinja2.runtime import jinja2.utils import jinja2.nodes import jinja2.filters import jinja2.ext import jinja2.environment import jinja2.compiler # Escape function replacement in Jinja2 library jinja2._markupsafe.escape = utf8escape jinja2.runtime.escape = utf8escape jinja2.utils.escape = utf8escape jinja2.filters.escape = utf8escape jinja2.compiler.escape = utf8escape jinja2.escape = utf8escape # Markup class replacement in Jinja2 library jinja2._markupsafe.Markup = Markup jinja2.runtime.Markup = Markup jinja2.utils.Markup = Markup jinja2.filters.Markup = Markup jinja2.compiler.Markup = Markup jinja2.Markup = Markup jinja2.nodes.Markup = Markup jinja2.ext.Markup = Markup jinja2.environment.Markup = Markup # Escape/Markup replacement in MarkupSafe library. try: import MarkupSafe MarkupSafe.escape = utf8escape MarkupSafe.Markup = Markup except ImportError: pass def utf8escape(s): """ UTF8-8-bit-string-friendly replacement function for MarkupSafe/Jinja2 escape function. WARNING: Do not use this method. Use jinja2.escape() instead. """ if isinstance(s, str): return jinja2_escape(s.decode('utf8')) return jinja2_escape(s) # Ensure function name is identical to replaced function. utf8escape.__name__ = jinja2_escape.__name__ class Markup(jinja2_Markup): """ Markup replacement class Forces the use of utf8 codec for decoding 8-bit strings, in case no encoding is specified. WARNING: Do not use this class. Use jinja2.Markup instead. """ def __new__(cls, base=u'', encoding=None, errors='strict'): if encoding is None and isinstance(base, str): encoding = 'utf8' return jinja2_Markup.__new__(cls, base=base, encoding=encoding, errors=errors) def extend_application_template_filters(app): """ Extends application template filters with custom filters and fixes. List of applied filters: ------------------------ * filesizeformat * path_join * quoted_txt2html * invenio_format_date * invenio_pretty_date * invenio_url_args """ import os from datetime import datetime from invenio.textutils import nice_size from invenio.dateutils import convert_datetext_to_dategui, \ convert_datestruct_to_dategui, pretty_date from invenio.webmessage_mailutils import email_quoted_txt2html @app.template_filter('filesizeformat') def _filesizeformat_filter(value): """ Jinja2 filesizeformat filters is broken in Jinja2 up to v2.7, so let's implement our own. """ return nice_size(value) test_not_empty = lambda v: v is not None and v != '' @app.template_filter('prefix') def _prefix(value, prefix=''): return prefix + value if test_not_empty(value) else '' @app.template_filter('suffix') def _suffix(value, suffix=''): return value + suffix if test_not_empty(value) else '' @app.template_filter('wrap') def _wrap(value, prefix='', suffix=''): return prefix + value + suffix if test_not_empty(value) else '' @app.template_filter('sentences') def _sentences(value, limit, separator='. '): """ Returns first `limit` number of sentences ending by `separator`. """ return separator.join(value.split(separator)[:limit]) @app.template_filter('path_join') def _os_path_join(d): """Shortcut for `os.path.join`.""" return os.path.join(*d) @app.template_filter('quoted_txt2html') def _quoted_txt2html(*args, **kwargs): return email_quoted_txt2html(*args, **kwargs) @app.template_filter('invenio_format_date') def _format_date(date): """ This is a special Jinja2 filter that will call convert_datetext_to_dategui to print a human friendly date. """ if isinstance(date, datetime): return convert_datestruct_to_dategui(date.timetuple(), g.ln).decode('utf-8') return convert_datetext_to_dategui(date, g.ln).decode('utf-8') @app.template_filter('invenio_pretty_date') def _pretty_date(date): """ This is a special Jinja2 filter that will call pretty_date to print a human friendly timestamp. """ if isinstance(date, datetime): return pretty_date(date, ln=g.ln) return date @app.template_filter('invenio_url_args') def _url_args(d, append=u'?', filter=[]): from jinja2.utils import escape rv = append + u'&'.join( u'%s=%s' % (escape(key), escape(value)) for key, value in d.iteritems(True) if value is not None and key not in filter # and not isinstance(value, Undefined) ) return rv diff --git a/modules/miscutil/lib/mailutils.py b/modules/miscutil/lib/mailutils.py index 14251d204..d26425a63 100644 --- a/modules/miscutil/lib/mailutils.py +++ b/modules/miscutil/lib/mailutils.py @@ -1,524 +1,436 @@ # -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Invenio mail sending utilities. send_email() is the main API function people should be using; just check out its docstring. """ __revision__ = "$Id$" -import sys from time import sleep -import smtplib -import socket import re import os +import sys -from email.Header import Header -from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders from email.MIMEImage import MIMEImage from email.Utils import formatdate from cStringIO import StringIO +from flask import g from formatter import DumbWriter, AbstractFormatter +from flask.ext.email.message import EmailMultiAlternatives, EmailMessage from invenio.config import \ - CFG_SITE_SUPPORT_EMAIL, \ - CFG_SITE_URL, \ - CFG_SITE_LANG, \ - CFG_SITE_NAME_INTL, \ - CFG_SITE_NAME, \ - CFG_SITE_ADMIN_EMAIL, \ - CFG_MISCUTIL_SMTP_HOST, \ - CFG_MISCUTIL_SMTP_PORT, \ - CFG_VERSION, \ - CFG_DEVEL_SITE - + CFG_SITE_SUPPORT_EMAIL, \ + CFG_SITE_URL, \ + CFG_SITE_LANG, \ + CFG_SITE_ADMIN_EMAIL, \ + CFG_MISCUTIL_SMTP_HOST, \ + CFG_MISCUTIL_SMTP_PORT, \ + CFG_VERSION, \ + CFG_DEVEL_SITE, \ + CFG_LOGDIR + +from invenio.config import CFG_MISCUTIL_SMTP_HOST, CFG_MISCUTIL_SMTP_PORT try: from invenio.config import \ - CFG_MISCUTIL_SMTP_USER,\ - CFG_MISCUTIL_SMTP_PASS,\ - CFG_MISCUTIL_SMTP_TLS + CFG_MISCUTIL_SMTP_USER,\ + CFG_MISCUTIL_SMTP_PASS,\ + CFG_MISCUTIL_SMTP_TLS except ImportError: CFG_MISCUTIL_SMTP_USER = '' CFG_MISCUTIL_SMTP_PASS = '' CFG_MISCUTIL_SMTP_TLS = False -from invenio.messages import wash_language, gettext_set_language -from invenio.textutils import guess_minimum_encoding from invenio.errorlib import register_exception from invenio.miscutil_config import InvenioMiscUtilError +from invenio.jinja2utils import render_template_to_string + + +def initialize_email_backend(app): + """ + Prepare application config from Invenio configuration. + + @see: https://flask-email.readthedocs.org/en/latest/#configuration + """ + app.config['DEFAULT_FROM_EMAIL'] = CFG_SITE_SUPPORT_EMAIL + app.config['SERVER_EMAIL'] = CFG_SITE_ADMIN_EMAIL + app.config['ADMINS'] = (CFG_SITE_ADMIN_EMAIL, ) + app.config['MANAGERS'] = (CFG_SITE_SUPPORT_EMAIL, ) + + if app.config.get('EMAIL_BACKEND') is None: + if CFG_MISCUTIL_SMTP_HOST and CFG_MISCUTIL_SMTP_PORT: + app.config['EMAIL_BACKEND'] = 'flask.ext.email.backends.smtp.Mail' + elif app.config.get('CFG_EMAIL_BACKEND'): + app.config['EMAIL_BACKEND'] = app.config.get('CFG_EMAIL_BACKEND') + # Defaults to 'flask.ext.email.backends.locmem.Mail' + + app.config['EMAIL_HOST'] = CFG_MISCUTIL_SMTP_HOST + app.config['EMAIL_PORT'] = CFG_MISCUTIL_SMTP_PORT + app.config['EMAIL_HOST_USER'] = CFG_MISCUTIL_SMTP_USER + app.config['EMAIL_HOST_PASSWORD'] = CFG_MISCUTIL_SMTP_PASS + app.config['EMAIL_USE_TLS'] = CFG_MISCUTIL_SMTP_TLS + # app.config['EMAIL_USE_SSL']: defaults to False + + app.config['EMAIL_FILE_PATH'] = CFG_LOGDIR + def scheduled_send_email(fromaddr, - toaddr, - subject="", - content="", - header=None, - footer=None, - copy_to_admin=0, - attempt_times=1, - attempt_sleeptime=10, - user=None, - other_bibtasklet_arguments=None, - replytoaddr=""): + toaddr, + subject="", + content="", + header=None, + footer=None, + copy_to_admin=0, + attempt_times=1, + attempt_sleeptime=10, + user=None, + other_bibtasklet_arguments=None, + replytoaddr=""): """ Like send_email, but send an email via the bibsched infrastructure. @param fromaddr: sender @type fromaddr: string @param toaddr: list of receivers @type toaddr: string (comma separated) or list of strings @param subject: the subject @param content: the body of the message @param header: optional header, otherwise default is used @param footer: optional footer, otherwise default is used @param copy_to_admin: set to 1 in order to send email the admins @param attempt_times: try at least n times before giving up sending @param attempt_sleeptime: number of seconds to sleep between two attempts @param user: the user name to user when scheduling the bibtasklet. If None, the sender will be used @param other_bibtasklet_arguments: other arguments to append to the list of arguments to the call of task_low_level_submission @param replytoaddr: [string or list-of-strings] to be used for the reply-to header of the email (if string, then receivers are separated by ',') @return: the scheduled bibtasklet """ from invenio.bibtask import task_low_level_submission if not isinstance(toaddr, (unicode, str)): toaddr = ','.join(toaddr) if not isinstance(replytoaddr, (unicode, str)): replytoaddr = ','.join(replytoaddr) toaddr = remove_temporary_emails(toaddr) if user is None: user = fromaddr if other_bibtasklet_arguments is None: other_bibtasklet_arguments = [] else: other_bibtasklet_arguments = list(other_bibtasklet_arguments) if not header is None: other_bibtasklet_arguments.extend(("-a", "header=%s" % header)) if not footer is None: other_bibtasklet_arguments.extend(("-a", "footer=%s" % footer)) return task_low_level_submission( "bibtasklet", user, "-T", "bst_send_email", "-a", "fromaddr=%s" % fromaddr, "-a", "toaddr=%s" % toaddr, "-a", "replytoaddr=%s" % replytoaddr, "-a", "subject=%s" % subject, "-a", "content=%s" % content, "-a", "copy_to_admin=%s" % copy_to_admin, "-a", "attempt_times=%s" % attempt_times, "-a", "attempt_sleeptime=%s" % attempt_sleeptime, *other_bibtasklet_arguments) + def send_email(fromaddr, toaddr, subject="", content="", html_content='', html_images=None, header=None, footer=None, html_header=None, html_footer=None, copy_to_admin=0, attempt_times=1, attempt_sleeptime=10, debug_level=0, ln=CFG_SITE_LANG, charset=None, replytoaddr="", attachments=None ): """Send a forged email to TOADDR from FROMADDR with message created from subjet, content and possibly header and footer. @param fromaddr: [string] sender @param toaddr: [string or list-of-strings] list of receivers (if string, then receivers are separated by ',') @param subject: [string] subject of the email @param content: [string] content of the email @param html_content: [string] html version of the email @param html_images: [dict] dictionary of image id, image path @param header: [string] header to add, None for the Default @param footer: [string] footer to add, None for the Default @param html_header: [string] header to add to the html part, None for the Default @param html_footer: [string] footer to add to the html part, None for the Default @param copy_to_admin: [int] if 1 add CFG_SITE_ADMIN_EMAIL in receivers @param attempt_times: [int] number of tries @param attempt_sleeptime: [int] seconds in between tries @param debug_level: [int] debug level @param ln: [string] invenio language @param charset: [string] the content charset. By default is None which means to try to encode the email as ascii, then latin1 then utf-8. @param replytoaddr: [string or list-of-strings] to be used for the reply-to header of the email (if string, then receivers are separated by ',') @param attachments: list of paths of files to be attached. Alternatively, every element of the list could be a tuple: (filename, mimetype) If sending fails, try to send it ATTEMPT_TIMES, and wait for ATTEMPT_SLEEPTIME seconds in between tries. e.g.: send_email('foo.bar@cern.ch', 'bar.foo@cern.ch', 'Let\'s try!'', 'check 1234', 'check 1234', {'image1': '/tmp/quantum.jpg'}) @return: [bool]: True if email was sent okay, False if it was not. """ if html_images is None: html_images = {} if type(toaddr) is str: toaddr = toaddr.strip().split(',') toaddr = remove_temporary_emails(toaddr) - usebcc = len(toaddr) > 1 # More than one address, let's use Bcc in place of To + usebcc = len(toaddr.split(',')) > 1 # More than one address, let's use Bcc in place of To + if copy_to_admin: if CFG_SITE_ADMIN_EMAIL not in toaddr: toaddr.append(CFG_SITE_ADMIN_EMAIL) - if CFG_DEVEL_SITE: #if we are on a development site, we don't want to send external e-mails - content = """ --------------------------------------------------------------- -This message would have been sent to the following recipients: -%s --------------------------------------------------------------- -%s""" % (toaddr, content) - toaddr = CFG_SITE_ADMIN_EMAIL - usebcc = False + body = forge_email(fromaddr, toaddr, subject, content, html_content, html_images, usebcc, header, footer, html_header, html_footer, ln, charset, replytoaddr, attachments) - _ = gettext_set_language(CFG_SITE_LANG) - if attempt_times < 1 or not toaddr: try: - raise InvenioMiscUtilError(_('The system is not attempting to send an email from %s, to %s, with body %s.') % (fromaddr, toaddr, body)) - except InvenioMiscUtilError, exc: + raise InvenioMiscUtilError(g._('The system is not attempting to send an email from %s, to %s, with body %s.') % (fromaddr, toaddr, body)) + except InvenioMiscUtilError: register_exception() -# log('ERR_MISCUTIL_NOT_ATTEMPTING_SEND_EMAIL', fromaddr, toaddr, body) return False sent = False while not sent and attempt_times > 0: + sent = body.send() try: - server = smtplib.SMTP(CFG_MISCUTIL_SMTP_HOST, CFG_MISCUTIL_SMTP_PORT) - if debug_level > 2: - server.set_debuglevel(1) - else: - server.set_debuglevel(0) - if CFG_MISCUTIL_SMTP_TLS: - server.ehlo() - server.starttls() - server.ehlo() - if CFG_MISCUTIL_SMTP_USER and CFG_MISCUTIL_SMTP_PASS: - server.login(CFG_MISCUTIL_SMTP_USER, CFG_MISCUTIL_SMTP_PASS) - server.sendmail(fromaddr, toaddr, body) - server.quit() - sent = True - except (smtplib.SMTPException, socket.error): + sent = body.send() + except Exception: register_exception() if debug_level > 1: try: - raise InvenioMiscUtilError(_('Error in connecting to the SMPT server waiting %s seconds. Exception is %s, while sending email from %s to %s with body %s.') % (attempt_sleeptime, sys.exc_info()[0], fromaddr, toaddr, body)) - except InvenioMiscUtilError, exc: + raise InvenioMiscUtilError(g._('Error in sending message. Waiting %s seconds. Exception is %s, while sending email from %s to %s with body %s.') % (attempt_sleeptime, sys.exc_info()[0], fromaddr, toaddr, body)) + except InvenioMiscUtilError: register_exception() -# log('ERR_MISCUTIL_CONNECTION_SMTP', attempt_sleeptime, -# sys.exc_info()[0], fromaddr, toaddr, body) if not sent: attempt_times -= 1 - if attempt_times > 0: # sleep only if we shall retry again + if attempt_times > 0: # sleep only if we shall retry again sleep(attempt_sleeptime) if not sent: try: - raise InvenioMiscUtilError(_('Error in sending email from %s to %s with body %s.') % (fromaddr, toaddr, body)) - except InvenioMiscUtilError, exc: + raise InvenioMiscUtilError(g._('Error in sending email from %s to %s with body %s.') % (fromaddr, toaddr, body)) + except InvenioMiscUtilError: register_exception() -# log('ERR_MISCUTIL_SENDING_EMAIL', fromaddr, toaddr, body) return sent -def email_header(ln=CFG_SITE_LANG): - """The header of the email - @param ln: language - @return: header as a string""" - ln = wash_language(ln) - _ = gettext_set_language(ln) - #standard header - out = """%(hello)s - """ % { - 'hello': _("Hello:") - } - return out - -def email_html_header(ln=CFG_SITE_LANG): - """The header of the email - @param ln: language - @return: header as a string""" - ln = wash_language(ln) - _ = gettext_set_language(ln) - #standard header - out = """%(hello)s
- """ % { - 'hello': _("Hello:") - } - return out - - -def email_footer(ln=CFG_SITE_LANG): - """The footer of the email - @param ln: language - @return: footer as a string""" - ln = wash_language(ln) - _ = gettext_set_language(ln) - #standard footer - out = """\n\n%(best_regards)s --- -%(sitename)s <%(siteurl)s> -%(need_intervention_please_contact)s <%(sitesupportemail)s> - """ % { - 'sitename': CFG_SITE_NAME_INTL[ln], - 'best_regards': _("Best regards"), - 'siteurl': CFG_SITE_URL, - 'need_intervention_please_contact': _("Need human intervention? Contact"), - 'sitesupportemail': CFG_SITE_SUPPORT_EMAIL - } - return out - -def email_html_footer(ln=CFG_SITE_LANG): - """The html footer of the email - @param ln: language - @return: footer as a string""" - ln = wash_language(ln) - _ = gettext_set_language(ln) - #standard footer - out = """

%(best_regards)s -
-%(sitename)s
-%(need_intervention_please_contact)s %(sitesupportemail)s - """ % { - 'sitename': CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME), - 'best_regards': _("Best regards"), - 'siteurl': CFG_SITE_URL, - 'need_intervention_please_contact': _("Need human intervention? Contact"), - 'sitesupportemail': CFG_SITE_SUPPORT_EMAIL - } - return out + +def attach_embed_image(email, image_id, image_path): + """ + Attach an image to the email. + """ + with open(image_path, 'rb') as image_data: + img = MIMEImage(image_data.read()) + img.add_header('Content-ID', '<%s>' % image_id) + img.add_header('Content-Disposition', 'attachment', filename=os.path.split(image_path)[1]) + email.attach(img) def forge_email(fromaddr, toaddr, subject, content, html_content='', html_images=None, usebcc=False, header=None, footer=None, html_header=None, html_footer=None, ln=CFG_SITE_LANG, charset=None, replytoaddr="", attachments=None): """Prepare email. Add header and footer if needed. @param fromaddr: [string] sender @param toaddr: [string or list-of-strings] list of receivers (if string, then receivers are separated by ',') @param usebcc: [bool] True for using Bcc in place of To @param subject: [string] subject of the email @param content: [string] content of the email @param html_content: [string] html version of the email @param html_images: [dict] dictionary of image id, image path @param header: [string] None for the default header @param footer: [string] None for the default footer @param ln: language @charset: [string] the content charset. By default is None which means to try to encode the email as ascii, then latin1 then utf-8. @param replytoaddr: [string or list-of-strings] to be used for the reply-to header of the email (if string, then receivers are separated by ',') @param attachments: list of paths of files to be attached. Alternatively, every element of the list could be a tuple: (filename, mimetype) @return: forged email as a string""" if html_images is None: html_images = {} - if header is None: - content = email_header(ln) + content - else: - content = header + content - if footer is None: - content += email_footer(ln) - else: - content += footer - - if charset is None: - (content, content_charset) = guess_minimum_encoding(content) - else: - content_charset = charset - - try: - subject = subject.encode('ascii') - except (UnicodeEncodeError, UnicodeDecodeError): - subject = Header(subject, 'utf-8') - - try: - fromaddr = fromaddr.encode('ascii') - except (UnicodeEncodeError, UnicodeDecodeError): - fromaddr = Header(fromaddr, 'utf-8') + content = render_template_to_string('mail_text.tpl', content=content, + header=header, footer=footer) if type(toaddr) is not str: toaddr = ','.join(toaddr) - try: - toaddr = toaddr.encode('ascii') - except (UnicodeEncodeError, UnicodeDecodeError): - toaddr = Header(toaddr, 'utf-8') if type(replytoaddr) is not str: replytoaddr = ','.join(replytoaddr) - try: - replytoaddr = replytoaddr.encode('ascii') - except (UnicodeEncodeError, UnicodeDecodeError): - replytoaddr = Header(replytoaddr, 'utf-8') toaddr = remove_temporary_emails(toaddr) + headers = {} + kwargs = {'to': [], 'cc': [], 'bcc': []} + + if replytoaddr: + headers['Reply-To'] = replytoaddr + if usebcc: + headers['Bcc'] = toaddr + kwargs['bcc'] = toaddr.split(',') + kwargs['to'] = ['Undisclosed.Recipients:'] + else: + kwargs['to'] = toaddr.split(',') + headers['From'] = fromaddr + headers['Date'] = formatdate(localtime=True) + headers['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL) + if html_content: - if html_header is None: - html_content = email_html_header(ln) + html_content - else: - html_content = html_header + html_content - if html_footer is None: - html_content += email_html_footer(ln) - else: - html_content += html_footer - - if charset is None: - (html_content, html_content_charset) = guess_minimum_encoding(html_content) - else: - html_content_charset = charset - - msg_root = MIMEMultipart('alternative') - msg_root.preamble = 'This is a multi-part message in MIME format.' - - msg_text = MIMEText(content, _charset=content_charset) - msg_root.attach(msg_text) - - msg_text = MIMEText(html_content, 'html', _charset=html_content_charset) - if not html_images: - # No image? Attach the HTML to the root - msg_root.attach(msg_text) - else: + html_content = render_template_to_string('mail_html.tpl', + content=html_content, + header=html_header, + footer=html_footer) + + msg_root = EmailMultiAlternatives(subject=subject, body=content, + from_email=fromaddr, + headers=headers, **kwargs) + msg_root.attach_alternative(html_content, "text/html") + + #if not html_images: + # # No image? Attach the HTML to the root + # msg_root.attach(msg_text) + #else: + if html_images: # Image(s)? Attach the HTML and image(s) as children of a # "related" block msg_related = MIMEMultipart('related') - msg_related.attach(msg_text) + #msg_related.attach(msg_text) for image_id, image_path in html_images.iteritems(): - msg_image = MIMEImage(open(image_path, 'rb').read()) - msg_image.add_header('Content-ID', '<%s>' % image_id) - msg_image.add_header('Content-Disposition', 'attachment', filename=os.path.split(image_path)[1]) - msg_related.attach(msg_image) + attach_embed_image(msg_related, image_id, image_path) msg_root.attach(msg_related) else: - msg_root = MIMEText(content, _charset=content_charset) + msg_root = EmailMessage(subject=subject, body=content, + from_email=fromaddr, headers=headers, **kwargs) if attachments: from invenio.bibdocfile import _mimes, guess_format_from_url - old_msg_root = msg_root - msg_root = MIMEMultipart() - msg_root.attach(old_msg_root) + #old_msg_root = msg_root + #msg_root = MIMEMultipart() + #msg_root.attach(old_msg_root) for attachment in attachments: try: + mime = None if type(attachment) in (list, tuple): attachment, mime = attachment if mime is None: ## Automatic guessing of mimetype mime = _mimes.guess_type(attachment)[0] if mime is None: ext = guess_format_from_url(attachment) mime = _mimes.guess_type("foo" + ext)[0] if not mime: mime = 'application/octet-stream' part = MIMEBase(*mime.split('/', 1)) part.set_payload(open(attachment, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) msg_root.attach(part) except: register_exception(alert_admin=True, prefix="Can't attach %s" % attachment) - msg_root['From'] = fromaddr - if replytoaddr: - msg_root['Reply-To'] = replytoaddr - if usebcc: - msg_root['Bcc'] = toaddr - msg_root['To'] = 'Undisclosed.Recipients:' - else: - msg_root['To'] = toaddr - msg_root['Date'] = formatdate(localtime=True) - msg_root['Subject'] = subject - msg_root['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL) - return msg_root.as_string() + return msg_root RE_NEWLINES = re.compile(r'|

', re.I) RE_SPACES = re.compile(r'\s+') RE_HTML_TAGS = re.compile(r'<.+?>') + def email_strip_html(html_content): """Strip html tags from html_content, trying to respect formatting.""" html_content = RE_SPACES.sub(' ', html_content) html_content = RE_NEWLINES.sub('\n', html_content) html_content = RE_HTML_TAGS.sub('', html_content) html_content = html_content.split('\n') out = StringIO() out_format = AbstractFormatter(DumbWriter(out)) for row in html_content: out_format.add_flowing_data(row) out_format.end_paragraph(1) return out.getvalue() + def remove_temporary_emails(emails): """ Removes the temporary emails (which are constructed randomly when user logs in with an external authentication provider which doesn't supply an email address) from an email list. @param emails: email list (if string, then receivers are separated by ',') @type emails: str|[str] @rtype: str """ from invenio.access_control_config import CFG_TEMP_EMAIL_ADDRESS if not isinstance(emails, (str, unicode)): emails = ','.join(emails) # Remove all of the spaces emails = emails.replace(' ', '') # Remove all of the emails formatted like CFG_TEMP_EMAIL_ADDRESS emails = re.sub((CFG_TEMP_EMAIL_ADDRESS % '\w+') + '(,|$)', '', emails, re.IGNORECASE) # Remove all consecutive commas emails = re.sub(',+', ',', emails) if emails[0] == ',': # Remove the comma at the beginning of the string emails = emails[1:] if emails[-1] == ',': # Remove the comma at the end of the string emails = emails[:-1] return emails diff --git a/modules/miscutil/lib/mailutils_backend_adminonly.py b/modules/miscutil/lib/mailutils_backend_adminonly.py new file mode 100644 index 000000000..7447ddee3 --- /dev/null +++ b/modules/miscutil/lib/mailutils_backend_adminonly.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +## +## This file is part of Invenio. +## Copyright (C) 2013 CERN. +## +## Invenio is free software; you can redistribute it and/or +## modify it under the terms of the GNU General Public License as +## published by the Free Software Foundation; either version 2 of the +## License, or (at your option) any later version. +## +## Invenio is distributed in the hope that it will be useful, but +## WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +## General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with Invenio; if not, write to the Free Software Foundation, Inc., +## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +""" +Invenio Admin mail backend. send_email() will send emails only to +CFG_SITE_ADMIN_EMAIL. +""" + +__revision__ = "$Id$" + +from invenio.config import CFG_SITE_ADMIN_EMAIL +from flask.ext.email.backends.smtp import Mail as SMTP +from flask.ext.email.backends.console import Mail as Console + + +def adminonly_class(Backend): + """Admin only mail backend class factory.""" + + class _Mail(Backend): + + def send_messages(self, email_messages): + def process_message(m): + m.body = """ +#-------------------------------------------------------------- +#This message would have been sent to the following recipients: +#%s +#-------------------------------------------------------------- +#%s""" % (','.join(m.recipients()), m.body) + m.to = [CFG_SITE_ADMIN_EMAIL] + m.cc = [] + m.bcc = [] + if 'Cc' in m.extra_headers: + del m.extra_headers['Cc'] + if 'Bcc' in m.extra_headers: + del m.extra_headers['Bcc'] + return m + return super(_Mail, self).send_messages( + map(process_message, email_messages)) + + return _Mail + +SMTPMail = adminonly_class(SMTP) +ConsoleMail = adminonly_class(Console) + +__all__ = ['SMTPMail', 'ConsoleMail'] diff --git a/modules/miscutil/lib/mailutils_unit_tests.py b/modules/miscutil/lib/mailutils_unit_tests.py new file mode 100644 index 000000000..9d3c18577 --- /dev/null +++ b/modules/miscutil/lib/mailutils_unit_tests.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +## +## This file is part of Invenio. +## Copyright (C) 2013 CERN. +## +## Invenio is free software; you can redistribute it and/or +## modify it under the terms of the GNU General Public License as +## published by the Free Software Foundation; either version 2 of the +## License, or (at your option) any later version. +## +## Invenio is distributed in the hope that it will be useful, but +## WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +## General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with Invenio; if not, write to the Free Software Foundation, Inc., +## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +""" +Test unit for the miscutil/mailutils module. +""" + +import os +import sys +from base64 import encodestring +from StringIO import StringIO +from flask import current_app + +from invenio.mailutils import send_email +from invenio.testutils import make_test_suite, run_test_suite, InvenioTestCase + + +class MailTestCase(InvenioTestCase): + + EMAIL_BACKEND = 'flask.ext.email.backends.console.Mail' + + def setUp(self): + super(MailTestCase, self).setUp() + current_app.config['EMAIL_BACKEND'] = self.EMAIL_BACKEND + self.__stdout = sys.stdout + self.stream = sys.stdout = StringIO() + + def tearDown(self): + del self.stream + sys.stdout = self.__stdout + del self.__stdout + super(MailTestCase, self).tearDown() + + def flush_mailbox(self): + self.stream = sys.stdout = StringIO() + + #def get_mailbox_content(self): + # messages = self.stream.getvalue().split('\n' + ('-' * 79) + '\n') + # return [message_from_string(m) for m in messages if m] + + +class TestMailUtils(MailTestCase): + """ + mailutils TestSuite. + """ + + def test_console_send_email(self): + """ + Test that the console backend can be pointed at an arbitrary stream. + """ + msg_content = """Content-Type: text/plain; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Subject: Subject +From: from@example.com +To: to@example.com""" + + send_email('from@example.com', ['to@example.com'], subject='Subject', + content='Content') + self.assertIn(msg_content, sys.stdout.getvalue()) + self.flush_mailbox() + + send_email('from@example.com', 'to@example.com', subject='Subject', + content='Content') + self.assertIn(msg_content, sys.stdout.getvalue()) + self.flush_mailbox() + + + def test_email_text_template(self): + """ + Test email text template engine. + """ + from invenio.jinja2utils import render_template_to_string + + contexts = { + 'ctx1': {'content': 'Content 1'}, + 'ctx2': {'content': 'Content 2', 'header': 'Header 2'}, + 'ctx3': {'content': 'Content 3', 'footer': 'Footer 3'}, + 'ctx4': {'content': 'Content 4', 'header': 'Header 4', 'footer': 'Footer 4'} + } + + msg_content = """Content-Type: text/plain; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Subject: %s +From: from@example.com +To: to@example.com""" + + for name, ctx in contexts.iteritems(): + msg = render_template_to_string('mail_text.tpl', **ctx) + send_email('from@example.com', ['to@example.com'], subject=name, + **ctx) + email = sys.stdout.getvalue() + self.assertIn(msg_content % name, email) + self.assertIn(msg, email) + self.flush_mailbox() + + def test_email_html_template(self): + """ + Test email html template engine. + """ + from invenio.jinja2utils import render_template_to_string + + contexts = { + 'ctx1': {'html_content': 'Content 1'}, + 'ctx2': {'html_content': 'Content 2', + 'html_header': '

Header 2

'}, + 'ctx3': {'html_content': 'Content 3', + 'html_footer': 'Footer 3'}, + 'ctx4': {'html_content': 'Content 4', + 'html_header': '

Header 4

', + 'html_footer': 'Footer 4'} + } + + def strip_html_key(ctx): + return dict(map(lambda (k, v): (k[5:], v), ctx.iteritems())) + + for name, ctx in contexts.iteritems(): + msg = render_template_to_string('mail_html.tpl', + **strip_html_key(ctx)) + send_email('from@example.com', ['to@example.com'], subject=name, + content='Content Text', **ctx) + email = sys.stdout.getvalue() + self.assertIn('Content-Type: multipart/alternative;', email) + self.assertIn('Content Text', email) + self.assertIn(msg, email) + self.flush_mailbox() + + def test_email_html_image(self): + """ + Test sending html message with an image. + """ + from invenio.config import CFG_WEBDIR + html_images = { + 'img1': os.path.join(CFG_WEBDIR, 'img', 'journal_water_dog.gif') + } + send_email('from@example.com', ['to@example.com'], + subject='Subject', content='Content Text', + html_content='', + html_images=html_images) + email = sys.stdout.getvalue() + self.assertIn('Content Text', email) + self.assertIn('', email) + with open(html_images['img1'], 'r') as f: + self.assertIn(encodestring(f.read()), email) + self.flush_mailbox() + + def test_sending_attachment(self): + """ + Test sending email with an attachment. + """ + from invenio.config import CFG_WEBDIR + attachments = [ + os.path.join(CFG_WEBDIR, 'img', 'journal_header.png') + ] + send_email('from@example.com', ['to@example.com'], + subject='Subject', content='Content Text', + attachments=attachments) + email = sys.stdout.getvalue() + self.assertIn('Content Text', email) + # First attachemnt is image/png + self.assertIn('Content-Type: image/png', email) + for attachment in attachments: + with open(attachment, 'r') as f: + self.assertIn(encodestring(f.read()), email) + self.flush_mailbox() + + def test_bbc_undisclosed_recipients(self): + """ + Test that the email receivers are hidden. + """ + msg_content = """Content-Type: text/plain; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Subject: Subject +From: from@example.com +To: Undisclosed.Recipients:""" + + send_email('from@example.com', ['to@example.com', 'too@example.com'], + subject='Subject', content='Content') + email = sys.stdout.getvalue() + self.assertIn(msg_content, email) + self.assertIn('Bcc: to@example.com,too@example.com', email) + self.flush_mailbox() + + send_email('from@example.com', 'to@example.com, too@example.com', + subject='Subject', content='Content') + email = sys.stdout.getvalue() + self.assertIn(msg_content, email) + self.assertIn('Bcc: to@example.com,too@example.com', email) + self.flush_mailbox() + + +class TestAdminMailBackend(MailTestCase): + + EMAIL_BACKEND = 'invenio.mailutils_backend_adminonly.ConsoleMail' + ADMIN_MESSAGE = "This message would have been sent to the following recipients" + + def test_simple_email_header(self): + """ + Test simple email header. + """ + from invenio.config import CFG_SITE_ADMIN_EMAIL + from invenio.jinja2utils import render_template_to_string + + msg_content = """Content-Type: text/plain; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Subject: Subject +From: from@example.com +To: %s""" % (CFG_SITE_ADMIN_EMAIL, ) + + msg = render_template_to_string('mail_text.tpl', content='Content') + + send_email('from@example.com', ['to@example.com'], subject='Subject', + content='Content') + email = sys.stdout.getvalue() + self.assertIn(msg_content, email) + self.assertIn(self.ADMIN_MESSAGE, email) + self.assertNotIn('Bcc:', email) + self.assertIn(msg, email) + self.flush_mailbox() + + send_email('from@example.com', 'to@example.com', subject='Subject', + content='Content') + email = sys.stdout.getvalue() + self.assertIn(msg_content, email) + self.assertIn(self.ADMIN_MESSAGE, email) + self.assertNotIn('Bcc:', email) + self.assertIn(msg, email) + self.flush_mailbox() + + + def test_cc_bcc_headers(self): + """ + Test that no Cc and Bcc headers are sent. + """ + from invenio.config import CFG_SITE_ADMIN_EMAIL + msg_content = """Content-Type: text/plain; charset="utf-8" +MIME-Version: 1.0 +Content-Transfer-Encoding: 7bit +Subject: Subject +From: from@example.com +To: %s""" % (CFG_SITE_ADMIN_EMAIL, ) + + send_email('from@example.com', ['to@example.com', 'too@example.com'], + subject='Subject', content='Content') + email = sys.stdout.getvalue() + self.assertIn(msg_content, email) + self.assertIn(self.ADMIN_MESSAGE, email) + self.assertIn('to@example.com,too@example.com', email) + self.assertNotIn('Bcc: to@example.com,too@example.com', email) + self.flush_mailbox() + + send_email('from@example.com', 'to@example.com, too@example.com', + subject='Subject', content='Content') + email = sys.stdout.getvalue() + self.assertIn(msg_content, email) + self.assertIn(self.ADMIN_MESSAGE, email) + self.assertIn('to@example.com,too@example.com', email) + self.assertNotIn('Bcc: to@example.com,too@example.com', email) + self.flush_mailbox() + + +TEST_SUITE = make_test_suite(TestMailUtils, TestAdminMailBackend) + +if __name__ == "__main__": + run_test_suite(TEST_SUITE) diff --git a/modules/webmessage/lib/webmessage_model.py b/modules/webmessage/lib/webmessage_model.py index 1447f2f50..bee5db7d5 100644 --- a/modules/webmessage/lib/webmessage_model.py +++ b/modules/webmessage/lib/webmessage_model.py @@ -1,218 +1,218 @@ # -*- coding: utf-8 -*- # ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ WebMessage database models. """ # General imports from invenio.sqlalchemyutils import db # Create your models here. from string import strip from invenio.websession_model import User, Usergroup from invenio.webmessage_config import CFG_WEBMESSAGE_SEPARATOR from sqlalchemy.ext.associationproxy import association_proxy class MsgMESSAGE(db.Model): """Represents a MsgMESSAGE record.""" def __str__(self): return "From: %s<%s>, Subject: <%s> %s" % \ (self.user_from.nickname or _('None'), self.user_from.email or _('unknown'), self.subject, self.body) __tablename__ = 'msgMESSAGE' id = db.Column(db.Integer(15, unsigned=True), nullable=False, primary_key=True, autoincrement=True) id_user_from = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id), nullable=True, server_default='0') _sent_to_user_nicks = db.Column(db.Text, name='sent_to_user_nicks', nullable=False) _sent_to_group_names = db.Column(db.Text, name='sent_to_group_names', nullable=False) subject = db.Column(db.Text, nullable=False) body = db.Column(db.Text, nullable=True) sent_date = db.Column(db.DateTime, nullable=False, server_default='0001-01-01 00:00:00') # db.func.now() -> 'NOW()' received_date = db.Column(db.DateTime, server_default='0001-01-01 00:00:00') user_from = db.relationship(User, backref='sent_messages') #recipients = db.relationship(User, # secondary=lambda: UserMsgMESSAGE.__table__, # collection_class=set) recipients = association_proxy('sent_to_users', 'user_to', creator=lambda u:UserMsgMESSAGE(user_to=u)) @db.hybrid_property def sent_to_user_nicks(self): """ Alias for column 'sent_to_user_nicks'. """ return self._sent_to_user_nicks @db.hybrid_property def sent_to_group_names(self): """ Alias for column 'sent_to_group_names'. """ return self._sent_to_group_names @db.validates('_sent_to_user_nicks') def validate_sent_to_user_nicks(self, key, value): user_nicks = filter(len, map(strip, value.split(CFG_WEBMESSAGE_SEPARATOR))) assert len(user_nicks) == len(set(user_nicks)) if len(user_nicks) > 0: assert len(user_nicks) == \ User.query.filter(User.nickname.in_(user_nicks)).count() return CFG_WEBMESSAGE_SEPARATOR.join(user_nicks) @db.validates('_sent_to_group_names') def validate_sent_to_group_names(self, key, value): group_names = filter(len, map(strip, value.split(CFG_WEBMESSAGE_SEPARATOR))) assert len(group_names) == len(set(group_names)) if len(group_names) > 0: assert len(group_names) == \ Usergroup.query.filter(Usergroup.name.in_(group_names)).count() return CFG_WEBMESSAGE_SEPARATOR.join(group_names) @sent_to_user_nicks.setter def sent_to_user_nicks(self, value): old_user_nicks = self.user_nicks self._sent_to_user_nicks = value to_add = set(self.user_nicks)-set(old_user_nicks) to_del = set(old_user_nicks)-set(self.user_nicks) if len(self.group_names): to_del = to_del-set([u.nickname for u in User.query.\ join(User.usergroups).filter( Usergroup.name.in_(self.group_names)).\ all()]) if len(to_del): is_to_del = lambda u: u.nickname in to_del remove_old = filter(is_to_del, self.recipients) for u in remove_old: self.recipients.remove(u) if len(to_add): for u in User.query.filter(User.nickname.\ in_(to_add)).all(): if u not in self.recipients: self.recipients.append(u) @sent_to_group_names.setter def sent_to_group_names(self, value): old_group_names = self.group_names self._sent_to_group_names = value groups_to_add = set(self.group_names)-set(old_group_names) groups_to_del = set(old_group_names)-set(self.group_names) if len(groups_to_del): to_del = set([u.nickname for u in User.query.\ join(User.usergroups).filter( Usergroup.name.in_(groups_to_del)).\ all()])-set(self.user_nicks) is_to_del = lambda u: u.nickname in to_del remove_old = filter(is_to_del, self.recipients) for u in remove_old: self.recipients.remove(u) if len(groups_to_add): for u in User.query.join(User.usergroups).filter(db.and_( Usergroup.name.in_(groups_to_add), db.not_(User.nickname.in_(self.user_nicks)))).all(): if u not in self.recipients: self.recipients.append(u) @property def user_nicks(self): if not self._sent_to_user_nicks: return [] return filter(len, map(strip, self._sent_to_user_nicks.split(CFG_WEBMESSAGE_SEPARATOR))) @property def group_names(self): if not self._sent_to_group_names: return [] return filter(len, map(strip, self.sent_to_group_names.split(CFG_WEBMESSAGE_SEPARATOR))) #TODO consider moving following lines to separate file. from invenio.webmessage_config import CFG_WEBMESSAGE_EMAIL_ALERT from invenio.config import CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL -from invenio.mailutils import send_email, scheduled_send_email -from invenio.jinja2utils import render_template_to_string from invenio.dateutils import datetext_format from datetime import datetime def email_alert(mapper, connection, target): """ Sends email alerts to message recipients. """ + from invenio.jinja2utils import render_template_to_string + from invenio.mailutils import send_email, scheduled_send_email m = target is_reminder = m.received_date is not None \ and m.received_date > datetime.now() alert = send_email if is_reminder: alert = lambda *args, **kwargs: scheduled_send_email(*args, other_bibtasklet_arguments=[ m.received_date.strftime(datetext_format)], **kwargs) for u in m.recipients: if isinstance(u.settings, dict) and \ u.settings.get('webmessage_email_alert', True): try: alert( CFG_WEBCOMMENT_ALERT_ENGINE_EMAIL, u.email, subject = m.subject, content = render_template_to_string( 'webmessage_email_alert.html', message=m, user=u)) except: # FIXME tests are not in request context pass if CFG_WEBMESSAGE_EMAIL_ALERT: from sqlalchemy import event # Register after insert callback. event.listen(MsgMESSAGE, 'after_insert', email_alert) class UserMsgMESSAGE(db.Model): """Represents a UserMsgMESSAGE record.""" __tablename__ = 'user_msgMESSAGE' id_user_to = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id), nullable=False, server_default='0', primary_key=True) id_msgMESSAGE = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(MsgMESSAGE.id), nullable=False, server_default='0', primary_key=True) status = db.Column(db.Char(1), nullable=False, server_default='N') user_to = db.relationship(User, backref='received_messages', collection_class=set) message = db.relationship(MsgMESSAGE, backref='sent_to_users', collection_class=set) __all__ = ['MsgMESSAGE', 'UserMsgMESSAGE'] diff --git a/modules/webstyle/lib/webinterface_handler_flask.py b/modules/webstyle/lib/webinterface_handler_flask.py index c7c7a80aa..328b11b2e 100644 --- a/modules/webstyle/lib/webinterface_handler_flask.py +++ b/modules/webstyle/lib/webinterface_handler_flask.py @@ -1,642 +1,645 @@ # -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2011, 2012, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Invenio -> Flask adapter """ ## Import the remote debugger as a first thing, if allowed try: from invenio import remote_debugger except: remote_debugger = None import os from os.path import join from pprint import pformat from functools import wraps from logging.handlers import RotatingFileHandler from logging import Formatter from flask import Flask, session, request, g, url_for, current_app, \ render_template, redirect, flash, abort, has_app_context from jinja2 import FileSystemLoader, MemcachedBytecodeCache from werkzeug.routing import BuildError from invenio import config from invenio.errorlib import register_exception from invenio.config import CFG_PYLIBDIR, \ CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER, \ CFG_BIBDOCFILE_USE_XSENDFILE, \ CFG_LOGDIR, CFG_SITE_LANG, CFG_WEBDIR, \ CFG_ETCDIR, CFG_DEVEL_SITE, \ CFG_FLASK_CACHE_TYPE, CFG_FLASK_DISABLED_BLUEPRINTS, \ CFG_SITE_URL, CFG_SITE_SECURE_URL, CFG_FLASK_SERVE_STATIC_FILES, \ CFG_SITE_SECRET_KEY, CFG_BINDIR from invenio.websession_config import CFG_WEBSESSION_COOKIE_NAME, \ CFG_WEBSESSION_ONE_DAY CFG_HAS_HTTPS_SUPPORT = CFG_SITE_SECURE_URL.startswith("https://") CFG_FULL_HTTPS = CFG_SITE_URL.lower().startswith("https://") def create_invenio_flask_app(**kwargs_config): """ Prepare WSGI Invenio application based on Flask. Invenio consists of a new Flask application with legacy support for the old WSGI legacy application and the old Python legacy scripts (URLs to *.py files). An incoming request is processed in the following manner: * The Flask application first routes request via its URL routing system (see LegacyAppMiddleware.__call__()). * One route in the Flask system, will match Python legacy scripts (see static_handler_with_legacy_publisher()). * If the Flask application aborts the request with a 404 error, the request is passed on to the WSGI legacy application (see page_not_found()). E.g. either the Flask application did not find a route, or a view aborted the request with a 404 error. """ ## The Flask application instance _app = Flask(__name__, ## Static files are usually handled directly by the webserver (e.g. Apache) ## However in case WSGI is required to handle static files too (such ## as when running simple server), then this flag can be ## turned on (it is done automatically by wsgi_handler_test). ## We assume anything under '/' which is static to be server directly ## by the webserver from CFG_WEBDIR. In order to generate independent ## url for static files use func:`url_for('static', filename='test')`. static_url_path='', static_folder=CFG_WEBDIR) ## Update application config from parameters. _app.config.update(kwargs_config) if 'SQLALCHEMY_DATABASE_URI' not in _app.config: from sqlalchemy.engine.url import URL # Global variables from invenio.dbquery import CFG_DATABASE_HOST, CFG_DATABASE_PORT,\ CFG_DATABASE_NAME, CFG_DATABASE_USER, CFG_DATABASE_PASS, \ CFG_DATABASE_TYPE _app.config['SQLALCHEMY_DATABASE_URI'] = URL(CFG_DATABASE_TYPE, username=CFG_DATABASE_USER, password=CFG_DATABASE_PASS, host=CFG_DATABASE_HOST, database=CFG_DATABASE_NAME, port=CFG_DATABASE_PORT, ) ## Let's initialize database. from invenio.sqlalchemyutils import db db.init_app(_app) ## Make sure that all tables are loaded in `db.metadata.tables`. from invenio.importutils import autodiscover_modules autodiscover_modules(['invenio'], related_name_re=".+_model\.py") ## First check that you have all rights to logs from invenio.bibtask import check_running_process_user check_running_process_user() from invenio.pluginutils import PluginContainer from invenio.session_flask import InvenioSessionInterface from invenio.webuser_flask import InvenioLoginManager, current_user from invenio.messages import wash_language, gettext_set_language, \ language_list_long, is_language_rtl from invenio.urlutils import create_url, get_canonical_and_alternates_urls from invenio.cache import cache from invenio.jinja2utils import CollectionExtension, \ LangExtension, hack_jinja2_utf8decoding, \ extend_application_template_filters from flask.ext.assets import Environment, Bundle from invenio.webinterface_handler_flask_utils import unicodifier, InvenioRequest from flaskext.gravatar import Gravatar from werkzeug.wrappers import BaseResponse from werkzeug.exceptions import HTTPException from invenio.flask_sslify import SSLify from invenio.webinterface_handler_wsgi import application as legacy_application from invenio.webinterface_handler_wsgi import is_mp_legacy_publisher_path, \ mp_legacy_publisher # See note on Jinja2 string decoding using ASCII codec instead of UTF8 in # function documentation hack_jinja2_utf8decoding() # Handle both url with and without trailing slashe by Flask. # @blueprint.route('/test') # @blueprint.route('/test/') -> not necessary when strict_slashes == False _app.url_map.strict_slashes = False # SECRET_KEY is needed by Flask Debug Toolbar SECRET_KEY = _app.config.get('SECRET_KEY') or CFG_SITE_SECRET_KEY if not SECRET_KEY or SECRET_KEY == '': fill_secret_key = """ Set variable CFG_SITE_SECRET_KEY with random string in invenio-local.conf. You can use following commands: $ %s $ %s """ % (CFG_BINDIR + os.sep + 'inveniocfg --create-secret-key', CFG_BINDIR + os.sep + 'inveniocfg --update-config-py') try: raise Exception(fill_secret_key) except Exception: register_exception(alert_admin=True, subject="Missing CFG_SITE_SECRET_KEY") raise Exception(fill_secret_key) _app.config["SECRET_KEY"] = SECRET_KEY # Enable Flask Debug Toolbar early to also catch HTTPS redirects if 'debug-toolbar' in getattr(config, 'CFG_DEVEL_TOOLS', []): _app.config["DEBUG_TB_ENABLED"] = True _app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = 'intercept-redirects' in getattr(config, 'CFG_DEVEL_TOOLS', []) from flask_debugtoolbar import DebugToolbarExtension DebugToolbarExtension(_app) + # Set email backend for Flask-Email plugin + from invenio.mailutils import initialize_email_backend + initialize_email_backend(_app) if CFG_HAS_HTTPS_SUPPORT: # Makes request always run over HTTPS. _sslify = SSLify(_app) if not CFG_FULL_HTTPS: @_sslify.criteria_handler def criteria(): """Extends criteria when to stay on HTTP site.""" _force_https = False if request.blueprint in current_app.blueprints: _force_https = current_app.blueprints[request.blueprint].\ _force_https view_func = current_app.view_functions.get(request.endpoint) if view_func is not None and hasattr(view_func, '_force_https'): _force_https = view_func._force_https return not (_force_https or session.need_https()) class LegacyAppMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): if remote_debugger: remote_debugger.start() with self.app.request_context(environ): g.start_response = start_response try: response = self.app.full_dispatch_request() except Exception as e: register_exception(req=request, alert_admin=True) response = self.app.handle_exception(e) return response(environ, start_response) _app.wsgi_app = LegacyAppMiddleware(_app) @_app.errorhandler(404) def page_not_found(error): try: response = legacy_application(request.environ, g.start_response) if not isinstance(response, BaseResponse): response = current_app.make_response(str(response)) return response except HTTPException: return render_template("404.html"), 404 @_app.errorhandler(401) def do_login_first(error=401): """Displays login page when user is not authorised.""" if request.is_xhr: return _("Authorization failure"), 401 flash(_("Authorization failure"), 'error') from invenio.webaccount_blueprint import login return login(referer=request.referrer), 401 @_app.endpoint('static') @_app.route(_app.static_url_path + '/', methods=['POST']) def static_handler_with_legacy_publisher(*args, **kwargs): """ Adds support for legacy publisher. NOTE: It changes order of url page lookup. First, the invenio_handler will be called and on 404 error the mp_legacy_publisher is called. """ possible_module, possible_handler = is_mp_legacy_publisher_path( request.environ['PATH_INFO']) if possible_module is not None: legacy_publisher = lambda req: \ mp_legacy_publisher(req, possible_module, possible_handler) return legacy_application(request.environ, g.start_response, handler=legacy_publisher) # Static file serving for devserver # --------------------------------- # Apache normally serve all static files, but if we are using the # devserver we need to serve static files here. Werkzeugs default # behaviour is to return a '405 Method not allowed' for POST requests # to static files. However, if we abort all POST requests with 405, the # legacy_application (see page_not_found()) will not be given a chance # to serve static files as it only get's invokved when we abort with a # 404. Hence, on POST requests, we first check if the static file exists, # and if it does we return we abort the request with a 405. if not CFG_FLASK_SERVE_STATIC_FILES: abort(404) else: static_file_response = _app.send_static_file(*args, **kwargs) if request.method == 'POST': abort(405) else: return static_file_response if CFG_FLASK_CACHE_TYPE not in [None, 'null']: _app.jinja_options = dict(_app.jinja_options, auto_reload=False, cache_size=-1, bytecode_cache=MemcachedBytecodeCache( cache, prefix="jinja::", timeout=3600)) ## Let's customize the template loader to first look into ## /opt/invenio/etc-local/templates and then into ## /opt/invenio/etc/templates _app.jinja_loader = FileSystemLoader([join(CFG_ETCDIR + '-local', 'templates'), join(CFG_ETCDIR, 'templates')]) ## Let's attach our session handling (which is bridging with the native ## Invenio session handling _app.session_interface = InvenioSessionInterface() ## Set custom request class _app.request_class = InvenioRequest ## Let's load the whole invenio.config into Flask :-) ... _app.config.from_object(config) ## ... and map certain common parameters _app.config['SESSION_COOKIE_NAME'] = CFG_WEBSESSION_COOKIE_NAME _app.config['PERMANENT_SESSION_LIFETIME'] = \ CFG_WEBSESSION_EXPIRY_LIMIT_REMEMBER * CFG_WEBSESSION_ONE_DAY _app.config['USE_X_SENDFILE'] = CFG_BIBDOCFILE_USE_XSENDFILE _app.config['DEBUG'] = CFG_DEVEL_SITE > 0 _app.debug = CFG_DEVEL_SITE > 0 _app.config['CFG_LANGUAGE_LIST_LONG'] = [(lang, longname.decode('utf-8')) for (lang, longname) in language_list_long()] ## Invenio is all using str objects. Let's change them to unicode _app.config.update(unicodifier(dict(_app.config))) ## Cache _app.config['CACHE_TYPE'] = CFG_FLASK_CACHE_TYPE # FIXME problem in Flask-Cache==0.11.1 cache.app = _app cache.init_app(_app) if CFG_FLASK_CACHE_TYPE == 'redis': def with_try_except_block(f): def decorator(*args, **kwargs): try: return f(*args, **kwargs) except Exception: register_exception(alert_admin=True) pass return decorator ## When the redis is down, we would like to keep the site running. cache.cache._client.execute_command = with_try_except_block( cache.cache._client.execute_command) # FIXME problem in Flask-Cache==0.11.1 cache.app = current_app _flask_log_handler = RotatingFileHandler(os.path.join(CFG_LOGDIR, 'flask.log')) _flask_log_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) _app.logger.addHandler(_flask_log_handler) # Let's create login manager. _login_manager = InvenioLoginManager() _login_manager.login_view = 'webaccount.login' _login_manager.setup_app(_app) _login_manager.unauthorized_handler(do_login_first) # Let's create main menu. class Menu(object): def __init__(self, id='', title='', url='', order=None, children=None, display=lambda: True): self.id = id self.title = title self.url = url self.children = children or {} self.order = order or 100 self.display = display # Let's create assets environment. _assets = Environment(_app) _assets.debug = 'assets-debug' in getattr(config, 'CFG_DEVEL_TOOLS', []) _assets.directory = config.CFG_WEBDIR def _jinja2_new_bundle(tag, collection, name=None): if not _assets.debug: files = [f for f in collection if os.path.isfile( os.path.join(_assets.directory, f))] if len(files) != len(collection): ## Turn on debuging to generate 404 request on missing files. _assets.debug = True current_app.logger.error('Missing files: ' + ','.join( set(collection) - set(files))) if len(collection): return Bundle(output="%s/%s-%s.%s" % (tag, 'invenio' if name is None else name, hash('|'.join(collection)), tag), *collection) _app.jinja_env.extend(new_bundle=_jinja2_new_bundle, default_bundle_name='90-invenio') _app.jinja_env.add_extension(CollectionExtension) _app.jinja_env.add_extension(LangExtension) _app.jinja_env.add_extension('jinja2.ext.do') # Let's extend application with custom template filters. extend_application_template_filters(_app) # Let's create Gravatar bridge. _gravatar = Gravatar(_app, size=100, rating='g', default='retro', force_default=False, force_lower=False) del _gravatar @_login_manager.user_loader def _load_user(uid): """ Function should not raise an exception if uid is not valid or User was not found in database. """ from invenio.webuser_flask import UserInfo return UserInfo(uid) @_app.before_request def reset_template_context_processor(): g._template_context_processor = [] @_app.context_processor def _inject_template_context(): context = {} if not hasattr(g, '_template_context_processor'): reset_template_context_processor() for func in g._template_context_processor: context.update(func()) return context @_app.before_request def _guess_language(): """ Before every request being handled, let's compute the language needed to return the answer to the client. This information will then be available in the session['ln'] and in g.ln. Additionally under g._ an already configured internationalization function will be available (configured to return unicode objects). """ required_ln = None try: values = request.values except: values = {} if "ln" in values: ## If ln is specified explictly as a GET or POST argument ## let's take it! passed_ln = str(values["ln"]) required_ln = wash_language(passed_ln) if passed_ln != required_ln: ## But only if it was a valid language required_ln = None if required_ln: ## Ok it was. We store it in the session. session["ln"] = required_ln if not "ln" in session: ## If there is no language saved into the session... if "user_info" in session and session["user_info"].get("language"): ## ... and the user is logged in, we try to take it from its ## settings. session["ln"] = session["user_info"]["language"] else: ## Otherwise we try to guess it from its request headers for value, quality in request.accept_languages: value = str(value) ln = wash_language(value) if ln == value or ln[:2] == value[:2]: session["ln"] = ln break else: ## Too bad! We stick to the default :-) session["ln"] = CFG_SITE_LANG ## Well, let's make it global now g.ln = session["ln"] g._ = gettext_set_language(g.ln, use_unicode=True) @_app.context_processor def _inject_utils(): """ This will add some more variables and functions to the Jinja2 to execution context. In particular it will add: - `url_for`: an Invenio specific wrapper of Flask url_for, that will let you obtain URLs for non Flask-native handlers (i.e. not yet ported Invenio URLs) - `breadcrumbs`: this will be a list of three-elements tuples, containing the hierarchy of Label -> URLs of navtrails/breadcrumbs. - `_`: this can be used to automatically translate a given string. - `is_language_rtl`: is True if the chosen language should be read right to left """ def invenio_url_for(endpoint, **values): try: return url_for(endpoint, **values) except BuildError: if endpoint.startswith('http://') or endpoint.startswith('https://'): return endpoint if endpoint.startswith('.'): endpoint = request.blueprint + endpoint return create_url('/' + '/'.join(endpoint.split('.')), values, False).decode('utf-8') if request.endpoint in current_app.config['breadcrumbs_map']: breadcrumbs = current_app.config['breadcrumbs_map'][request.endpoint] elif request.endpoint: breadcrumbs = [(_('Home'), '')] + current_app.config['breadcrumbs_map'].get(request.endpoint.split('.')[0], []) else: breadcrumbs = [(_('Home'), '')] user = current_user._get_current_object() canonical_url, alternate_urls = get_canonical_and_alternates_urls( request.environ['PATH_INFO']) alternate_urls = dict((ln.replace('_', '-'), alternate_url) for ln, alternate_url in alternate_urls.iteritems()) _guess_language() from invenio.bibfield import get_record # should not be global due to bibfield_config return dict(_=lambda *args, **kwargs: g._(*args, **kwargs), current_user=user, get_css_bundle=_app.jinja_env.get_css_bundle, get_js_bundle=_app.jinja_env.get_js_bundle, is_language_rtl=is_language_rtl, canonical_url=canonical_url, alternate_urls=alternate_urls, get_record=get_record, url_for=invenio_url_for, breadcrumbs=breadcrumbs, ) def _invenio_blueprint_plugin_builder(plugin_name, plugin_code): """ Handy function to bridge pluginutils with (Invenio) blueprints. """ if plugin_name in CFG_FLASK_DISABLED_BLUEPRINTS: raise ValueError('%s is excluded by CFG_FLASK_DISABLED_BLUEPRINTS' % plugin_name) from invenio.webinterface_handler_flask_utils import InvenioBlueprint if 'blueprint' in dir(plugin_code): candidate = getattr(plugin_code, 'blueprint') if isinstance(candidate, InvenioBlueprint): return candidate raise ValueError('%s is not a valid blueprint plugin' % plugin_name) ## Let's load all the blueprints that are composing this Invenio instance _BLUEPRINTS = PluginContainer( os.path.join(CFG_PYLIBDIR, 'invenio', '*_blueprint.py'), plugin_builder=_invenio_blueprint_plugin_builder) ## Let's report about broken plugins open(join(CFG_LOGDIR, 'broken-blueprints.log'), 'w').write( pformat(_BLUEPRINTS.get_broken_plugins())) _app.config['breadcrumbs_map'] = {} _app.config['menubuilder_map'] = {} ## Let's attach all the blueprints from invenio.webinterface_handler_flask_utils import _ for plugin in _BLUEPRINTS.values(): _app.register_blueprint(plugin) if plugin.config: ## Let's include the configuration parameters of the config file. ## E.g. if the blueprint specify the config string ## 'invenio.webmessage_config' any uppercase variable defined in ## the module invenio.webmessage_config is loaded into the system. _app.config.from_object(plugin.config) if plugin.breadcrumbs: _app.config['breadcrumbs_map'][plugin.name] = plugin.breadcrumbs _app.config['breadcrumbs_map'].update(plugin.breadcrumbs_map) ## Let's build global menu. Each blueprint can plug its own menu items. if plugin.menubuilder: _app.config['menubuilder_map'].update((m[0], Menu(*m)) for m in plugin.menubuilder) _app.config['menubuilder_map'].update(plugin.menubuilder_map) _app.config['menubuilder_map'].update({ 'main.admin': Menu('main.admin', _('Administration'), 'help.admin', 9998, [], lambda: current_user.is_admin), 'main.help': Menu('main.help', _('Help'), 'help', 9999)}) menu = {'main': Menu('main', '', ''), 'personalize': Menu('personalize', '', '')} for key, item in _app.config['menubuilder_map'].iteritems(): start = menu if '.' not in key: if key in menu: menu[key] = item.children.update(menu[key].children) else: menu[key] = item continue keys = key.split('.') for k in keys[:-1]: try: start = start[k].children except: start[k] = Menu() start = start[k].children if keys[-1] in start: item.children.update(start[keys[-1]].children) start[keys[-1]] = item _app.config['menubuilder_map'] = menu # Flask-Admin from invenio.adminutils import register_admin register_admin(_app) try: ## When deploying Invenio, one can prepare a module called ## webinterface_handler_local.py to be deployed under ## CFG_PYLIBDIR/invenio directory, and containing a function called ## customize_app which should accept a Flask application. ## This function has a chance to modify the application as needed ## including changing the URL routing map. # pylint: disable=E0611 from invenio.webinterface_handler_local import customize_app # pylint: enable=E0611 customize_app(_app) except ImportError: ## No customization needed. pass return _app def with_app_context(app=None, new_context=False, **kwargs_config): """Run function within application context""" def get_application(): if app is None: application = create_invenio_flask_app(**kwargs_config) elif not isinstance(app, Flask) and callable(app): application = app(**kwargs_config) return application def decorator(f): @wraps(f) def decorated_func(*args, **kwargs): """This function has to run within application context.""" if not has_app_context() or new_context: with get_application().app_context(): current_app.preprocess_request() result = f(*args, **kwargs) else: result = f(*args, **kwargs) return result return decorated_func return decorator diff --git a/requirements-flask-ext.txt b/requirements-flask-ext.txt index 960f3bb30..c16b43c33 100644 --- a/requirements-flask-ext.txt +++ b/requirements-flask-ext.txt @@ -1,9 +1,10 @@ Flask-Assets==0.7 Flask-Cache==0.11.1 Flask-DebugToolbar==0.7.1 +Flask-Email==1.4.4 Flask-Gravatar==0.2.3 Flask-Script==0.5.3 Flask-SQLAlchemy==0.16 Flask-Testing==0.4 Flask-WTF==0.8 -Flask-Admin==1.0.6 \ No newline at end of file +Flask-Admin==1.0.6