MobileBlur

Diff
Login

Diff

Differences From Artifact [60791b7dca]:

To Artifact [0948ae43fd]:


19
20
21
22
23
24
25
26


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46


47
48
49
50


51
52
53
54
55
56
57
58
59
60
61
62
63

64
65

66
67
68
69
70
71
72
19
20
21
22
23
24
25

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

47
48
49
50
51

52
53
54
55
56
57
58
59
60
61
62
63
64
65

66
67

68
69
70
71
72
73
74
75







-
+
+



















-
+
+



-
+
+












-
+

-
+







                  ('email_server','localhost'),
                  ('email_sender','you@example.com'),
                  ('email_login',''),
                  ('login_method','local'),
                  ('login_config',''),
                  ('plugins',[])],
        'tables':['auth_user'],
        'table_auth_user':['username','first_name','last_name','email','password'],
        'table_auth_user':['username','first_name',
                           'last_name','email','password'],
        'pages':['index','error'],
        'page_index':'# Welcome to my new app',
        'page_error':'# Error: the document does not exist',
        }

if not session.app: reset(session)

def listify(x):
    if not isinstance(x,(list,tuple)):
        return x and [x] or []
    return x

def clean(name):
    return re.sub('\W+','_',name.strip().lower())

def index():
    response.view='wizard/step.html'
    reset(session)
    apps=os.listdir(os.path.join(request.folder,'..'))
    form=SQLFORM.factory(Field('name',requires=[IS_NOT_EMPTY(),IS_ALPHANUMERIC()]))
    form=SQLFORM.factory(Field('name',requires=[IS_NOT_EMPTY(),
                                                IS_ALPHANUMERIC()]))
    if form.accepts(request.vars):
        app = form.vars.name
        session.app['name'] = app
        if MULTI_USER_MODE and db(db.app.name==app)(db.app.owner!=auth.user.id).count():
        if MULTI_USER_MODE and db(db.app.name==app)\
                (db.app.owner!=auth.user.id).count():
            session.flash = 'App belongs already to other user'
        elif app in apps:
            meta = os.path.normpath(\
                os.path.join(os.path.normpath(request.folder),
                             '..',app,'wizard.metadata'))
            if os.path.exists(meta):
                try:
                    metafile = open(meta,'rb')
                    try:
                        session.app = pickle.load(metafile)
                    finally:
                        metafile.close()
                    session.flash = "The app exists, was created by wizard, continue to overwrite!"
                    session.flash = T("The app exists, was created by wizard, continue to overwrite!")
                except:
                    session.flash = "The app exists, was NOT created by wizard, continue to overwrite!"
                    session.flash = T("The app exists, was NOT created by wizard, continue to overwrite!")
        redirect(URL('step1'))
    return dict(step='Start',form=form)


def step1():
    from gluon.contrib.simplejson import loads
    import urllib
116
117
118
119
120
121
122
123
124
125






126
127
128
129
130
131
132
133
134
135
136





137
138
139
140
141
142
143
119
120
121
122
123
124
125



126
127
128
129
130
131
132
133
134
135
136
137





138
139
140
141
142
143
144
145
146
147
148
149







-
-
-
+
+
+
+
+
+






-
-
-
-
-
+
+
+
+
+







    return dict(step='1: Setting Parameters',form=form)

def step2():
    response.view='wizard/step.html'
    form=SQLFORM.factory(Field('table_names','list:string',
                               default=session.app['tables']))
    if form.accepts(request.vars):
        table_names = [clean(t) for t in listify(form.vars.table_names) if t.strip()]
        if [t for t in table_names if t.startswith('auth_') and not t=='auth_user']:
            form.error.table_names = T('invalid table names (auth_* tables already defined)')
        table_names = [clean(t) for t in listify(form.vars.table_names) \
                           if t.strip()]
        if [t for t in table_names if t.startswith('auth_') and \
                not t=='auth_user']:
            form.error.table_names = \
                T('invalid table names (auth_* tables already defined)')
        else:
            session.app['tables']=table_names
            for table in session.app['tables']:
                if not 'table_'+table in session.app:
                    session.app['table_'+table]=['name']
                if not table=='auth_user':
                    for key in ['create','read','update','select','search']:
                        name = table+'_'+key
                        if not name in session.app['pages']:
                            session.app['pages'].append(name)
                            session.app['page_'+name]='## %s %s' % (key.capitalize(),table)
                    name = table+'_manage'
                    if not name in session.app['pages']:
                        session.app['pages'].append(name)
                        session.app['page_'+name] = \
                            '## Manage %s\n{{=form}}' % (table)
            if session.app['tables']:
                redirect(URL('step3',args=0))
            else:
                redirect(URL('step4'))
    return dict(step='2: Tables',form=form)

def step3():
162
163
164
165
166
167
168
169


170
171
172
173
174
175
176
168
169
170
171
172
173
174

175
176
177
178
179
180
181
182
183







-
+
+







        except RuntimeError:
            response.flash=T('invalid circual reference')
        else:
            if n<m-1:
                redirect(URL('step3',args=n+1))
            else:
                redirect(URL('step4'))
    return dict(step='3: Fields for table "%s" (%s of %s)' % (table,n+1,m),table=table,form=form)
    return dict(step='3: Fields for table "%s" (%s of %s)' \
                    % (table,n+1,m),table=table,form=form)

def step4():
    response.view='wizard/step.html'
    form=SQLFORM.factory(Field('pages','list:string',
                               default=session.app['pages']))
    if form.accepts(request.vars):
        session.app['pages']=[clean(t)
187
188
189
190
191
192
193
194


195
196
197
198
199
200
201
194
195
196
197
198
199
200

201
202
203
204
205
206
207
208
209







-
+
+







    n=int(request.args(0) or 0)
    m=len(session.app['pages'])
    if n>=m: redirect(URL('step4'))
    page=session.app['pages'][n]
    markmin_url='http://web2py.com/examples/static/markmin.html'
    form=SQLFORM.factory(Field('content','text',
                               default=session.app.get('page_'+page,[]),
                               comment=A('use markmin',_href=markmin_url,_target='_blank')),
                               comment=A('use markmin',
                                         _href=markmin_url,_target='_blank')),
                         formstyle='table2cols')
    if form.accepts(request.vars):
        session.app['page_'+page]=form.vars.content
        if n<m-1:
            redirect(URL('step5',args=n+1))
        else:
            redirect(URL('step6'))
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


272
273
274
275
276
277
278
279
280
281
282


283
284
285
286
287
288
289
255
256
257
258
259
260
261


262
263
264
265
266
267
268
269
270
271
272
273
274
275
276

277
278
279
280
281
282
283
284
285
286
287


288
289
290
291
292
293
294
295
296







-
-















-
+
+









-
-
+
+








def make_table(table,fields):
    rawtable=table
    if table!='auth_user': table='t_'+table
    s=''
    s+='\n'+'#'*40+'\n'
    s+="db.define_table('%s',\n" % table
    s+="    Field('id','id',\n"
    s+="          represent=lambda id:SPAN(id,' ',A('view',_href=URL('%s_read',args=id)))),\n"%rawtable
    first_field='id'
    for field in fields:
        items=[x.lower() for x in field.split()]
        has = {}
        keys = []
        for key in ['notnull','unique','integer','double','boolean','float',
                    'boolean', 'date','time','datetime','text','wiki',
                    'html','file','upload','image','true',
                    'hidden','readonly','writeonly','multiple',
                    'notempty','required']:
            if key in items[1:]:
                keys.append(key)
                has[key] = True
        tables = session.app['tables']
        refs = [t for t in tables if t in items]
        items = items[:1] + [x for x in items[1:] if not x in keys and not x in tables]
        items = items[:1] + [x for x in items[1:] \
                                 if not x in keys and not x in tables]
        barename = name = '_'.join(items)
        if table[:2]=='t_': name='f_'+name
        if first_field=='id': first_field=name

        ### determine field type
        ftype='string'
        deftypes={'integer':'integer','double':'double','boolean':'boolean',
                  'float':'double','bool':'boolean',
                  'date':'date','time':'time','datetime':'datetime',
                  'text':'text','file':'upload','image':'upload','upload':'upload',
                  'wiki':'text', 'html':'text'}
                  'text':'text','file':'upload','image':'upload',
                  'upload':'upload','wiki':'text', 'html':'text'}
        for key,t in deftypes.items():
            if key in has:                
                ftype = t
        if refs:
            key = refs[0]
            if not key=='auth_user': key='t_'+key
            if 'multiple' in has:
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

332
333
334
335
336
337
338





339
340
341
342
343
344
345
346
347
348
349
350
351


352
353
354
355
356
357
358
359
360
361
362
363
364
365

366
367
368
369
370
371
372
373
374
310
311
312
313
314
315
316




317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333

334







335
336
337
338
339







340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360

361
362

363
364
365
366
367
368
369







-
-
-
-

















-
+
-
-
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-






+
+













-
+

-







            s+=', notnull=True'
        if 'unique' in has:
            s+=', unique=True'
        if ftype=='boolean' and 'true' in has:
            s+=",\n          default=True"

        ### determine field representation
        if 'image' in has:
            s+=",\n          represent=lambda x: x and IMG(_alt='image',_src=URL('download',args=x), _width='200px') or ''"
        elif ftype in ('file','upload'):
            s+=",\n          represent=lambda x: x and A('download',_href=URL('download',args=x)) or ''"
        elif 'wiki' in has:
            s+=",\n          represent=lambda x: MARKMIN(x)"
            s+=",\n          comment='WIKI (markmin)'"
        elif 'html' in has:
            s+=",\n          represent=lambda x: XML(x,sanitize=True)"
            s+=",\n          comment='HTML (sanitized)'"
        ### determine field access
        if name=='password' or 'writeonly' in has:
            s+=",\n          readable=False"
        elif 'hidden' in has:
            s+=",\n          writable=False, readable=False"
        elif 'readonly' in has:
            s+=",\n          writable=False"

        ### make up a label
        s+=",\n          label=T('%s')),\n" % \
            ' '.join(x.capitalize() for x in barename.split('_'))
    if table!='auth_user':
    if table=='auth_user':
        s+="    Field('is_active','boolean',default=True,\n"
        s+="          label=T('Active'),writable=False,readable=False),\n"
    s+="    Field('created_on','datetime',default=request.now,\n"
    s+="          label=T('Created On'),writable=False,readable=False),\n"
    s+="    Field('modified_on','datetime',default=request.now,\n"
    s+="          label=T('Modified On'),writable=False,readable=False,\n"
    s+="          update=request.now),\n"
        s+="    Field('created_on','datetime',default=request.now,\n"
        s+="          label=T('Created On'),writable=False,readable=False),\n"
        s+="    Field('modified_on','datetime',default=request.now,\n"
        s+="          label=T('Modified On'),writable=False,readable=False,\n"
        s+="          update=request.now),\n"
    if not table=='auth_user' and 'auth_user' in session.app['tables']:
        s+="    Field('created_by',db.auth_user,default=auth.user_id,\n"
        s+="          label=T('Created By'),writable=False,readable=False),\n"
        s+="    Field('modified_by',db.auth_user,default=auth.user_id,\n"
        s+="          label=T('Modified By'),writable=False,readable=False,\n"
        s+="          update=auth.user_id),\n"
    elif table=='auth_user':
        s+="    Field('registration_key',default='',\n"
        s+="          writable=False,readable=False),\n"
        s+="    Field('reset_password_key',default='',\n"
        s+="          writable=False,readable=False),\n"
        s+="    Field('registration_id',default='',\n"
        s+="          writable=False,readable=False),\n"
    elif 'auth_user' in session.app['tables']:
        s+="    auth.signature,\n"
    s+="    format='%("+first_field+")s',\n"
    s+="    migrate=settings.migrate)\n\n"
    if table=='auth_user':
        s+="""
db.auth_user.first_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
db.auth_user.last_name.requires = IS_NOT_EMPTY(error_message=auth.messages.is_empty)
db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key)
db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username)
db.auth_user.registration_id.requires = IS_NOT_IN_DB(db, db.auth_user.registration_id)
db.auth_user.email.requires = (IS_EMAIL(error_message=auth.messages.invalid_email),
                               IS_NOT_IN_DB(db, db.auth_user.email))
"""
    else:
        s+="db.define_table('%s_archive',db.%s,Field('current_record','reference %s'))\n" % (table,table,table)
        s+="db.define_table('%s_archive',db.%s,Field('current_record','reference %s',readable=False,writable=False))\n" % (table,table,table)
    return s


def fix_db(filename):
    params = dict(session.app['params'])
    content = read_file(filename,'rb')
    if 'auth_user' in session.app['tables']:
        auth_user = make_table('auth_user',session.app['table_auth_user'])
        content = content.replace('sqlite://storage.sqlite',
388
389
390
391
392
393
394
395
396
397
398
399
400
401







402
403
404
405
406
407
408
409








410
411
412
413
414
415
416
417
418
419


420
421
422
423
424


425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443

444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493

494
495
496
497
498
499
500
383
384
385
386
387
388
389







390
391
392
393
394
395
396

397






398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413


414
415





416
417



















418




419
420
421
422
423
424


































425
426
427

428

429
430
431
432
433
434
435
436







-
-
-
-
-
-
-
+
+
+
+
+
+
+
-

-
-
-
-
-
-
+
+
+
+
+
+
+
+








-
-
+
+
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-






-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-



-

-
+







    api_key = settings.login_config.split(':')[-1],
    domain = settings.login_config.split(':')[0],
    url = "http://%s/%s/default/user/login" % (request.env.http_host,request.application))
"""
    write_file(filename, content, 'wb')

def make_menu(pages):
    s="""
response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%s <%s>' % (settings.author, settings.author_email)
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
    s=''
    s+='response.title = settings.title\n'
    s+='response.subtitle = settings.subtitle\n'
    s+="response.meta.author = '%(author)s <%(author_email)s>' % settings\n"
    s+='response.meta.keywords = settings.keywords\n'
    s+='response.meta.description = settings.description\n'
    s+='response.menu = [\n'
"""
    for page in pages:
        if not page.endswith('_read') and \
                not page.endswith('_update') and \
                not page.endswith('_search') and \
                not page.startswith('_') and not page.startswith('error'):
            s+="    (T('%s'),URL('default','%s')==URL(),URL('default','%s'),[]),\n" % \
                (' '.join(x.capitalize() for x in page.split('_')),page,page)
        if not page.startswith('error'):
            if page.endswith('_manage'):
                page_name = page[:-7]
            else:
                page_name = page
            page_name = ' '.join(x.capitalize() for x in page_name.split('_'))
            s+="(T('%s'),URL('default','%s')==URL(),URL('default','%s'),[]),\n" \
                % (page_name,page,page)
    s+=']'
    return s

def make_page(page,contents):
    if 'auth_user' in session.app['tables'] and not page in ('index','error'):
        s="@auth.requires_login()\ndef %s():\n" % page
    else:
        s="def %s():\n" % page
    items=page.rsplit('_',1)
    if items[0] in session.app['tables'] and len(items)==2:
    items = page.rsplit('_',1)
    if items[0] in session.app['tables'] and len(items)==2 and items[1]=='manage':
        t=items[0]
        if items[1]=='read':
            s+="    record = db.t_%s(request.args(0)) or redirect(URL('error'))\n" % t
            s+="    form=crud.read(db.t_%s,record)\n" % t
            s+="    return dict(form=form)\n\n"
        s+="    form = SQLFORM.smartgrid(db.t_%s,onupdate=auth.archive)\n" % items[0]
        s+="    return locals()\n\n"
        elif items[1]=='update':
            s+="    record = db.t_%s(request.args(0),is_active=True) or redirect(URL('error'))\n" % t
            s+="    form=crud.update(db.t_%s,record,next='%s_read/[id]',\n"  % (t,t)
            s+="                     ondelete=lambda form: redirect(URL('%s_select')),\n" % t
            s+="                     onaccept=crud.archive)\n"
            s+="    return dict(form=form)\n\n"
        elif items[1]=='create':
            s+="    form=crud.create(db.t_%s,next='%s_read/[id]')\n" % (t,t)
            s+="    return dict(form=form)\n\n"
        elif items[1]=='select':
            s+="    f,v=request.args(0),request.args(1)\n"
            s+="    try: query=f and db.t_%s[f]==v or db.t_%s\n" % (t,t)
            s+="    except: redirect(URL('error'))\n"
            s+="    rows=db(query)(db.t_%s.is_active==True).select()\n" % t
            s+="    return dict(rows=rows)\n\n"
        elif items[1]=='search':
            s+="    form, rows=crud.search(db.t_%s,query=db.t_%s.is_active==True)\n" % (t,t)
            s+="    return dict(form=form, rows=rows)\n\n"
        else:
    else:
            t=None
    else:
        t=None
    if not t:
        s+="    return dict()\n\n"
    return s

def make_view(page,contents):
    s="{{extend 'layout.html'}}\n\n"
    s+=str(MARKMIN(contents))
    items=page.rsplit('_',1)
    if items[0] in session.app['tables'] and len(items)==2:
        t=items[0]
        if items[1]=='read':
            s+="\n{{=A(T('edit %s'),_href=URL('%s_update',args=request.args(0)))}}\n<br/>\n"%(t,t)
            s+='\n{{=form}}\n'
            s+="{{for t,f in db.t_%s._referenced_by:}}{{if not t[-8:]=='_archive':}}" % t
            s+="[{{=A(t[2:],_href=URL('%s_select'%t[2:],args=(f,form.record.id)))}}]"
            s+='{{pass}}{{pass}}'
        elif items[1]=='create':
            s+="\n{{=A(T('select %s'),_href=URL('%s_select'))}}\n<br/>\n"%(t,t)
            s+='\n{{=form}}\n'
        elif items[1]=='update':
            s+="\n{{=A(T('show %s'),_href=URL('%s_read',args=request.args(0)))}}\n<br/>\n"%(t,t)
            s+='\n{{=form}}\n'
        elif items[1]=='select':
            s+="\n{{if request.args:}}<h3>{{=T('For %s #%s' % (request.args(0)[2:],request.args(1)))}}</h3>{{pass}}\n"
            s+="\n{{=A(T('create new %s'),_href=URL('%s_create'))}}\n<br/>\n"%(t,t)
            s+="\n{{=A(T('search %s'),_href=URL('%s_search'))}}\n<br/>\n"%(t,t)
            s+="\n{{if rows:}}"
            s+="\n  {{headers=dict((str(k),k.label) for k in db.t_%s)}}" % t
            s+="\n  {{=SQLTABLE(rows,headers=headers)}}"
            s+="\n{{else:}}"
            s+="\n  {{=TAG.blockquote(T('No Data'))}}"
            s+="\n{{pass}}\n"
        elif items[1]=='search':
            s+="\n{{=A(T('create new %s'),_href=URL('%s_create'))}}\n<br/>\n"%(t,t)
            s+='\n{{=form}}\n'
            s+="\n{{if rows:}}"
            s+="\n  {{headers=dict((str(k),k.label) for k in db.t_%s)}}" % t
            s+="\n  {{=SQLTABLE(rows,headers=headers)}}"
            s+="\n{{else:}}"
            s+="\n  {{=TAG.blockquote(T('No Data'))}}"
            s+="\n{{pass}}\n"
    return s

def populate(tables):

    s = 'from gluon.contrib.populate import populate\n'
    s+= 'if not db(db.auth_user).count():\n'
    s+= 'if db(db.auth_user).isempty():\n'
    for table in sort_tables(tables):
        t=table=='auth_user' and 'auth_user' or 't_'+table
        s+="     populate(db.%s,10)\n" % t
    return s

def create(options):
    if DEMO_MODE:
587
588
589
590
591
592
593
594

595
596
597
598
599
600
601
602
603
523
524
525
526
527
528
529

530


531
532
533
534
535
536
537







-
+
-
-







        controller = os.path.join(request.folder,'..',app,'controllers','default.py')
        file = open(controller,'wb')
        try:
            file.write("""# -*- coding: utf-8 -*-
### required - do no delete
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call():
def call(): return service()
    session.forget()
    return service()
### end requires
""")
            for page in session.app['pages']:
                file.write(make_page(page,session.app.get('page_'+page,'')))
        finally:
            file.close()