# -*- coding: utf-8 # Copyright 2007 by Meelis Mets from Globals import InitializeClass from Products.CMFCore.utils import getToolByName from zipfile import ZipFile, BadZipfile, ZIP_DEFLATED from cStringIO import StringIO from AccessControl import ClassSecurityInfo, Unauthorized, getSecurityManager from elementtree.ElementTree import ElementTree class BaseFunctions: def arrayCordinatesAsNr(self, cor, array): """array to nr""" nr = 0 x = len(array[0]) y = len(array) for a in range(0,y,1): for b in range(0,x,1): nr = nr + 1 if a == int(cor[0]) and b == int(cor[1]): return nr return nr def getObjectsArray(self): """return handy arry of objcts""" objects = self.objectValues(['ChoiceObject',]) rows = int(self.getTableHeight()) cols = int(self.getTableWidth()) objectsLen = len(objects) objectsArray = [] counter = 0 for h in range(0,rows): objectsRow = [] for w in range(0,cols): if counter >= objectsLen: objectsRow.append("None") else: objectsRow.append(objects[counter]) counter = counter + 1 objectsArray.append(objectsRow) return objectsArray def createChoiceObjects(self): """script for creating choice objects""" objects = self.objectValues(['ChoiceObject',]) rows = int(self.getTableHeight()) cols = int(self.getTableWidth()) objectsLen = len(objects) counter = 0 for h in range(0,rows): for w in range(0,cols): createObject = False title = self.REQUEST.get('title_'+str(h)+'_'+str(w)) if self.REQUEST.get('pic_'+str(h)+'_'+str(w)): pic = self.REQUEST.get('pic_'+str(h)+'_'+str(w)) else: pic = False usetitle = False if self.REQUEST.get('usetitle_'+str(h)+'_'+str(w)): usetitle = True alreadychecked = False if self.REQUEST.get('alreadychecked_'+str(h)+'_'+str(w)): alreadychecked = True right = False right2 = False if self.REQUEST.get('rightwrong_'+str(h)+'_'+str(w)): rw_choice = self.REQUEST.get('rightwrong_'+str(h)+'_'+str(w)) if rw_choice == 'r1': right = True right2 = True elif rw_choice == 'r2': right = True right2 = False elif rw_choice == 'w1': right = False right2 = False elif rw_choice == 'w2': right = False right2 = True if title: if counter >= objectsLen: self.createChoiceObject(title, pic, usetitle, alreadychecked, right, right2) else: self.modifyChoiceObject(objects[counter].id, title, pic, usetitle, alreadychecked, right, right2) counter = counter + 1 return self.REQUEST.RESPONSE.redirect(self.absolute_url()+'/objects_view') def modifyChoiceObject(self, id, title, pic=False, usetitle=False, alreadychecked=False, right=False, right2=False): """ modifications """ obj = getattr(self, id) if obj.Title() != title: obj.title = title if pic: obj.getField('choiceImage').set(obj, pic) if obj.useTitle != usetitle: obj.useTitle = usetitle if obj.alreadyChecked != alreadychecked: obj.alreadyChecked = alreadychecked if obj.rightChoice != right: obj.rightChoice = right if obj.rightChoice2 != right2: obj.rightChoice2 = right2 obj.reindexObject() def createChoiceObject(self, title, pic=False, usetitle=False, alreadychecked=False, right=False, right2=False): """ creation """ import time newId = 'Choice-'+str(time.time()) id = self.invokeFactory("ChoiceObject", id=newId, title=title) obj = getattr(self,id) obj.useTitle = usetitle obj.alreadyChecked = alreadychecked if pic: obj.getField('choiceImage').set(obj, pic) obj.rightChoice = right obj.rightChoice2 = right2 def getNumbers(self): """return time array""" nrs = [] for nr in range(1, 11, 1): nrs.append(nr) return nrs def getCollectionFolder(self): """return collection list""" if hasattr(self, 'psyhvel'): psyhvel = getattr(self,'psyhvel') if hasattr(psyhvel,'tests'): collection_folder = getattr(psyhvel,'tests') return collection_folder raise "Error: Collection folder not found" def getCollectionList(self): """return collection list""" return self.getCollectionFolder().getFolderContents() def addToCollection(self): """add to collection""" collection_id = self.REQUEST.get('choose_collection') test_objects = self.REQUEST.get('test_objects') if test_objects != None: collection_folder = getattr(self.getCollectionFolder(),collection_id) if hasattr(self, str(test_objects)): self.makeAnswerObject(collection_folder,getattr(self, str(test_objects))) else: for t in test_objects: self.makeAnswerObject(collection_folder,getattr(self, str(t))) return self.REQUEST.RESPONSE.redirect(collection_folder.absolute_url()) def makeAnswerObject(self, where, what): """make object""" test_id = what.id+'db' test_title = what.Title() if not hasattr(where, test_id): from AnswerFolder import AnswerFolder answer = AnswerFolder(test_id) where._setObject(answer.id, answer) ob = getattr(where,answer.id) ob.setTitle(test_title) ob.addRefsToTests(what) if what.meta_type in ['GameFolder']: ob.isGame = True ob.reindexObject() def renderTestTable(self, width=600, owidth=200): """renders html table for dispaly tests""" objects = [] table = [] user = str(self.REQUEST.AUTHENTICATED_USER) member = self.portal_membership.getMemberById(user) trs = getToolByName(self, 'translation_service') counter = 0 testObjects = self.getFolderContents() nrOfObjs = len(testObjects) notActive = False table.append('') isEditor = False security = getSecurityManager() if security.checkPermission('Modify portal content', self): isEditor = True for obj in testObjects: url = str(obj.getObject().absolute_url()) if obj.getObject().isLocked(): if not isEditor: objects.append('') else: objects.append('') elif notActive: if not isEditor: objects.append('') else: objects.append('') else: objects.append('') if obj.getObject().getCurrentPage()==0: notActive = True counter = counter + 1 if isEditor: url = self.portal_url()+'/psyhvel/library?collection='+self.id objects.append('') nrOfObjs = len(objects) rows = int(nrOfObjs*owidth/width)+1 max_objs = int(width/owidth) if nrOfObjs < max_objs: max_objs = nrOfObjs for line in range(0,rows): table.append('') lines = [] spacer = [] for i in range(0,max_objs*2-1): if len(objects) > 0 and i%2 == 0: ob = objects.pop(0) lines.append(ob) if i==max_objs*2-2: spacer.append('') else: spacer.append('') elif len(objects) > 0 and i%2 != 0 and line%2 == 0: lines.append('') spacer.append('') elif len(objects) > 0 and i%2 != 0 and line%2 != 0: lines.append('') spacer.append('') else: lines.append('') spacer.append('') if line%2 != 0: lines.reverse() spacer.reverse() for li in lines: table.append(li) table.append('') # line + 1 sest muidu pani siia asja kylge kui ei oel enam vaja siis viks 2ra if line+1 != rows: table.append('') for sp in spacer: table.append(sp) table.append('') table.append('
'+trs.utranslate('psyhvel', 'Test', self, self)+' '+str(counter+1)+''+trs.utranslate('psyhvel', 'Test', self, self)+' '+str(counter+1)+''+trs.utranslate('psyhvel', 'Test', self, self)+' '+str(counter+1)+''+trs.utranslate('psyhvel', 'Test', self, self)+' '+str(counter+1)+''+trs.utranslate('psyhvel', 'Test', self, self)+' '+str(counter+1)+''+trs.utranslate('psyhvel', 'Add Test', self, self)+'
') return table def getGoodTime(self): """renders good time""" time = 0 if hasattr(self, 'getTime'): time = self.getTime() time = time.replace(",",".") time = int(float(time)*1000) return time def getBaseXML(self): """base xml""" xml = '\n\n' xml += ''+self.portal_type+'\n' xml += '\n' try: xml += '<![CDATA['+self.title.decode('utf_8')+']]>\n' except: xml += '<![CDATA['+self.title+']]>\n' xml += '\n' xml += '\n' xml += '\n' xml += '\n' return xml def getObjectsXML(self, files): """special xml""" xml = self.getBaseXML() xml += '' return [xml, files] def getStructureXML(self): """structure xml""" xmls = [] files = [] sxml = '\n' sxml += '\n\n' oxml = self.getObjectsXML(files) files = oxml[1] xmls.append({'id':self.id, 'xml':oxml[0]}) parent_object = self #print "vanavanem on:" + parent_object.portal_type parent_tail = parent_object.getFolderContents() if len(parent_tail)>0: for child in parent_tail: sxml += '\n' coxml = child.getObject().getObjectsXML(files) files = coxml[1] xmls.append({'id':child.id, 'xml':coxml[0]}) cs = parent_object.getContentStructureXML(child, xmls, files) sxml += '\n'+cs[0] #print "vanem on:" + parent_object.portal_type #sxml += '\n\n' sxml += '\n\n' return [sxml, xmls, files] def getContentStructureXML(parent_object, cnt, xmls, files): """con str""" cxml = '' child_tail = cnt.getObject().getFolderContents() if len(child_tail)>0: for cn in child_tail: parent_object = cn.getObject() cxml += '\n' ccoxml = parent_object.getObjectsXML(files) files = ccoxml[1] xmls.append({'id':cn.id, 'xml':ccoxml[0]}) ccs = parent_object.getContentStructureXML(cn, xmls, files) cxml += '\n'+ccs[0] cxml += '\n' cxml += '\n' else: cxml += '\n' cxml += '\n' parent_object = parent_object.aq_parent() return [cxml, xmls, files] def makeZipExport(self): """zip file""" out = StringIO() zipFile = ZipFile(out, 'w', ZIP_DEFLATED) structureXML = self.getStructureXML() zipFile.writestr('structure.xml', structureXML[0]) for oxml in structureXML[1]: #print oxml['xml'].encode('utf_8') zipFile.writestr(oxml['id']+'.xml', oxml['xml'].encode('utf_8')) for fileo in structureXML[2]: existingnames = zipFile.namelist() #print fileo['filename'] if fileo['filename']: if fileo['filename'] not in existingnames: zipFile.writestr(fileo['filename'], fileo['file']) zipFile.close() out.seek(0) fileOut = out.read() out.close() self.REQUEST.RESPONSE.setHeader("Content-type", "application/octet-stream") self.REQUEST.RESPONSE.setHeader("Content-disposition", "attachment; filename="+self.id+".zip") return fileOut def importZipFile(self): """Zip import""" parent_object = self importedFile = self.REQUEST.get('importZipFile') try: zf=ZipFile(importedFile, 'r') except BadZipfile: return self.REQUEST.RESPONSE.redirect(self.absolute_url()+"/import_form?error=678") #return ('failure','The zip file does not exist or could not be opened.') files = [file.filename for file in zf.filelist] if len(files) < 1: return self.REQUEST.RESPONSE.redirect(self.absolute_url()+"/import_form?error=567") #return ('failure','The zip file was empty') fs = zf.read("structure.xml") f = open('structure.xml', 'w') f.write(fs.replace("\n", "")) f.close() root = ElementTree(file="structure.xml") iter = root.getiterator() for element in iter: if element.tag == "self": if element.keys(): for name, value in element.items(): if name == "id": f_self = zf.read(value+".xml") self_f = open(value+'.xml', 'w') self_f.write(f_self.replace("\n", "")) self_f.close() self_root = ElementTree(file=value + ".xml") new_parent_object = self.makeObjectAsXmlSays(self, self_root, value, zf) if new_parent_object is None: return self.REQUEST.RESPONSE.redirect(self.absolute_url()+"/import_form?error=789") if element.getchildren(): self.checkChildren(element, new_parent_object, zf) return self.REQUEST.RESPONSE.redirect(new_parent_object.absolute_url()) def checkChildren(self, parent_child, parent_object, zf): """checking children""" default_parent_object = parent_object for older_child in parent_child: if older_child.tag == "children": if older_child.getchildren(): for child in older_child: if child.tag == "child": if child.keys(): for name, value in child.items(): if name == "id": f_child = zf.read(value+".xml") child_f = open(value+'.xml', 'w') child_f.write(f_child) child_f.close() child_root = ElementTree(file=value + ".xml") new_parent_object = parent_object.makeObjectAsXmlSays(parent_object, child_root, value, zf) if child.getchildren(): self.checkChildren(child, new_parent_object, zf) else: parent_object = default_parent_object def makeObjectAsXmlSays(self, parent_object, o_root, oid, zf): """make object""" o_iter = o_root.getiterator() oobj = False for element in o_iter: if element.text: text = element.text if element.tag == "type": import time oid = text.lower()+'-'+str(time.time()) print "making object:" +text+ " with id:" + oid + "on parent object: " + str(parent_object) try: ooid = parent_object.invokeFactory(text, id=oid, title="Imported "+text) except ValueError: return None oobj = getattr(parent_object, ooid) elif oobj: if oobj.getField(element.tag): oobj.getField(element.tag).set(oobj, text) else: if element.tag in ["imageFile", "file"]: if element.keys(): for name, value in element.items(): if name == "field": file = zf.read(text) if oobj.getField(value): if file: oobj.getField(value).set(oobj, file) else: oobj.objectSpecData(element.tag, text) if oobj: oobj.reindexObject() return oobj return False def objectSpecData(self, key, val): """objects spec data""" pass def isExportable(self): """is exportable""" return False; def isImportable(self): """is exportable""" return False;