# -*- coding: utf-8 # -*- Mode: Python; py-indent-offset: 4 -*- # $Id$ # # Copyright (c) 2006, Vahur Rebas, HTK, TLU # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Question and Test online authoring tool """ __version__ = "$Revision:33$"[11:-2] import re import Globals from Globals import Acquisition, Persistent from Acquisition import aq_base, aq_inner, aq_parent, Explicit from AccessControl import ClassSecurityInfo, getSecurityManager from OFS.Folder import Folder from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.GlobalTranslationService import getGlobalTranslationService from Products.QTAuthor.utils import send_mail from SOAPpy import SOAPProxy from SOAPpy import Types from zope.interface import implements from config import LICENCES, VERSION, CONF, LRE_KEYWORDS from interfaces import IQTAuthor class QTAuthor(Folder, Persistent, Explicit): """ QTAuthor - Question and Test online authoring tool """ meta_type = 'QTAuthor' security = ClassSecurityInfo() security.declareObjectPublic() implements(IQTAuthor) manage_options = Folder.manage_options def manage_afterAdd(self, item, container): self._setupPAS() self._setupZCatalogs() self._setupFolders() self._setupCacheObject() self._setupAnswersFolder() self._setupGroupsFolder() self._setupConfiguration() self._setupUsersFolder() self._setupKupuTool() from Permissions import perm_view_question, perm_edit_question, perm_view_test from Permissions import perm_edit_test, perm_create_question, perm_create_test self.manage_permission(perm_view_question, ('Manager', 'Owner', 'Authenticated'), 0) self.manage_permission(perm_edit_question, ('Manager', 'Owner',), 0) self.manage_permission(perm_view_test, ('Manager', 'Owner', 'Authenticated'), 0) self.manage_permission(perm_edit_test, ('Manager', 'Owner',), 0) self.manage_permission(perm_create_question, ('Manager', 'Owner', 'Authenticated',)) self.manage_permission(perm_create_test, ('Manager', 'Owner', 'Authenticated',), 0) def _setupKupuTool(self): """ setup kupu tool """ from kuputool import TatsKupuLibraryTool k = TatsKupuLibraryTool() self._setObject(k.id, k) def _setupPAS(self): """ Setup Pluggable Auth Service """ from zExceptions import BadRequest from Products.PluggableAuthService.PluggableAuthService import addPluggableAuthService # PAS try: addPluggableAuthService(self) except BadRequest: pass #cookie auth from Products.PluggableAuthService.plugins.CookieAuthHelper import addCookieAuthHelper try: addCookieAuthHelper(self.acl_users, 'cookie', '', '__ac') except BadRequest: pass self.acl_users.cookie.manage_activateInterfaces(['IExtractionPlugin', 'IChallengePlugin', 'ICredentialsUpdatePlugin', 'ICredentialsResetPlugin']) # acl_users/ZODBUser source from Products.PluggableAuthService.plugins.ZODBUserManager import addZODBUserManager try: addZODBUserManager(self.acl_users, 'users', '') except BadRequest: pass self.acl_users.users.manage_activateInterfaces(['IAuthenticationPlugin', 'IUserEnumerationPlugin', 'IUserAdderPlugin']) # roles from Products.PluggableAuthService.plugins.ZODBRoleManager import addZODBRoleManager try: addZODBRoleManager(self.acl_users, 'roles', '') except BadRequest: pass self.acl_users.roles.manage_activateInterfaces(['IRolesPlugin', 'IRoleEnumerationPlugin', 'IRoleAssignerPlugin']) def _setupZCatalogs(self): """ setup ZCatalogs """ # setup catalog for questions from Products.ZCatalog.ZCatalog import ZCatalog catalog = ZCatalog('zcatalog', 'ZCatalog for questions') class largs: def __init__(self, **kw): self.__dict__.update(kw) from Products.ZCTextIndex.ZCTextIndex import manage_addLexicon manage_addLexicon(catalog, 'lexicon', elements=[ largs(group= 'Stop Words', name= " Don't remove stop words" ), largs(group= 'Word Splitter' , name= "QTAuthor Unicode Whitespace splitter" ), ] ) class attrs: doc_attr = 'getId, getTitle, getQuestion, getKeywordsTuple, getAuthor' lexicon_id = 'lexicon' index_type = 'Cosine Measure' catalog.addIndex('fulltext', 'ZCTextIndex', attrs()) catalog.addIndex('getUser', 'FieldIndex') catalog.addIndex('getTitle', 'FieldIndex') catalog.addIndex('getLastChange', 'DateIndex') catalog.addIndex('getKeywordsTuple', 'KeywordIndex') catalog.addIndex('getDifficulty', 'FieldIndex') catalog.addIndex('getLicence', 'FieldIndex') catalog.addIndex('getLanguage', 'FieldIndex') catalog.addIndex('getKeywords', 'FieldIndex') catalog.addIndex('getErased', 'FieldIndex') catalog.addIndex('getAuthor', 'FieldIndex') catalog.addIndex('getType', 'FieldIndex') catalog.addIndex('getStatus', 'FieldIndex') catalog.addColumn('getId') catalog.addColumn('getTitle') catalog.addColumn('getQuestion') catalog.addColumn('getKeywordsTuple') catalog.addColumn('getUser') catalog.addColumn('getLastChange') catalog.addColumn('getDifficulty') catalog.addColumn('getLicence') catalog.addColumn('getLanguage') catalog.addColumn('getKeywords') catalog.addColumn('getErased') catalog.addColumn('getAuthor') catalog.addColumn('getType') catalog.addColumn('getStatus') self._setObject('cat_ques', catalog) # setup catalog for tests catalog_tests = ZCatalog('zcatalog', 'ZCatalog for tests') manage_addLexicon(catalog_tests, 'lexicon', elements=[ largs(group= 'Stop Words', name= " Don't remove stop words" ), largs(group= 'Word Splitter' , name= "QTAuthor Unicode Whitespace splitter" ), ] ) class attrs: doc_attr = 'getId, getTitle, getDescription, getKeywordsTuple, getUser, getAuthor' lexicon_id = 'lexicon' index_type = 'Cosine Measure' catalog_tests.addIndex('fulltext', 'ZCTextIndex', attrs()) catalog_tests.addIndex('getTitle', 'FieldIndex') catalog_tests.addIndex('getDescription', 'FieldIndex') catalog_tests.addIndex('getKeywords', 'KeywordIndex') catalog_tests.addIndex('getLanguage', 'FieldIndex') catalog_tests.addIndex('getDifficulty', 'FieldIndex') catalog_tests.addIndex('getLicence', 'FieldIndex') catalog_tests.addIndex('getUser', 'FieldIndex') catalog_tests.addIndex('getAuthor', 'FieldIndex') catalog_tests.addIndex('getStatus', 'FieldIndex') catalog_tests.addIndex('getLastChange', 'FieldIndex') catalog_tests.addIndex('getQuestions', 'KeywordIndex') catalog_tests.addIndex('getErased', 'FieldIndex') catalog_tests.addColumn('getId') catalog_tests.addColumn('getTitle') catalog_tests.addColumn('getKeywords') catalog_tests.addColumn('getLanguage') catalog_tests.addColumn('getDifficulty') catalog_tests.addColumn('getLicence') catalog_tests.addColumn('getUser') catalog_tests.addColumn('getAuthor') catalog_tests.addColumn('getStatus') catalog_tests.addColumn('getNumQuestions') catalog_tests.addColumn('getLastChange') catalog_tests.addColumn('getQuestions') catalog_tests.addColumn('getErased') self._setObject('cat_tests', catalog_tests) # setup catalog for groups catalog_groups = ZCatalog('zcatalog', 'ZCatalog for groups') manage_addLexicon(catalog_groups, 'lexicon', elements=[ largs(group= 'Stop Words', name= " Don't remove stop words" ), largs(group= 'Word Splitter' , name= "QTAuthor Unicode Whitespace splitter" ), ] ) class attrs: doc_attr = 'getId, getTitle, getDescription, getUser' lexicon_id = 'lexicon' index_type = 'Cosine Measure' catalog_groups.addIndex('fulltext', 'ZCTextIndex', attrs()) catalog_groups.addIndex('getTitle', 'FieldIndex') catalog_groups.addIndex('getUser', 'FieldIndex') catalog_groups.addIndex('getMembers', 'KeywordIndex') catalog_groups.addIndex('getTests', 'KeywordIndex') catalog_groups.addColumn('getId') catalog_groups.addColumn('getTitle') catalog_groups.addColumn('getDescription') catalog_groups.addColumn('getUser') catalog_groups.addColumn('getMembers') catalog_groups.addColumn('getTests') self._setObject('cat_groups', catalog_groups) #setup catalog for answersobjects catalog_answers = ZCatalog('zcatalog', 'ZCatalog for answers') manage_addLexicon(catalog_answers, 'lexicon', elements=[ largs(group= 'Stop Words', name= " Don't remove stop words" ), largs(group= 'Word Splitter' , name= "QTAuthor Unicode Whitespace splitter" ), ] ) catalog_answers.addIndex('getQuesId', 'FieldIndex') catalog_answers.addIndex('isCorrect', 'FieldIndex') catalog_answers.addColumn('getId') catalog_answers.addColumn('getQuesId') catalog_answers.addColumn('isCorrect') self._setObject('cat_answers', catalog_answers) #setup catalog for images catalog_images = ZCatalog('zcatalog', 'ZCatalog for images') manage_addLexicon(catalog_images, 'lexicon', elements=[ largs(group= 'Stop Words', name= " Don't remove stop words" ), largs(group= 'Word Splitter' , name= "QTAuthor Unicode Whitespace splitter" ), ] ) catalog_images.addIndex('getId', 'FieldIndex') catalog_images.addIndex('getErased', 'FieldIndex') catalog_images.addIndex('getUser', 'FieldIndex') catalog_images.addColumn('getId') catalog_images.addColumn('getErased') catalog_images.addColumn('getFilename') catalog_images.addColumn('getUser') self._setObject('cat_images', catalog_images) def _setupFolders(self): """ setup Folders: questions, tests, images, videos """ from Questions import Questions q = Questions() self._setObject(q.id, q) from Tests import Tests t = Tests() self._setObject(t.id, t) from Images import Images i = Images() self._setObject(i.id, i) from Videos import Videos v = Videos() self._setObject(v.id, v) def _setupAnswersFolder(self): """ setup Folder: answers """ from Answers import Answers a = Answers() self._setObject(a.id, a) def _setupCacheObject(self): """ """ from Cache import Cache c = Cache('cache') self._setObject(c.id, c) def _setupGroupsFolder(self): """ setup Folders: groups, students """ from Groups import Groups g = Groups() self._setObject(g.id, g) from Students import Students s = Students() self._setObject(s.id, s) def _setupConfiguration(self): """ setup configuration object """ if not hasattr(self, 'configuration'): from Configuration import Configuration c = Configuration() self._setObject(c.id, c) def _setupUsersFolder(self): """ setup Folder: users""" if not hasattr(self, 'users'): from Users import Users u = Users() self._setObject(u.id, u) def getSkinsFolderName(self): return "portal_skins" def checkRoles(self, context, user, role='Authenticated'): """ check user's roles in context """ if role in user.getRolesInContext(context): return 1 return 0 def get_root(self): return self def logged_in(self, REQUEST): """ user just logged in """ url = REQUEST.get('came_from', self.absolute_url()) from User import User name = str(REQUEST.get('AUTHENTICATED_USER')) try: self.users._getOb(name) except KeyError: u = User(name) self.users._setObject(name, u) return REQUEST.RESPONSE.redirect(url) def register_action(self, REQUEST, username='', email=''): """ create a new user account """ msg = '' if not username: msg += self.utranslate('uname_field_empty', 'Username field is empty.') + '
' else: if self._check_user_existence(username): msg += self.utranslate('uname_taken', 'Username is already taken.') + '
' elif not re.match('[a-zA-Z0-9]+$', username): msg += self.utranslate('uname_can_only_contain', 'Username can only contain letters and numbers.') + '
' if not email: msg += self.utranslate('email_field_empty', 'Email address field is empty.') + '
' else: if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email): msg += self.utranslate('email_not_valid', 'Email address is not valid.') + '
' elif self._check_user_email(email): msg += self.utranslate('email_exists', 'User with that email address is already registered.') + '
' #if not password1: # msg += self.utranslate('password_field_empty', 'Password field is empty.') + '
' #elif (password1 != password2): # msg += self.utranslate('passwords_dont_match', 'Passwords do not match.') + '
' if msg: return self.restrictedTraverse('register.html')(messages=msg) else: create_res = 1 passwd = '' import random, string chars = string.ascii_lowercase for x in range(3): nr = 95 while chr(nr) not in chars: nr = random.randint(65,122) passwd += chr(nr) new_pass = passwd + str(int(random.random()*10))+str(int(random.random()*10))+str(int(random.random()*10)) ac = self.acl_users ac._doAddUser(username, new_pass, [], ()) from User import User u = User(username) u.setEmail(email) self.users._setObject(username, u) mail_subject = self.utranslate('registration_mail_subject', 'TATS: Registration') mail_content = self.utranslate('registration_mail_content', 'Hello!\n\nYou have been registered as a TATS member.\n\nHere are the details you will need to sign in:\n\nusername: %(username)s \npassword: %(password)s \n\n\nBest regards,\n\nTATS') %{'username':username, 'password':new_pass} send_mail(email, mail_subject, mail_content) return REQUEST.RESPONSE.redirect('register_done.html') def _check_user_existence(self, uname): """ check if uname already exists in some acl_users folder """ ext = self.acl_users.getUserById(uname) return ext is not None def _check_user_email(self, email): """ check if user with that email already exists """ users = self.users.objectValues('User') for user in users: if user.getEmail() == email: return 1 return 0 def send_password_remainder(self, REQUEST, uname=''): """ """ msg = '' try: user = self.users._getOb(name) except KeyError: msg += "Could not find user with that username." if user: if (user.getEmail()): # send password to user email address password = user.getPassword() email = user.getEmail() mh = self.MailHost mail_subject = self.utranslate('password_remainder_mail_subject', 'TATS: Password reminder') mail_content = self.utranslate('password_remainder_mail_content', '\nHere are the details you will need to sign in:\n\nusername: %(username)s \npassword: %(password)s \n\n\nBest regards,\n\nTATS') %{'username':username, 'password':password} mh.secureSend(mail_content, email, 'TATS ', mail_subject, charset='utf-8') else: msg += "That user does not have an email address." def getRendererServiceURL(self): return getattr(self, 'renderer_url', '') def isWaramuEnabled(self): return getattr(self, 'waramu_enabled', 0) def getWaramuURL(self): return getattr(self, 'waramu_url', '') def getWaramuUsername(self): return getattr(self, 'waramu_username', '') def getWaramuPassword(self): return getattr(self, 'waramu_password', '') def getWaramu(self): if not self.isWaramuEnabled(): return None from waramulib.interfaces import IWaramuClient from zope.component import getUtility wu = getUtility(IWaramuClient, name="waramuconnection") if wu.isConnected(): return wu wu._init(self.getWaramuURL()) wu.newSession(self.getWaramuUsername(), self.getWaramuPassword()) wu.Identify() return wu def getFeedbackEmail(self): return getattr(self, 'feedback_email', '') security.declareProtected('Manage', 'changeOptions') def changeOptions(self, renderer_url='', is_waramu=0, waramu_url='', waramu_username='', waramu_pass=''): """ change options """ self.renderer_url = renderer_url self.waramu_enabled = is_waramu self.waramu_url = waramu_url self.waramu_username = waramu_username self.waramu_password = waramu_pass security.declareProtected('Manage', 'changeSettings') def changeSettings(self, feedback_email=''): """ change portal settings """ self.feedback_email = feedback_email def getImageById(self, id): """ """ return self.images._getOb(id) def getTestById(self, id): """ """ return self.tests._getOb(id) def getQuestionById(self, id): """ get question by id """ return self.questions._getOb(id) def getAnswerContainerById(self, id): return self.answers._getOb(id) def getTokenTestId(self, token): """ """ tests = self.tests.objectValues() for t in tests: t_tokens = t.getTokens() if token in t_tokens: return t.getId() return False def getGroups(self, user): objs = self.groups._getAllGroups() all = [] for x in objs: if x.getOwnerTuple()[1] == str(user): all.append(x) return all def getGroupById(self, id): """ get group by id """ return self.groups._getOb(id) def getContainerById(self, id): """ get answercontainer by id """ return self.answers._getOb(id) def getUserFolderById(self, id): """ get user folder by id """ o = None try: o = self.users._getOb(id) except KeyError: from User import User name = str(self.REQUEST.get('AUTHENTICATED_USER')) u = User(name) self.users._setObject(name, u) o = self.users.get(name) return o def getAllMembers(self): #et kuvada välja kõik inimesed kes on gruppides """ """ allmembers = [] alluids = [] groups = self.groups._getAllGroups() for group in groups: gmembers = group.getMembers() for member in gmembers: if member['uid'] not in alluids: alluids.append(member['uid']) allmembers.append(member) return allmembers def getStudentById(self, studentid): """ """ if studentid == '': return '' allstudents = self.students.getAllStudents() for s in allstudents: if s.get('uid') == studentid: return s def getMemberTests(self, memberid): """ """ testIds = [] member = self.getMemberById(memberid) ansfolders = member['ans_containers'] for f in ansfolders: folder = self.getContainerById(f) f_testid = folder.getTestId() testIds.append(f_testid) #f_sessions = folder.getSessions() return testIds def getMemberAnswers(self, folderid): """ """ container = self.getContainerById(folderid) sessions = container.getSessions() for s in sessions: answers = s.getAllAnswers() return answers def getContainerByTestId(self, containers, test_id, group_id): """ """ for c in containers: container = self.getContainerById(c) c_test_id = container.getTestId() c_group_id = container.getGroupId() if c_test_id == test_id and (c_group_id == '' or (c_group_id != '' and c_group_id == group_id)): return container def setTokenFolders(self, tokens, test_id): test = self.getTestById(test_id) from random import choice import string chars = string.letters + string.digits fnames = test.getTokenFolderNames() for token in tokens: if fnames.has_key(token) == False: folderid = '' for i in range(20): folderid += choice(chars) self.answers.setupTokenFolder(folderid, token) fnames[token] = folderid test.setTokenFolderNames(fnames) def test(self, token, REQUEST): """ start testing """ test_id = self.getTokenTestId(token) if test_id == False: return "You can't do this test." test = self.getTestById(test_id) haventDone = test.haventDone(token) if haventDone == False: return "You have already done it!" fnames = test.getTokenFolderNames() tfoldername = fnames.get(token) tfolder = getattr(self.answers, tfoldername) sessFolder = tfolder.setupSessionFolder(test_id) sess_id = sessFolder.getId() # cookie import time day = int(time.strftime("%d", time.localtime())) + 1 weekday = time.strftime("%a, ", time.localtime()) all = time.strftime(" %b %Y %H:%M:%S", time.localtime()) expiredate = weekday + str(day) + all +' GMT' REQUEST.RESPONSE.setCookie('token', token, expires=expiredate) if sessFolder.isCompleted(): return REQUEST.RESPONSE.redirect('answers/'+tfoldername+'/'+sess_id+'/finish_test') return REQUEST.RESPONSE.redirect('answers/'+tfoldername+'/'+sess_id+'/index_html') security.declareProtected('Manage', 'catalogObjects') def catalogObjects(self): #et küsimused ja testid uuesti katalogiseerida """ """ objs = self.questions.objectValues() for q in objs: q.index_object() testobjs = self.tests.objectValues() for t in testobjs: t.index_object() answers = self.answers.objectValues() for ans in answers: sessions = ans.getSessions() for sess in sessions: ansobjs = sess.getAllAnswers() for a in ansobjs: a.index_object() security.declareProtected('Manage', 'upgrade') def upgrade(self): """ upgrade """ from migration import upgrade return upgrade(self, VERSION) def portal_url(self): return self.absolute_url() def getStates(self): """ """ return ['draft', 'public', 'private'] def getLicenceTypes(self): return LICENCES def getLREKeywordsMapping(self): return LRE_KEYWORDS def getSortedLREKeywords(self): """ returns sorted array of (key, value) pairs [('91', 'art'), .. ] """ return sorted(LRE_KEYWORDS.iteritems(), key=lambda (k,v): (self.utranslate(v, v).lower(),k)) def utranslate(self, msgid='', default=''): """ """ if msgid == '': msgid=default # get the global translation service service = getGlobalTranslationService() text = service.translate(domain='qtauthor', msgid=msgid, default=default, context=self) if isinstance(text, str): text = text.decode('utf-8') #if not isinstance(text, str): # try: # text = text.decode('utf-8') # except UnicodeEncodeError: # pass return text def roundNumber(self, nr): """ """ rounded = "%.0f" %nr return rounded def getAllLanguages(self): languages = { 'et':{'short_name':'et', 'name':'eesti'}, 'en':{'short_name':'en', 'name':'english'}, 'ru':{'short_name':'ru', 'name':'pусский'}, 'fi':{'short_name':'fi', 'name':'suomi'} } return languages def formatDate(self, date): """" """ import time date = str(date).split(' ')[0] try: date = time.strptime(date, "%Y-%m-%d") date = time.strftime("%d-%m-%Y", date) except ValueError: pass return date def save_user_profile(self, REQUEST, save_button=''): """ """ if save_button: email = REQUEST.get('email') if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email): msg = self.utranslate('email_not_valid', 'Email address is not valid.') return self.restrictedTraverse('profile_edit.html')(message=msg) user = str(REQUEST.get('AUTHENTICATED_USER')) userfolder = self.getUserFolderById(user) userfolder.setFirstName(REQUEST.get('fname')) userfolder.setLastName(REQUEST.get('lname')) userfolder.setEmail(email) return REQUEST.RESPONSE.redirect('profile.html') def change_user_password(self, REQUEST, save_button=''): """ """ if save_button: msg = '' u = getSecurityManager().getUser() user = str(u) old_password = REQUEST.get('current_password') if not old_password: msg = self.utranslate("current_password_field_empty", "You didn't enter your current password.") uuser = self.acl_users.searchUsers(id=str(u)) if len(uuser) != 1: msg = self.utranslate("system_error", "... system error") return self.restrictedTraverse('profile.html')(message=msg) uuser = uuser[0] um = getattr(self.acl_users, uuser.get('pluginid')) if um.authenticateCredentials({'login': user, 'password': old_password}) is None: print "no match..." msg = self.utranslate("wrong_current_password", "Your current password don't match.") if msg: return self.restrictedTraverse('password_change.html')(message=msg) password1 = REQUEST.get('new_password1') password2 = REQUEST.get('new_password2') if not password1: msg = self.utranslate("new_password_field_empty", "You didn't enter a new password.") elif (password1 != password2): msg = self.utranslate('passwords_dont_match', 'Passwords do not match.') if msg: return self.restrictedTraverse('password_change.html')(message=msg) um.updateUserPassword(user, password1) # keep user logged in after password change um.updateCredentials(REQUEST, REQUEST.RESPONSE, user, password1) return self.restrictedTraverse('profile.html')(infomessage='Password changed.') return REQUEST.RESPONSE.redirect('profile.html') #def nullWaramuUIDS(self): # """ nukll all """ # qs = self.questions.objectValues() # for q in qs: # if q.getErased(): # continue # q._setWaramuUid("") security.declareProtected('Manage', 'massToWaramu') def massToWaramu(self): """ mass send to waramu """ from waramulib import Errors as wErrors qs = self.questions.objectValues() d = 0 nd = 0 ext = 0 for q in qs: if q.getErased(): #print "deleted question:", q.getTitles() #q.unindex_object() self.questions._delObject(q.getId()) d += 1 continue #q.setStatus('public') if q.getWaramuUid() == "": try: q._exportToWaramu() ext += 1 except AttributeError: print "xml error 1:", q, q.getId() except TypeError: print "xml error 2:", q, q.getId() else: try: q._updateToWaramu() ext += 1 except wErrors.InternalServerError: q._exportToWaramu() except wErrors.AccessDenied: print q.getWaramuUid() nd += 1 print "deleted:", d print "nondelt:", nd print "success on waramu:", ext return "ok" security.declareProtected('Manage', 'sendQuestionsToWaramu') def sendQuestionsToWaramu(self): """ temporary method for sending all public questions to waramu """ from waramulib import Errors as wErrors qs = self.questions.objectValues() public = 0 exported = 0 for q in qs: if not q.getErased(): if q.getStatus() == "public": try: q._exportToWaramu() exported += 1 except AttributeError: print "xml error 1:", q, q.getId() except TypeError: print "xml error 2:", q, q.getId() public += 1 print "public questions:", public print "exported to waramu: ", exported return "ok" security.declareProtected('Manage', 'sendTestsToWaramu') def sendTestsToWaramu(self): """ temporary method for sending all public tests to waramu """ from waramulib import Errors as wErrors qs = self.tests.objectValues() public = 0 exported = 0 for q in qs: if not q.getErased(): if q.getStatus() == "public": print "test id: ", q.getId() try: q._exportToWaramu() exported += 1 except AttributeError: print "xml error 1:", q, q.getId() except TypeError: print "xml error 2:", q, q.getId() public += 1 print "public tests:", public print "exported to waramu: ", exported return "ok" Globals.InitializeClass(QTAuthor) def manage_addQTAuthor(self, REQUEST, id): """ instantiate QTAutor """ qta = QTAuthor(id) self._setObject(id, qta) if REQUEST: return self.manage_main(self, REQUEST) manage_addQTAuthorForm = PageTemplateFile('addQTAuthorForm.pt', globals())