PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/models/db.py

https://code.google.com/p/web2conf/
Python | 259 lines | 211 code | 31 blank | 17 comment | 27 complexity | 1e56bd79b76ee5ad3efbaba7c21039db MD5 | raw file
  1. from gluon.tools import *
  2. import uuid, datetime, re, os, time, stat
  3. now=datetime.datetime.now()
  4. migrate = True
  5. fake_migrate = False
  6. if SUSPEND_SERVICE:
  7. raise HTTP(503, "<html><body><h3>Service is unavailable</h3></body></html>")
  8. if is_gae:
  9. db=GQLDB()
  10. session.connect(request,response,db=db)
  11. else:
  12. db=DAL(DBURI)
  13. PAST=datetime.datetime.today()-datetime.timedelta(minutes=1)
  14. #### cleanup sessions
  15. ##ps=os.path.join(request.folder,'sessions')
  16. ##try: [os.unlink(os.path.join(ps,f)) for f in os.listdir(ps) if os.stat(os.path.join(ps,f))[stat.ST_MTIME]<time.time()-3600]
  17. ##except: pass
  18. #### end cleanup sessions
  19. def wysiwyg(field,value):
  20. return DIV(field.name,TEXTAREA(_name=field.name, _cols="60", value=value, _id="wysiwyg"))
  21. ######################################
  22. ### PERSON
  23. ######################################
  24. db.define_table('auth_user',
  25. ##Field('username', length=512, default='', label=T('Username')),
  26. db.Field('first_name',length=128,label=T('First Name')),
  27. db.Field('last_name',length=128,label=T('Last Name')),
  28. db.Field('email',length=128),
  29. db.Field('password','password',default='',label=T('Password'),readable=False),
  30. db.Field('level','text',label=T('Level'),requires=IS_IN_SET(('principiante','intermedio','avanzado'))),
  31. db.Field('tutorials','list:string',label=T('Tutorials'),readable=False,writable=False),
  32. #db.Field('dni','integer'),
  33. db.Field('certificate','boolean',default=False,label=T('I want a certificate of attendance'),readable=False,writable=False),
  34. db.Field('address',length=255,label=T('Mailing Address'),default=''),
  35. db.Field('city',label=T('City'),default=''),
  36. db.Field('state',label=T('State'),default='Buenos Aires'),
  37. db.Field('country',label=T('Country'),default='Argentina'),
  38. db.Field('zip_code',label=T('Zip/Postal Code'),default=''),
  39. db.Field('phone_number',label=T('Phone Number')),
  40. db.Field('include_in_delegate_listing','boolean',default=True,label=T('Include in Delegates List')),
  41. db.Field('sponsors','boolean',default=True,label=T('Contacto con Auspiciantes'),readable=True,writable=True),
  42. db.Field('personal_home_page',length=128,label=T('Personal Home Page'),default=''),
  43. db.Field('company_name',label=T('Company Name'),default=''),
  44. db.Field('company_home_page',length=128,label=T('Company Home Page'),default=''),
  45. db.Field('t_shirt_size',label=T('T-shirt Size')),
  46. db.Field('attendee_type',label=T('Registration Type'),default=ATTENDEE_TYPES[0][0],readable=False,writable=False),
  47. db.Field('discount_coupon',length=64,label=T('Discount Coupon'), readable=False,writable=False),
  48. db.Field('donation','double',default=0.0,label=T('Donation to PSF'),readable=False,writable=False),
  49. db.Field('amount_billed','double',default=0.0,readable=False,writable=False),
  50. db.Field('amount_added','double',default=0.0,readable=False,writable=False),
  51. db.Field('amount_subtracted','double',default=0.0,readable=False,writable=False),
  52. db.Field('amount_paid','double',default=0.0,readable=False,writable=False),
  53. db.Field('amount_due','double',default=0.0,readable=False,writable=False),
  54. db.Field('resume','text',label=T('Resume (Bio)'),readable=True,writable=True),
  55. db.Field('photo','upload',label=T('Photo'),readable=True,writable=True),
  56. db.Field('cv','upload',label=T('CV'),readable=True,writable=True),
  57. db.Field('speaker','boolean',default=False,readable=False,writable=False),
  58. db.Field('session_chair','boolean',default=False,readable=False,writable=False),
  59. db.Field('manager','boolean',default=False,readable=False,writable=False),
  60. db.Field('reviewer','boolean',default=True,readable=False,writable=False),
  61. db.Field('latitude','double',default=0.0,readable=False,writable=False),
  62. db.Field('longitude','double',default=0.0,readable=False,writable=False),
  63. db.Field('confirmed','boolean',default=False,writable=False,readable=False),
  64. db.Field('registration_key',length=64,default='',readable=False,writable=False),
  65. db.Field('created_by_ip',readable=False,writable=False,default=request.client),
  66. db.Field('created_on','datetime',readable=False,writable=False,default=request.now),
  67. ##db.Field('cena_viernes','boolean', comment="-con cargo-"),
  68. ##db.Field('cena_sabado','boolean', comment="sin cargo para los disertantes + organizadores"),
  69. ##db.Field('cena_obs','string', comment="indique si quiere invitar a la cena a familiares o amigos (cant. de reservas) -con cargo-"),
  70. format="%(last_name)s, %(first_name)s (%(id)s)",
  71. migrate=migrate, fake_migrate=fake_migrate)
  72. # web2py planet model
  73. db.define_table("feed",
  74. Field("name", label=T("name")),
  75. Field("author", label=T("author")),
  76. Field("email", requires=IS_EMAIL(), label=T("email")),
  77. Field("url", requires=IS_URL(), comment=T("RSS/Atom feed")),
  78. Field("link", requires=IS_URL(), comment=T("Blog href"), label=T("link")),
  79. Field("general", "boolean", comment=T("Many categories (needs filters)"), label=T("general")),
  80. migrate=migrate, fake_migrate=fake_migrate)
  81. PLANET_FEEDS_MAX = 4
  82. # end of web2py planet model
  83. ##db.auth_user.username.comment=T('(required)')
  84. db.auth_user.first_name.comment=T('(required)')
  85. db.auth_user.last_name.comment=T('(required)')
  86. db.auth_user.email.comment=T('(required)')
  87. db.auth_user.password.comment=not JANRAIN and T('(required)') or T('(optional)')
  88. db.auth_user.resume.widget=lambda field,value: SQLFORM.widgets.text.widget(field,value,_cols="10",_rows="8")
  89. db.auth_user.photo.comment=T('Your picture (for authors)')
  90. #db.auth_user.dni.comment=T('(required if you need a certificate)')
  91. #db.auth_user.certificate.comment=XML(A(str(T('El Costo de Certificado es $x.-')) + '[2]',_href='#footnote2'))
  92. db.auth_user.t_shirt_size.requires=IS_IN_SET(T_SHIRT_SIZES,T_SHIRT_SIZES_LABELS)
  93. db.auth_user.t_shirt_size.comment='Si desea remera, seleccione tama?o (con costo a definir)'
  94. db.auth_user.level.comment="Conocimiento de Python, para organizaci?n"
  95. db.auth_user.zip_code.comment=T('(also used for attendee mapping)')
  96. db.auth_user.company_name.comment=T('corporation, university, user group, etc.')
  97. db.auth_user.sponsors.comment=XML(A(str(T('Desmarcar si no desea que los Auspiciantes de la conferencia tengan acceso a sus datos de contacto')) + '[1]',_href='#footnote1'))
  98. #db.auth_user.include_in_delegate_listing.comment=T('If checked, your Name, Company and Location will be displayed publicly')
  99. db.auth_user.include_in_delegate_listing.comment=XML(A(str(T('If checked, your Name, Company and Location will be displayed publicly')) + '[1]',_href='#footnote1'))
  100. db.auth_user.resume.comment=T('Short Biography and references (for authors)')
  101. db.auth_user.cv.comment=T('If you want you can upload your CV to be available to our Sponsors in further laboral searchs:')
  102. ##db.auth_user.username.requires=[IS_LENGTH(512),IS_NOT_EMPTY(), IS_NOT_IN_DB(db,'auth_user.username')]
  103. db.auth_user.first_name.requires=[IS_LENGTH(128),IS_NOT_EMPTY()]
  104. db.auth_user.last_name.requires=[IS_LENGTH(128),IS_NOT_EMPTY()]
  105. auth=Auth(globals(),db) # authentication/authorization
  106. db.auth_user.password.requires=[CRYPT()]
  107. if not JANRAIN:
  108. db.auth_user.password.requires.append(IS_NOT_EMPTY())
  109. auth.settings.table_user=db.auth_user
  110. auth.define_tables(username=False)
  111. auth.settings.controller='user'
  112. auth.settings.login_url=URL(r=request,c='user',f='login')
  113. auth.settings.on_failed_authorization=URL(r=request,c='user',f='login')
  114. auth.settings.logout_next=URL(r=request,c='default',f='index')
  115. auth.settings.register_next=URL(r=request,c='default',f='index')
  116. auth.settings.verify_email_next=URL(r=request,c='default',f='index')
  117. auth.settings.profile_next=URL(r=request,c='user',f='profile')
  118. auth.settings.retrieve_password_next=URL(r=request,c='user',f='login')
  119. auth.settings.change_password_next=URL(r=request,c='default',f='index')
  120. auth.settings.logged_url=URL(r=request,c='user',f='profile')
  121. auth.settings.create_user_groups = False
  122. auth.settings.actions_disabled = ['register', 'change_password','request_reset_password']
  123. auth.settings.reset_password_requires_verification = True
  124. if EMAIL_SERVER:
  125. mail=Mail() # mailer
  126. mail.settings.server=EMAIL_SERVER
  127. mail.settings.sender=EMAIL_SENDER
  128. mail.settings.login=EMAIL_AUTH
  129. auth.settings.mailer=mail # for user email verification
  130. auth.settings.registration_requires_verification = EMAIL_VERIFICATION
  131. auth.messages.verify_email_subject = EMAIL_VERIFY_SUBJECT
  132. auth.messages.verify_email = EMAIL_VERIFY_BODY
  133. if RECAPTCHA_PUBLIC_KEY:
  134. auth.setting.captcha=Recaptcha(request,RECAPTCHA_PUBLIC_KEY,RECAPTCHA_PRIVATE_KEY)
  135. auth.define_tables()
  136. db.auth_membership.user_id.represent=lambda v: "%(last_name)s, %(first_name)s (%(id)s)" % db.auth_user[v]
  137. def require_address(person=None):
  138. try:
  139. if (request.vars.donation_to_PSF \
  140. and float(request.vars.donation_to_PSF)!=0.0)\
  141. or (person and person.donation_to_PSF):
  142. db.auth_user.address1.requires.append(IS_NOT_EMPTY())
  143. db.auth_user.city.requires.append(IS_NOT_EMPTY())
  144. db.auth_user.state.requires.append(IS_NOT_EMPTY())
  145. db.auth_user.zip_code.requires.append(IS_NOT_EMPTY())
  146. except: pass
  147. require_address()
  148. db.auth_user.email.requires=[IS_LENGTH(128),IS_EMAIL(),IS_NOT_IN_DB(db,'auth_user.email')]
  149. db.auth_user.personal_home_page.requires=[IS_LENGTH(128),IS_NULL_OR(IS_URL())]
  150. db.auth_user.company_home_page.requires=[IS_LENGTH(128),IS_NULL_OR(IS_URL())]
  151. db.auth_user.country.requires=IS_IN_SET(COUNTRIES)
  152. db.auth_user.created_by_ip.requires=\
  153. IS_NOT_IN_DB(db(db.auth_user.created_on>PAST),'auth_user.created_by_ip')
  154. db.auth_user.registration_key.default=str(uuid.uuid4())
  155. db.auth_user.reviewer.writable=db.auth_user.reviewer.readable=auth.has_membership('manager')
  156. db.auth_user.speaker.writable=db.auth_user.speaker.readable=auth.has_membership('manager')
  157. # Enable tutorial selection after proposal deadline
  158. db.auth_user.tutorials.writable = db.auth_user.tutorials.readable = TODAY_DATE>PROPOSALS_DEADLINE_DATE
  159. db.auth_user.tutorials.label = "Charlas Preferidas"
  160. # Enable simplified registration (no password asked)
  161. if SIMPLIFIED_REGISTRATION and TODAY_DATE>REVIEW_DEADLINE_DATE and request.controller=='user' and request.function=='register':
  162. db.auth_user.password.readable = False
  163. db.auth_user.password.writable = False
  164. ##db.auth_user.confirmed.default = False
  165. else:
  166. db.auth_user.confirmed.default = False
  167. ##db.auth_user.confirmed.readable = True
  168. ##db.auth_user.confirmed.writable = True
  169. db.auth_user.confirmed.label = T("Confirm attendance")
  170. # conference options
  171. db.define_table("option",
  172. Field("name", "string", unique=True),
  173. Field("value", "text", comment=T("Value or record reference")),
  174. Field("valuetype", requires=IS_EMPTY_OR(IS_IN_SET({"integer":T("integer"),
  175. "double":T("double"), "string":T("string"), "text": T("text"),
  176. "boolean":T("boolean"), "date": T("date"), "datetime": T("datetime"),
  177. "reference": T("reference")}))),
  178. Field("tablename", requires=IS_EMPTY_OR(IS_IN_SET(db.tables)), default=None),
  179. Field("description", "text"),
  180. format=lambda row: row.name,
  181. migrate=migrate, fake_migrate=fake_migrate
  182. )
  183. def get_option(name, default=None):
  184. cdata = cache.ram(name, lambda: retrieve_option(name, default=default), 12*60*60)
  185. return cdata
  186. def retrieve_option(name, default=None):
  187. option = db(db.option.name==name).select().first()
  188. if option is not None:
  189. if option.valuetype == "reference":
  190. try:
  191. obj = db[option.tablename][int(option.value)]
  192. except (ValueError, TypeError, AttributeError):
  193. obj = default
  194. else:
  195. try:
  196. if option.valuetype == "integer":
  197. obj = int(option.value)
  198. elif option.valuetype == "double":
  199. obj = float(option.value)
  200. elif option.valuetype == "boolean":
  201. if option.value in ("", "False", None, False):
  202. obj = False
  203. else:
  204. obj = True
  205. elif option.valuetype == "date":
  206. ymd = [int(v) for v in option.value.split("-")]
  207. obj = datetime.date(ymd[0], ymd[1], ymd[2])
  208. elif option.valuetype == "datetime":
  209. split_data = option.value.split(" ")
  210. ymd = [int(v) for v in split_data[0].split("-")]
  211. hms = [int(v) for v in split_data[1].split(":")]
  212. obj = datetime.datetime(ymd[0], ymd[1], ymd[2],
  213. hms[0], hms[1], hms[2])
  214. else:
  215. # string, text, other types
  216. obj = option.value
  217. except (ValueError, TypeError, AttributeError):
  218. obj = option.value
  219. else:
  220. obj = default
  221. return obj