# copyright 2003-2016 LOGILAB S.A. (Paris, FRANCE), all rights reserved.# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr## This file is part of CubicWeb.## CubicWeb is free software: you can redistribute it and/or modify it under the# terms of the GNU Lesser General Public License as published by the Free# Software Foundation, either version 2.1 of the License, or (at your option)# any later version.## CubicWeb 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 Lesser General Public License for more# details.## You should have received a copy of the GNU Lesser General Public License along# with CubicWeb. If not, see <http://www.gnu.org/licenses/>."""CubicWeb is a generic framework to quickly build applications which describesrelations between entitites."""importloggingimportosimportpickleimportsysimportwarningsimportzlibfromlogilab.common.logging_extimportset_log_methodsfromyams.constraintsimportBASE_CONVERTERS,BASE_CHECKERSfromyams.schemaimportrole_nameasrnamefromcubicweb.__pkginfo__importversionas__version__# noqa# make all exceptions accessible from the packagefromlogilab.common.registryimportObjectNotFound,NoSelectableObject,RegistryNotFound# noqafromyamsimportValidationErrorfromcubicweb._exceptionsimport*# noqafromioimportBytesIO# ignore the pygments UserWarningswarnings.filterwarnings('ignore',category=UserWarning,message='.*was already imported',module='.*pygments')# pre python 2.7.2 safetylogging.basicConfig()set_log_methods(sys.modules[__name__],logging.getLogger('cubicweb'))# this is necessary for i18n devtools test where chdir is done while __path__ is relative, which# breaks later imports__path__[0]=os.path.abspath(__path__[0])# noqaCW_SOFTWARE_ROOT=__path__[0]# noqa# '_' is available to mark internationalized string but should not be used to# do the actual translation_=strclassBinary(BytesIO):"""class to hold binary data. Use BytesIO to prevent use of unicode data"""_allowed_types=(bytes,bytearray,memoryview)def__init__(self,buf=b''):assertisinstance(buf,self._allowed_types), \"Binary objects must use bytes/buffer objects, not %s"%buf.__class__# don't call super, BytesIO may be an old-style class (on python < 2.7.4)BytesIO.__init__(self,buf)defwrite(self,data):assertisinstance(data,self._allowed_types), \"Binary objects must use bytes/buffer objects, not %s"%data.__class__# don't call super, BytesIO may be an old-style class (on python < 2.7.4)BytesIO.write(self,data)defto_file(self,fobj):"""write a binary to disk the writing is performed in a safe way for files stored on Windows SMB shares """pos=self.tell()self.seek(0)ifsys.platform=='win32':whileTrue:# the 16kB chunksize comes from the shutil module# in stdlibchunk=self.read(16*1024)ifnotchunk:breakfobj.write(chunk)else:fobj.write(self.read())self.seek(pos)@staticmethoddeffrom_file(filename):"""read a file and returns its contents in a Binary the reading is performed in a safe way for files stored on Windows SMB shares """binary=Binary()withopen(filename,'rb')asfobj:ifsys.platform=='win32':whileTrue:# the 16kB chunksize comes from the shutil module# in stdlibchunk=fobj.read(16*1024)ifnotchunk:breakbinary.write(chunk)else:binary.write(fobj.read())binary.seek(0)returnbinarydef__eq__(self,other):ifnotisinstance(other,Binary):returnFalsereturnself.getvalue()==other.getvalue()# Binary helpers to store/fetch python objects@classmethoddefzpickle(cls,obj):""" return a Binary containing a gzipped pickle of obj """retval=cls()retval.write(zlib.compress(pickle.dumps(obj,protocol=2)))returnretvaldefunzpickle(self):""" decompress and loads the stream before returning it """returnpickle.loads(zlib.decompress(self.getvalue()))defcheck_password(eschema,value):returnisinstance(value,(bytes,Binary))BASE_CHECKERS['Password']=check_passworddefstr_or_binary(value):ifisinstance(value,Binary):returnvaluereturnbytes(value)BASE_CONVERTERS['Password']=str_or_binary# use this dictionary to rename entity types while keeping bw compatETYPE_NAME_MAP={}# XXX cubic web cube migration map. See if it's worth keeping this mecanism# to help in cube renamingCW_MIGRATION_MAP={}defneg_role(role):ifrole=='subject':return'object'return'subject'defrole(obj):try:returnobj.roleexceptAttributeError:returnneg_role(obj.target)deftarget(obj):try:returnobj.targetexceptAttributeError:returnneg_role(obj.role)classCubicWebEventManager(object):"""simple event / callback manager. Typical usage to register a callback:: >>> from cubicweb import CW_EVENT_MANAGER >>> CW_EVENT_MANAGER.bind('after-registry-reload', mycallback) Typical usage to emit an event:: >>> from cubicweb import CW_EVENT_MANAGER >>> CW_EVENT_MANAGER.emit('after-registry-reload') emit() accepts an additional context parameter that will be passed to the callback if specified (and only in that case) """def__init__(self):self.callbacks={}defbind(self,event,callback,*args,**kwargs):self.callbacks.setdefault(event,[]).append((callback,args,kwargs))defemit(self,event,context=None):forcallback,args,kwargsinself.callbacks.get(event,()):ifcontextisNone:callback(*args,**kwargs)else:callback(context,*args,**kwargs)CW_EVENT_MANAGER=CubicWebEventManager()defonevent(event,*args,**kwargs):"""decorator to ease event / callback binding >>> from cubicweb import onevent >>> @onevent('before-registry-reload') ... def mycallback(): ... print 'hello' ... >>> """def_decorator(func):CW_EVENT_MANAGER.bind(event,func,*args,**kwargs)returnfuncreturn_decoratordefvalidation_error(entity,errors,substitutions=None,i18nvalues=None):"""easy way to retrieve a :class:`cubicweb.ValidationError` for an entity or eid. You may also have 2-tuple as error keys, :func:`yams.role_name` will be called automatically for them. Messages in errors **should not be translated yet**, though marked for internationalization. You may give an additional substition dictionary that will be used for interpolation after the translation. """ifsubstitutionsisNone:# set empty dict else translation won't be done for backward# compatibility reason (see ValidationError.translate method)substitutions={}forkeyinlist(errors):ifisinstance(key,tuple):errors[rname(*key)]=errors.pop(key)returnValidationError(getattr(entity,'eid',entity),errors,substitutions,i18nvalues)# exceptions ##################################################################classProgrammingError(Exception):"""Exception raised for errors that are related to the database's operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, a memory allocation error occurred during processing, etc. """