def updateChanges(self, ids, override=False): standard.writeLog(self, "[updateChanges]: ids=%s" % str(ids)) standard.triggerEvent(self, 'beforeUpdateRepositoryEvt') success = [] failure = [] repositories = {} for i in ids: # Initialize. provider_id = i[:i.find(':')] id = i[i.find(':') + 1:] provider = getattr(self, provider_id) # Read repositories for provider. if provider_id not in repositories: repositories[provider_id] = self.readRepository(provider) repository = repositories[provider_id] # Update. try: r = repository[id] provider.updateRepository(r) success.append(id) except: standard.writeError(self, "[updateChanges]: can't %s" % id) failure.append(id) standard.triggerEvent(self, 'afterUpdateRepositoryEvt') return success, failure
def moveObjsToTrashcan(self, ids, REQUEST): if self.meta_id == 'ZMSTrashcan': return trashcan = self.getTrashcan() # Set deletion-date. ids_copy = [] for id in ids: try: context = getattr(self, id) context.del_uid = str(REQUEST.get('AUTHENTICATED_USER', None)) context.del_dt = standard.getDateTime(time.time()) ids_copy.append(id) except: standard.writeBlock( self, "[moveObjsToTrashcan]: Attribute Error %s" % (id)) # Use only successfully tried ids ids = ids_copy # Move (Cut & Paste). children = [getattr(self, x) for x in ids] [ standard.triggerEvent(child, 'beforeDeleteObjsEvt') for child in children ] cb_copy_data = _cb_decode(self.manage_cutObjects(ids)) trashcan.manage_pasteObjects(cb_copy_data=_cb_encode(cb_copy_data)) trashcan.normalizeSortIds() trashcan.run_garbage_collection(forced=1) # Sort-IDs. self.normalizeSortIds() [ standard.triggerEvent(child, 'afterDeleteObjsEvt') for child in children ]
def importFile(self, file, REQUEST, handler): # Get filename. if isinstance(file, ZPublisher.HTTPRequest.FileUpload): filename = file.filename else: filename = file.name standard.writeBlock(self, '[importFile]: filename=' + filename) # Create temporary folder. folder = tempfile.mktemp() os.mkdir(folder) # Save to temporary file. filename = _fileutil.getOSPath( '%s/%s' % (folder, _fileutil.extractFilename(filename))) _fileutil.exportObj(file, filename) # Import ZEXP-file. if _fileutil.extractFileExt(filename) == 'zexp': ob = self._importObjectFromFile(filename, verify=0) # Remove temporary files. _fileutil.remove(folder, deep=1) # Refresh zcatalog_index standard.triggerEvent(self, '*.onImportObjEvt') return ob # Find XML-file. if _fileutil.extractFileExt(filename) == 'zip': _fileutil.extractZipArchive(filename) filename = None for deep in [0, 1]: for ext in ['xml', 'htm', 'html']: if filename is None: filename = _fileutil.findExtension(ext, folder, deep) break if filename is None: raise zExceptions.InternalError('XML-File not found!') # Import Filter. if REQUEST.get('filter', '') in self.getFilterManager().getFilterIds(): filename = _filtermanager.importFilter(self, filename, REQUEST.get('filter', ''), REQUEST) # Import XML-file. standard.writeBlock(self, '[importFile]: filename=' + filename) f = standard.pyopen(filename, 'r', encoding='utf-8') ob = handler(self, f) f.close() # Remove temporary files. _fileutil.remove(folder, deep=1) # Return imported object. return ob
def parse(self, input, root=None, bInRootTag=0): """ Builder.parse """ # prepare builder self.oRootTag = None self.oCurrNode = None self.bInCData = False if bInRootTag: self.oCurrNode = root # create parser object p = pyexpat.ParserCreate() # connect parser object with handler methods p.StartElementHandler = self.OnStartElement p.EndElementHandler = self.OnEndElement p.CharacterDataHandler = self.OnCharacterData p.StartCdataSectionHandler = self.OnStartCData p.EndCdataSectionHandler = self.OnEndCData p.ProcessingInstructionHandler = self.OnProcessingInstruction p.CommentHandler = self.OnComment p.StartNamespaceDeclHandler = self.OnStartNamespaceDecl p.EndNamespaceDeclHandler = self.OnEndNamespaceDecl #### parsing #### if isinstance(input,bytes): # input is a string! rv = p.Parse(input, 1) else: # input is a file object! while True: v=input.read(self.iBufferSize) if v=="": rv = 1 break rv = p.Parse(v, 0) if not rv: break # raise parser exception if not rv: raise ParseError('%s at line %s' % (pyexpat.ErrorString(p.ErrorCode), p.ErrorLineNumber)) #### # reindex standard.triggerEvent( self, '*.ObjectImported') #### return root
def manage_pasteObjs(self, REQUEST, RESPONSE=None): """ CopySupport.manage_pasteObjs """ id_prefix = REQUEST.get('id_prefix', 'e') standard.writeBlock(self, "[CopySupport.manage_pasteObjs]") t0 = time.time() # Analyze request cb_copy_data = self._get_cb_copy_data(cb_copy_data=None, REQUEST=REQUEST) op = cb_copy_data[0] cp = (op, cb_copy_data[1]) cp = _cb_encode(cp) ids = [self._get_id(x.getId()) for x in self._get_obs(cp)] oblist = self._get_obs(cp) # Paste objects. action = ['Copy', 'Move'][op == OP_MOVE] standard.triggerEvent(self, 'before%sObjsEvt' % action) self.manage_pasteObjects(cb_copy_data=None, REQUEST=REQUEST) standard.triggerEvent(self, 'after%sObjsEvt' % action) # Sort order (I). self._set_sort_ids(ids=ids, op=op, REQUEST=REQUEST) # Move objects. if op == OP_MOVE: normalize_ids_after_move(self, id_prefix=id_prefix, ids=ids) # Copy objects. else: normalize_ids_after_copy(self, id_prefix=id_prefix, ids=ids) # Sort order (II). self.normalizeSortIds() # Return with message. if RESPONSE is not None: message = standard.pybytes(self.getZMILangStr('MSG_PASTED')) message += ' (in ' + str(int( (time.time() - t0) * 100.0) / 100.0) + ' secs.)' RESPONSE.redirect('manage_main?lang=%s&manage_tabs_message=%s' % (REQUEST['lang'], standard.url_quote(message)))
def importContent(self, file): # Setup. catalog_awareness = self.getConfProperty('ZMS.CatalogAwareness.active', 1) self.setConfProperty('ZMS.CatalogAwareness.active', 0) self.dTagStack = collections.deque() self.dValueStack = collections.deque() self.oParent = self.getParentNode() # Parse XML-file. ob = self.parse(file, self, 1) # Process objects after import recurse_importContent(ob, _fileutil.getFilePath(file.name)) # Cleanup. self.setConfProperty('ZMS.CatalogAwareness.active', catalog_awareness) standard.triggerEvent( self, '*.onImportObjEvt') # Return imported object. return ob
def subscriber(event): if isinstance(event, ObjectAddedEvent): if isinstance(event.object, ZMSObject): if isinstance(event.newParent, ZMSObject): # trigger object-added event standard.triggerEvent(event.object, "*.ObjectAdded") elif isinstance(event, ObjectMovedEvent): if isinstance(event.object, ZMSObject): if isinstance(event.newParent, ZMSObject): # trigger object-moved event standard.triggerEvent(event.object, "*.ObjectMoved") elif event.newParent is None: standard.triggerEvent(event.object, "*.ObjectRemoved") elif isinstance(event, ObjectRemovedEvent): if isinstance(event.object, ZMSObject): # trigger object-removed event standard.triggerEvent(event.object, "*.ObjectRemoved")
def commitChanges(self, ids): standard.writeLog(self, "[commitChanges]: ids=%s" % str(ids)) standard.triggerEvent(self, 'beforeCommitRepositoryEvt') success = [] failure = [] for provider_id in list(set([x.split(':')[0] for x in ids])): provider = getattr(self, provider_id) basepath = self.get_conf_basepath(provider.id) for id in list( set([ x.split(':')[1] for x in ids if x.split(':')[0] == provider_id ])): try: # Read local-files from provider. files = self.localFiles(provider, [id]) # Recreate folder. if os.path.exists(basepath): for name in os.listdir(basepath): filepath = os.path.join(basepath, name) if os.path.isdir(filepath) and name == id: standard.writeLog( self, "[commitChanges]: clear dir %s" % filepath) dir = [ os.path.join(filepath, x) for x in os.listdir(filepath) ] [ _fileutil.remove(x) for x in dir if os.path.isfile(x) ] elif os.path.isfile( filepath) and name == '%s.py' % id: standard.writeLog( self, "[commitChanges]: remove file %s" % filepath) _fileutil.remove(filepath) # Clear folders. dir = list( set([ os.path.join(basepath, x[:x.rfind(os.path.sep)]) for x in files if x.endswith('__init__.py') ])) dir = [ x for x in dir if x.split(os.path.sep)[-1] in [y.split(':')[-1] for y in ids] ] [[ os.remove(z) for z in [os.path.join(x, y) for y in os.listdir(x)] if os.path.isfile(z) ] for x in dir if os.path.isdir(x)] # Write files. for file in files: filepath = os.path.join(basepath, file) folder = filepath[:filepath.rfind(os.path.sep)] standard.writeLog( self, "[commitChanges]: exists folder %s %s" % (folder, str(os.path.exists(folder)))) if not os.path.exists(folder): standard.writeLog( self, "[commitChanges]: create folder %s" % folder) _fileutil.mkDir(folder) standard.writeLog( self, "[commitChanges]: write %s" % filepath) data = files[file]['data'] if data is not None: f = open(filepath, "wb") try: f.write(data.encode('utf-8')) except: f.write(data) f.close() else: failure.append('%s is None' % file) success.append(id) except: standard.writeError(self, "[commitChanges]: can't %s" % id) failure.append(id) standard.triggerEvent(self, 'afterCommitRepositoryEvt') return success, failure