Taskenizer

Check-in [e2ebb78c9c]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Made it use mysql instead of SQLITE
Timelines: family | ancestors | coming_up
Files: files | file ages | folders
SHA1: e2ebb78c9cb5f41e43c887763dfb472fb2342ddc
User & Date: joseph 2019-12-15 16:10:11
Context
2019-12-15
16:10
Made it use mysql instead of SQLITE Leaf check-in: e2ebb78c9c user: joseph tags: coming_up
2018-08-25
15:33
Switched up task-forecaster to 7 days check-in: 4143a1ff2a user: joseph tags: coming_up
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to add_user.py.

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
..
70
71
72
73
74
75
76
77
78
79
80




81
82
83
84
85
86
87
...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    database = conf['System']['dblocation']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
................................................................................
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

if not os.access(database, os.W_OK):
    print('''ERROR: no write permission to database file at ''' + database)
    sys.exit(1)

import sqlite3
dbconn = sqlite3.connect(database)
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")





# Ask for username, timezone and finally passphrase twice
d = Dialog(dialog="dialog", autowidgetsize=True)
d.set_background_title("Create Taskenizer user")

# Username
stage1error = ''
................................................................................
        stage1error = error.args[0]
        continue

    # Check it's not already taken
    tup = (chname,)
    conn.execute('''SELECT COUNT(*)
                    FROM User
                    WHERE username = ?;''', tup)
    result1 = conn.fetchone()

    if result1[0] > 0:
        stage1error = 'That username is already taken. '
        continue

    break







|







 







|
|
|
|
>
>
>
>







 







|







52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
..
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
...
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    dbname = conf['System']['dbname']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
................................................................................
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

if not os.access(database, os.W_OK):
    print('''ERROR: no write permission to database file at ''' + database)
    sys.exit(1)

# import sqlite3
# dbconn = sqlite3.connect(database)
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

import mysql.connector as mariadb
dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

# Ask for username, timezone and finally passphrase twice
d = Dialog(dialog="dialog", autowidgetsize=True)
d.set_background_title("Create Taskenizer user")

# Username
stage1error = ''
................................................................................
        stage1error = error.args[0]
        continue

    # Check it's not already taken
    tup = (chname,)
    conn.execute('''SELECT COUNT(*)
                    FROM User
                    WHERE username = %s;''', tup)
    result1 = conn.fetchone()

    if result1[0] > 0:
        stage1error = 'That username is already taken. '
        continue

    break

Changes to cron/backup_database.

15
16
17
18
19
20
21



22
23
24
25
26
27
28
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Taskenizer.  If not, see <http://www.gnu.org/licenses/>.

# OK so this makes a backup of Taskenizer's database in a new file.
# First arg is config file of Taskenizer instance. Second arg is backup file.




set -e

if ! [[ -f $1 ]]
then
    echo 'Error: config file must be specified as the first argument.'








>
>
>







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Taskenizer.  If not, see <http://www.gnu.org/licenses/>.

# OK so this makes a backup of Taskenizer's database in a new file.
# First arg is config file of Taskenizer instance. Second arg is backup file.

#### THIS SCRIPT CURRENTLY DOESN'T WORK AS IT HASN'T BEEN ADAPTED FOR MYSQL
exit 1

set -e

if ! [[ -f $1 ]]
then
    echo 'Error: config file must be specified as the first argument.'

Changes to cron/delete_old_shm.

15
16
17
18
19
20
21



22
23
24
25
26
27
28
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Taskenizer.  If not, see <http://www.gnu.org/licenses/>.

# OK so this will look for files called /dev/shm/taskenizer_catkey_* and if
# they're older than one day delete them. This should be run once an hour.




set -e

if ! [[ -f $1 ]]
then
    echo 'Error: config file must be specified as the first argument.'








>
>
>







15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Taskenizer.  If not, see <http://www.gnu.org/licenses/>.

# OK so this will look for files called /dev/shm/taskenizer_catkey_* and if
# they're older than one day delete them. This should be run once an hour.

#### THIS SCRIPT CURRENTLY DOESN'T WORK AS IT HASN'T BEEN ADAPTED FOR MYSQL
exit 1

set -e

if ! [[ -f $1 ]]
then
    echo 'Error: config file must be specified as the first argument.'

Changes to cron/force_reload.py.

44
45
46
47
48
49
50
51
52
53
54




55
56
57
58
59
60
61
..
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

# These imports must be done after the python search path is updated
from taskenizer.functions.operations import find_time
from taskenizer.functions.operations import inc_change_num

cur_time = int(time.time())

import sqlite3
dbconn = sqlite3.connect(conf['System']['dblocation'])
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")





# Get a list of all user ids and last reload force days.
conn.execute('''SELECT id, last_forced_reload_day
             FROM User;''')

# For each user
for row in conn.fetchall():
................................................................................
        # Increment the change numbers on all their categories to
        # force a reload.
        tup = (user_id,)

        # Note categories
        conn.execute('''SELECT id
                     FROM NoteCat
                     WHERE user_id = ?;''', tup)

        for row in conn.fetchall():
            cat_id = row[0]

            inc_change_num(conn, 0, cat_id, None)

        # AutoHabit categories
        conn.execute('''SELECT id
                     FROM AutoHabitCat
                     WHERE user_id = ?;''', tup)

        for row in conn.fetchall():
            cat_id = row[0]

            inc_change_num(conn, 1, cat_id, None)

        # ManuHabit categories
        conn.execute('''SELECT id
                     FROM ManuHabitCat
                     WHERE user_id = ?;''', tup)

        for row in conn.fetchall():
            cat_id = row[0]

            inc_change_num(conn, 2, cat_id, None)

        # Update their `last_forced_reload_day' value.
        tup = (cur_date, user_id,)
        conn.execute('''UPDATE User
                     SET last_forced_reload_day = ?
                     WHERE id = ?;''', tup)

dbconn.commit()
dbconn.close()







|
|
|
|
>
>
>
>







 







|









|









|









|
|



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
..
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116

# These imports must be done after the python search path is updated
from taskenizer.functions.operations import find_time
from taskenizer.functions.operations import inc_change_num

cur_time = int(time.time())

# import sqlite3
# dbconn = sqlite3.connect(conf['System']['dblocation'])
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

import mysql.connector as mariadb
dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

# Get a list of all user ids and last reload force days.
conn.execute('''SELECT id, last_forced_reload_day
             FROM User;''')

# For each user
for row in conn.fetchall():
................................................................................
        # Increment the change numbers on all their categories to
        # force a reload.
        tup = (user_id,)

        # Note categories
        conn.execute('''SELECT id
                     FROM NoteCat
                     WHERE user_id = %s;''', tup)

        for row in conn.fetchall():
            cat_id = row[0]

            inc_change_num(conn, 0, cat_id, None)

        # AutoHabit categories
        conn.execute('''SELECT id
                     FROM AutoHabitCat
                     WHERE user_id = %s;''', tup)

        for row in conn.fetchall():
            cat_id = row[0]

            inc_change_num(conn, 1, cat_id, None)

        # ManuHabit categories
        conn.execute('''SELECT id
                     FROM ManuHabitCat
                     WHERE user_id = %s;''', tup)

        for row in conn.fetchall():
            cat_id = row[0]

            inc_change_num(conn, 2, cat_id, None)

        # Update their `last_forced_reload_day' value.
        tup = (cur_date, user_id,)
        conn.execute('''UPDATE User
                     SET last_forced_reload_day = %s
                     WHERE id = %s;''', tup)

dbconn.commit()
dbconn.close()

Changes to cron/seek_huge_usage.py.

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
76
77
78
# Read the config file

conf = configparser.ConfigParser()
conf.read(config_file)

sys.path.append(os.path.abspath(conf['System']['code_location']))

import sqlite3
dbconn = sqlite3.connect(conf['System']['dblocation'])
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")





def check_violation(user_id, table, maxim, huge):
    # Count how many tasks there are. `maxim' is the maximum allowed
    # number of tasks and `huge' is the maximum size.
    tup = (user_id,)
    conn.execute('''SELECT COUNT(*)
                 FROM %s
                 WHERE user_id = ?;''' % table, tup)

    number = conn.fetchone()[0]

    if number > maxim:
        print("User id `" + str(user_id) + "' has created " + str(number) +
              " `" + table + "' table entries.")

    # If `huge' is set to `0' we don't run the size check
    if huge > 0:
        # Look for any tasks longer than the allowed size
        tup = (huge, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM %s
                     WHERE LENGTH(name) > ?
                     AND user_id = ?;''' % table, tup)

        big = conn.fetchone()[0]

        if big > 0:
            print("User id `" + str(user_id) + "' has created " + str(big) +
                  " `" + table +
                  "' table entries with `name' fields larger than " +







|
|
|
|

>
>
>







|













|
|







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
76
77
78
79
80
81
# Read the config file

conf = configparser.ConfigParser()
conf.read(config_file)

sys.path.append(os.path.abspath(conf['System']['code_location']))

# #import sqlite3
# dbconn = sqlite3.connect(conf['System']['dblocation'])
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

import mysql.connector as mariadb
dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

def check_violation(user_id, table, maxim, huge):
    # Count how many tasks there are. `maxim' is the maximum allowed
    # number of tasks and `huge' is the maximum size.
    tup = (user_id,)
    conn.execute('''SELECT COUNT(*)
                 FROM %s
                 WHERE user_id = %%s;''' % table, tup)

    number = conn.fetchone()[0]

    if number > maxim:
        print("User id `" + str(user_id) + "' has created " + str(number) +
              " `" + table + "' table entries.")

    # If `huge' is set to `0' we don't run the size check
    if huge > 0:
        # Look for any tasks longer than the allowed size
        tup = (huge, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM %s
                     WHERE LENGTH(name) > %%s
                     AND user_id = %%s;''' % table, tup)

        big = conn.fetchone()[0]

        if big > 0:
            print("User id `" + str(user_id) + "' has created " + str(big) +
                  " `" + table +
                  "' table entries with `name' fields larger than " +

Changes to del_user.py.

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
67
68
69
70
71
72
73
74
75
76
77




78
79
80
81
82
83
84
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    database = conf['System']['dblocation']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
................................................................................
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

if not os.access(database, os.W_OK):
    print('''ERROR: no write permission to database file at ''' + database)
    sys.exit(1)

import sqlite3
dbconn = sqlite3.connect(database)
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")





# Ask which user to delete, then ask for confirmation.
d = Dialog(dialog="dialog", autowidgetsize=True)
d.set_background_title("Delete Taskenizer user")

# Get list of users
conn.execute('''SELECT id, username







|







 







|
|
|
|
>
>
>
>







49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    dbname = conf['System']['dbname']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
................................................................................
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

if not os.access(database, os.W_OK):
    print('''ERROR: no write permission to database file at ''' + database)
    sys.exit(1)

# import sqlite3
# dbconn = sqlite3.connect(database)
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

import mysql.connector as mariadb
dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

# Ask which user to delete, then ask for confirmation.
d = Dialog(dialog="dialog", autowidgetsize=True)
d.set_background_title("Delete Taskenizer user")

# Get list of users
conn.execute('''SELECT id, username

Changes to doc/taskenizer.conf.

1
2
3
4
5
6
7
8
9
10
11
12






13
14
15
16
17
18
19
[System]
# Please always include a trailing slash on directory names otherwize the
# sky will fall down.

code_location = /usr/local/lib/Taskenizer/
dblocation = /var/lib/taskenizer/data/data.db
locks = /var/lib/taskenizer/data/locks/
user_locks = /var/lib/taskenizer/data/locks/user/
request_log = /var/log/taskenizer_req.log
socket = 127.0.0.1:3031
user = taskenizer
shmdir = /dev/shm/







# This is where Taskenizer's static files will be stored. You don't need to
# populate this, taskenizer-run will populate it when it starts.
servlocation = /usr/share/nginx/html/taskenizer_static/

# These are the web addresses of Taskenizer's static files and the
# Taskenizer engine.





<






>
>
>
>
>
>







1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[System]
# Please always include a trailing slash on directory names otherwize the
# sky will fall down.

code_location = /usr/local/lib/Taskenizer/

locks = /var/lib/taskenizer/data/locks/
user_locks = /var/lib/taskenizer/data/locks/user/
request_log = /var/log/taskenizer_req.log
socket = 127.0.0.1:3031
user = taskenizer
shmdir = /dev/shm/

dbhost = localhost
dbport = 3306
dbname = taskenizer
dbuser = tas
dbpass = 

# This is where Taskenizer's static files will be stored. You don't need to
# populate this, taskenizer-run will populate it when it starts.
servlocation = /usr/share/nginx/html/taskenizer_static/

# These are the web addresses of Taskenizer's static files and the
# Taskenizer engine.

Changes to list_users.py.

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
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    database = conf['System']['dblocation']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
    sys.exit(1)

if not os.access(database, os.R_OK):
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

import sqlite3
dbconn = sqlite3.connect(database)
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")





# Get a list of all user data.
conn.execute('''SELECT id, username, reg_date, tz, ip_address
             FROM User;''')

user_data = conn.fetchall()








|













|
|
|
|
>
>
>
>







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
76
77
78
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    dbname = conf['System']['dbname']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
    sys.exit(1)

if not os.access(database, os.R_OK):
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

# import sqlite3
# dbconn = sqlite3.connect(database)
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

import mysql.connector as mariadb
dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

# Get a list of all user data.
conn.execute('''SELECT id, username, reg_date, tz, ip_address
             FROM User;''')

user_data = conn.fetchall()

Changes to notification_broadcast.py.

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
..
69
70
71
72
73
74
75
76
77
78
79




80
81
82
83
84
85
86
...
127
128
129
130
131
132
133
134
135
136
137
138
139
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    database = conf['System']['dblocation']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
................................................................................
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

if not os.access(database, os.W_OK):
    print('''ERROR: no write permission to database file at ''' + database)
    sys.exit(1)

import sqlite3
dbconn = sqlite3.connect(database)
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")





# Ask them to enter their message, then ask them to confirm.
d = Dialog(dialog="dialog", autowidgetsize=True)
d.set_background_title("Broadcast a notification to all users")

# Keep asking them to enter a message until they either enter one or cancel.
stage1error = ''
................................................................................
                           user_id,
                           cur_time,
                           '%Y-%m-%d'
                           )

    tup = (their_date + ': ' + message, user_id)
    conn.execute('''INSERT INTO Notification (name, user_id)
                 VALUES (?, ?);''', tup)

dbconn.commit()
dbconn.close()

d.infobox("Message broadcast successfully.")







|







 







|
|
|
|
>
>
>
>







 







|





51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
..
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
131
132
133
134
135
136
137
138
139
140
141
142
143
# Read the config file
conf = configparser.ConfigParser()
conf._interpolation = configparser.ExtendedInterpolation()
conf.read(config_file)

# Check config file was valid
try:
    dbname = conf['System']['dbname']
except KeyError:
    print("ERROR: Can't read config file.")
    sys.exit(1)

# Test existance and permissions of the database file
if not os.access(database, os.F_OK):
    print('''ERROR: database file does not exist at ''' + database)
................................................................................
    print('''ERROR: no read permission to database file at ''' + database)
    sys.exit(1)

if not os.access(database, os.W_OK):
    print('''ERROR: no write permission to database file at ''' + database)
    sys.exit(1)

# import sqlite3
# dbconn = sqlite3.connect(database)
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

import mysql.connector as mariadb
dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

# Ask them to enter their message, then ask them to confirm.
d = Dialog(dialog="dialog", autowidgetsize=True)
d.set_background_title("Broadcast a notification to all users")

# Keep asking them to enter a message until they either enter one or cancel.
stage1error = ''
................................................................................
                           user_id,
                           cur_time,
                           '%Y-%m-%d'
                           )

    tup = (their_date + ': ' + message, user_id)
    conn.execute('''INSERT INTO Notification (name, user_id)
                 VALUES (%s, %s);''', tup)

dbconn.commit()
dbconn.close()

d.infobox("Message broadcast successfully.")

Changes to taskenizer/functions/crypto.py.

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
..
62
63
64
65
66
67
68



69
70
71
72
73
74
75


def prepare_cryptor(conn, user_id, cryptohash, cat_type, cat_id):
    if cat_type == 4:  # biscuits
        tup = (user_id,)
        conn.execute('''SELECT biscuits_iv, biscuits_key
                     FROM User
                     WHERE id = ?;''', tup)
        ans = conn.fetchall()
    else:
        # Get the iv and key of this category
        tup = (cat_type, str(cat_id), user_id)
        conn.execute('''SELECT iv, key
                     FROM CatKey
                     WHERE task_type = ?
                     AND cat_id = ?
                     AND user_id = ?;''', tup)
        ans = conn.fetchall()

    if len(ans) == 0:
        return False
    else:
        cativ = ans[0][0]
        key = ans[0][1]
................................................................................

        return fern


def decrypt_name(xfield, fern):
    import gzip




    # Decrypt
    cfield = fern.decrypt(xfield)

    # De-compress
    # As a messy hack for old accounts that are using non-compressed data
    try:
        efield = gzip.decompress(cfield)







|




|

|
|
|







 







>
>
>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
..
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78


def prepare_cryptor(conn, user_id, cryptohash, cat_type, cat_id):
    if cat_type == 4:  # biscuits
        tup = (user_id,)
        conn.execute('''SELECT biscuits_iv, biscuits_key
                     FROM User
                     WHERE id = %s;''', tup)
        ans = conn.fetchall()
    else:
        # Get the iv and key of this category
        tup = (cat_type, str(cat_id), user_id)
        conn.execute('''SELECT iv, thekey
                     FROM CatKey
                     WHERE task_type = %s
                     AND cat_id = %s
                     AND user_id = %s;''', tup)
        ans = conn.fetchall()

    if len(ans) == 0:
        return False
    else:
        cativ = ans[0][0]
        key = ans[0][1]
................................................................................

        return fern


def decrypt_name(xfield, fern):
    import gzip

    if type(xfield) == str:
        xfield = bytes(xfield, 'utf-8')
    
    # Decrypt
    cfield = fern.decrypt(xfield)

    # De-compress
    # As a messy hack for old accounts that are using non-compressed data
    try:
        efield = gzip.decompress(cfield)

Changes to taskenizer/functions/display.py.

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
...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
...
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
...
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
...
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
...
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
                     refresh_checker, cur_time, conf, javascript_name, theme):

    this_page_id = environ['QUERY_STRING']

    tup = (user_id,)
    conn.execute('''SELECT id, name
                 FROM Page
                 WHERE user_id = ?
                 ORDER BY seq;''', tup)
    rows = conn.fetchall()

    conn.execute('''SELECT biscuits_enabled
                 FROM User
                 WHERE id = ?;''', tup)
    b_enabled = conn.fetchall()[0][0]

    conn.execute('''SELECT id, name
                 FROM Notification
                 WHERE user_id = ?
                 ORDER BY id ASC;''', tup)
    notifications = conn.fetchall()

    css_code = templates['style'].render(theme=conf[theme])

    return templates['bottom_of_header'].render(
        jscript_filename=javascript_name,
................................................................................

def footer(environ, templates, conn, user_id, conf, source_tarball_name):

    if user_id is not None:
        tup = (user_id,)
        conn.execute('''SELECT username
                     FROM User
                     WHERE id = ?;''', tup)

        username = conn.fetchone()[0]
    else:
        username = None

    priv_pol_url = default_piv_pol(conf)
    development_link = default_dev_link(conf)
................................................................................
    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # I need to find out the change number of this category
    tup = (str(cat_id),)
    conn.execute('''SELECT change_num
                 FROM NoteCat
                 WHERE id = ?;''', tup)
    ans = conn.fetchone()
    change_num = ans[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0, cat_id)

    if fern is False:
        return '<error>Category access denied</error>'
................................................................................

        # We need to decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (0, user_id,)
        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?;''', tup)
        num_note_cats = conn.fetchone()

        return templates['xml_note_category'].render(
            cat_id=cat_id,
            num_note_cats=num_note_cats,
            list_of_notes=list_of_notes,
            defcolor=conf['Cosmetic']['default_task_background_color'],
................................................................................

    # We need to decide whether to display move buttons or
    # not. There's no point of displaying them if there's
    # only one category.
    tup = (user_id,)
    conn.execute('''SELECT COUNT(*)
                 FROM NoteCat
                 WHERE user_id = ?;''', tup)
    num_note_cats = conn.fetchone()

    # Now we get the biscuits
    tup = (user_id,)
    conn.execute('''SELECT id, color, name, timestamp
                 FROM Biscuit
                 WHERE user_id = ?
                 ORDER BY id DESC;''', tup)
    rows = conn.fetchall()

    # Decrypt the names
    rows = [[elem[0], elem[1], crypto.decrypt_name(elem[2], fern), elem[
        3]] for elem in rows]

................................................................................
    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # I need to find out the change number of this category
    tup = (str(cat_id),)
    conn.execute('''SELECT change_num
                 FROM AutoHabitCat
                 WHERE id = ?;''', tup)
    ans = conn.fetchone()
    change_num = ans[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)

    if fern is False:
        return '<error>Category access denied</error>'
................................................................................

        # We decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (1, user_id,)
        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?;''', tup)
        num_cats = conn.fetchone()

        return templates['xml_auto_&_manu_habit_category'].render(
            cat_id=cat_id,
            list_of_habits=list_of_habits,
            num_cats=num_cats,
            defcolor=conf['Cosmetic']['default_task_background_color'],
................................................................................
    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # I need to find out the change number of this category
    tup = (str(cat_id),)
    conn.execute('''SELECT change_num
                 FROM ManuHabitCat
                 WHERE id = ?;''', tup)
    ans = conn.fetchone()
    change_num = ans[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)

    if fern is False:
        return '<error>Category access denied</error>'
................................................................................
        # We decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (2, user_id,)

        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?;''', tup)
        num_cats = conn.fetchone()

        return templates['xml_auto_&_manu_habit_category'].render(
            cat_id=cat_id,
            list_of_habits=list_of_habits,
            num_cats=num_cats,
            defcolor=conf['Cosmetic']['default_task_background_color'],
................................................................................
def redirect_to_first_page(conn, user_id, conf):
    # So we're going to redirect to the first page.

    # First we need to find out the id of the first page.
    tup = (user_id,)
    conn.execute('''SELECT id
                 FROM Page
                 WHERE user_id = ?
                 ORDER BY seq LIMIT 1;''', tup)
    rows = conn.fetchone()

    status = '303 See Other'
    try:
        page_id = rows[0]








|





|




|







 







|







 







|







 







|
|







 







|






|







 







|







 







|
|







 







|







 







|
|







 







|







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
...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
...
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
...
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
...
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
...
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
                     refresh_checker, cur_time, conf, javascript_name, theme):

    this_page_id = environ['QUERY_STRING']

    tup = (user_id,)
    conn.execute('''SELECT id, name
                 FROM Page
                 WHERE user_id = %s
                 ORDER BY seq;''', tup)
    rows = conn.fetchall()

    conn.execute('''SELECT biscuits_enabled
                 FROM User
                 WHERE id = %s;''', tup)
    b_enabled = conn.fetchall()[0][0]

    conn.execute('''SELECT id, name
                 FROM Notification
                 WHERE user_id = %s
                 ORDER BY id ASC;''', tup)
    notifications = conn.fetchall()

    css_code = templates['style'].render(theme=conf[theme])

    return templates['bottom_of_header'].render(
        jscript_filename=javascript_name,
................................................................................

def footer(environ, templates, conn, user_id, conf, source_tarball_name):

    if user_id is not None:
        tup = (user_id,)
        conn.execute('''SELECT username
                     FROM User
                     WHERE id = %s;''', tup)

        username = conn.fetchone()[0]
    else:
        username = None

    priv_pol_url = default_piv_pol(conf)
    development_link = default_dev_link(conf)
................................................................................
    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # I need to find out the change number of this category
    tup = (str(cat_id),)
    conn.execute('''SELECT change_num
                 FROM NoteCat
                 WHERE id = %s;''', tup)
    ans = conn.fetchone()
    change_num = ans[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0, cat_id)

    if fern is False:
        return '<error>Category access denied</error>'
................................................................................

        # We need to decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (0, user_id,)
        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s;''', tup)
        num_note_cats = conn.fetchone()

        return templates['xml_note_category'].render(
            cat_id=cat_id,
            num_note_cats=num_note_cats,
            list_of_notes=list_of_notes,
            defcolor=conf['Cosmetic']['default_task_background_color'],
................................................................................

    # We need to decide whether to display move buttons or
    # not. There's no point of displaying them if there's
    # only one category.
    tup = (user_id,)
    conn.execute('''SELECT COUNT(*)
                 FROM NoteCat
                 WHERE user_id = %s;''', tup)
    num_note_cats = conn.fetchone()

    # Now we get the biscuits
    tup = (user_id,)
    conn.execute('''SELECT id, color, name, timestamp
                 FROM Biscuit
                 WHERE user_id = %s
                 ORDER BY id DESC;''', tup)
    rows = conn.fetchall()

    # Decrypt the names
    rows = [[elem[0], elem[1], crypto.decrypt_name(elem[2], fern), elem[
        3]] for elem in rows]

................................................................................
    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # I need to find out the change number of this category
    tup = (str(cat_id),)
    conn.execute('''SELECT change_num
                 FROM AutoHabitCat
                 WHERE id = %s;''', tup)
    ans = conn.fetchone()
    change_num = ans[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)

    if fern is False:
        return '<error>Category access denied</error>'
................................................................................

        # We decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (1, user_id,)
        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s;''', tup)
        num_cats = conn.fetchone()

        return templates['xml_auto_&_manu_habit_category'].render(
            cat_id=cat_id,
            list_of_habits=list_of_habits,
            num_cats=num_cats,
            defcolor=conf['Cosmetic']['default_task_background_color'],
................................................................................
    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # I need to find out the change number of this category
    tup = (str(cat_id),)
    conn.execute('''SELECT change_num
                 FROM ManuHabitCat
                 WHERE id = %s;''', tup)
    ans = conn.fetchone()
    change_num = ans[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)

    if fern is False:
        return '<error>Category access denied</error>'
................................................................................
        # We decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (2, user_id,)

        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s;''', tup)
        num_cats = conn.fetchone()

        return templates['xml_auto_&_manu_habit_category'].render(
            cat_id=cat_id,
            list_of_habits=list_of_habits,
            num_cats=num_cats,
            defcolor=conf['Cosmetic']['default_task_background_color'],
................................................................................
def redirect_to_first_page(conn, user_id, conf):
    # So we're going to redirect to the first page.

    # First we need to find out the id of the first page.
    tup = (user_id,)
    conn.execute('''SELECT id
                 FROM Page
                 WHERE user_id = %s
                 ORDER BY seq LIMIT 1;''', tup)
    rows = conn.fetchone()

    status = '303 See Other'
    try:
        page_id = rows[0]

Changes to taskenizer/functions/operations.py.

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
...
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
...
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
...
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
...
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
...
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
...
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
...
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
...
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
...
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
...
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
...
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
...
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
...
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
....
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
....
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
....
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
....
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
....
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
....
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
....
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
....
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
....
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
....
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
....
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
....
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
....
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
....
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
....
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
....
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
....
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
....
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
....
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
....
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
....
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
....
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
....
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
        tab_name = 'ManuHabit'

    if cat_id is None:
        # Find out what category this task belongs to
        tup = (task_id,)
        conn.execute('''SELECT cat_id
                     FROM %s
                     WHERE id = ?;''' % tab_name, tup)
        cat_id = conn.fetchone()[0]

    tab_name += 'Cat'

    tup = (cat_id,)
    conn.execute('''UPDATE %s
                 SET change_num = change_num + 1
                 WHERE id = ?;''' % tab_name, tup)


def check_change_num(conn, cat_type, cat_id, num):
    """checks to see if the change number is upto date

    returns either True or False

................................................................................
        tab_name = 'AutoHabitCat'
    if cat_type == 2:
        tab_name = 'ManuHabitCat'

    tup = (cat_id,)
    conn.execute('''SELECT change_num
                 FROM %s
                 WHERE id = ?;''' % tab_name, tup)

    # If the category has been deleted since the page was last loaded this will
    # return "TypeError: 'NoneType' object is not subscriptable".
    try:
        change_num = conn.fetchone()[0]
    except TypeError:
        return False    # Kind-of a kludge. Perhaps a whole-page reload
................................................................................
                                   biscuits_key,
                                   biscuits_enabled,
                                   last_forced_reload_day,
                                   ip_address,
                                   reg_date,
                                   actheme
                                   )
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);''', tup)

    tup = (remote_ip, cur_time)

    conn.execute('''INSERT INTO AcReg (ip_address, date) VALUES (?, ?);''', tup)

    # Annoyingly, I now need to find out the id of the account I just created
    tup = (username,)

    conn.execute('''SELECT id
                 FROM User
                 WHERE username = ?;''', tup)

    user_id = conn.fetchall()[0][0]

    populate_new_account(conn, user_id, cur_time, cryptohash, conf)

    return (user_id, cryptohash)

................................................................................
    # First, the rate limit check
    hour_ago = cur_time - 3600
    reg_lim = int(conf['System']['accregnum'])

    tup = (remote_ip, hour_ago)
    conn.execute('''SELECT COUNT(*)
                 FROM AcReg
                 WHERE ip_address = ?
                 AND date > ?;''', tup)
    numregs = conn.fetchone()[0]

    if numregs >= reg_lim:
        logging.info('IP address ' + remote_ip + ' is stopped from exceeding the account registration limit of ' + str(reg_lim) + '/hour.')

        raise ValueError('Your IP address is registering accounts too fast. Please contact us about this error.')

................................................................................

    # Check there's no silly characters. This will raise ValueError is there is.
    check_username(form['username'].value)

    tup = (form['username'].value,)
    conn.execute('''SELECT COUNT(*)
                 FROM User
                 WHERE username = ?;''', tup)
    result1 = conn.fetchone()

    if result1[0] > 0:
        raise ValueError('That username is already taken.')
    if form['timezone'].value not in common_timezones:
        raise ValueError('Invalid timezone data...')  # under attack?
    if form['new_passphrase_1'].value != form['new_passphrase_2'].value:
................................................................................
        page_id,
        name,
        new_number,
        user_id
    ]

    conn.execute('''INSERT INTO Page (id, name, seq, user_id)
                 VALUES (?, ?, ?, ?)''', tup)

    return page_id


def add_cat(conn, user_id, name, cur_time, cryptohash, cat_type):
    """Adds a category to the database using supplied info. Includes
    generating an encryption key for this new category."""
................................................................................
        name,
        user_id,
        1
    )

    conn.execute('''INSERT INTO %s
                 (id, name, user_id, change_num)
                 VALUES (?, ?, ?, ?)''' % cat_type, tup)

    if cat_type == 'NoteCat':
        task_type = 0
    elif cat_type == 'AutoHabitCat':
        task_type = 1
    elif cat_type == 'ManuHabitCat':
        task_type = 2

    tup = (task_type, new_id, user_id, cat_iv, token,)
    conn.execute('''INSERT INTO CatKey
                 (task_type, cat_id, user_id, iv, key)
                 VALUES (?, ?, ?, ?, ?)''', tup)

    return new_id


def add_page_entry(conn, user_id, new_number, cur_time, page_id, entry_type,
                   entry_id):
    """Adds a category to a page."""
................................................................................
        new_number,
        user_id
    ]

    conn.execute('''INSERT INTO PageContent (id, page_id,
                                          entry_type, entry_id,
                                          seq, user_id)
                 VALUES (?, ?, ?, ?, ?, ?)''', tup)


def add_new_note(conn, user_id, cur_time, cat_id, color, name, deferred,
                 def_days, def_months, def_years, cryptohash):
    """Just encrypts and adds a note."""

    from taskenizer.functions import crypto
................................................................................
                                       color,
                                       name,
                                       deferred,
                                       def_days,
                                       def_months,
                                       def_years,
                                       user_id)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', tup)

        inc_change_num(conn, 0, cat_id, None)


def populate_new_account(conn, user_id, cur_time, cryptohash, conf):
    """Puts sample entries into a new account.

................................................................................
                                        due_years,
                                        color,
                                        deferred,
                                        def_days,
                                        def_months,
                                        def_years,
                                        user_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', to_be_inserted)

    inc_change_num(conn, 1, form["data-category"].value, None)


def add_manu_habit(form, conn, user_id, cryptohash, cur_time, opt_color):
    """Processes form data and adds a ManuHabit. It is called from:
    - add_manu_habit_page - for obvious reasons,
................................................................................
                                        due,
                                        color,
                                        deferred,
                                        def_days,
                                        def_months,
                                        def_years,
                                        user_id)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', to_be_inserted)

    inc_change_num(conn, 2, form["data-category"].value, None)


def add_deferred_note(form, conn, user_id, cryptohash, cur_time, conf):
    from taskenizer.functions import crypto

................................................................................
        form["note-next-year"].value,
        user_id
    ]

    conn.execute('''INSERT INTO Note
                 (id, cat_id, color, name, deferred,
                 def_days, def_months, def_years, user_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', to_be_inserted)

    inc_change_num(conn, 0, form["data-category"].value, None)


def defer_task(form, conn, item, user_id, fern, conf, cat_type, task_type):
    from taskenizer.functions import crypto

................................................................................
        task_id
    )

    if not check_perm_task(conn, task_id, task_type, user_id):
        return 'OMG, no permission!'

    conn.execute('''UPDATE %s
                 SET deferred = 1, def_days = ?,
                 def_months = ?, def_years = ?,
                 color = ?, name = ?
                 WHERE id = ?;''' % cat_type, tup)

    inc_change_num(conn, task_type, None, task_id)


def modify_auto_habit(form, conn, item, user_id, fern):
    '''Modifies an automatic habit using the posted data'''
    from taskenizer.functions import crypto
................................................................................
            form["habit-next-day_" + itnum].value,
            form["habit-next-month_" + itnum].value,
            form["habit-next-year_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE AutoHabit
                     SET name = ?, freq = ?, freq_units = ?,
                     due_days = ?, due_months = ?,
                     due_years = ?
                     WHERE id = ?;''', tup)

        inc_change_num(conn, 1, None, task_id)

    if operation == 'modify_defer_page':
        if task_id == '':
            raise ValueError("ID missing :S.")  # bot attack?
        if form["task-name_" + itnum].value == '':
................................................................................
            nom,
            form["task-next-day_" + itnum].value,
            form["task-next-month_" + itnum].value,
            form["task-next-year_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE AutoHabit Set name = ?,
                        def_days = ?,
                        def_months = ?,
                        def_years = ?
                        WHERE id = ?;''', tup)

        inc_change_num(conn, 1, form["data-category"].value, None)


def modify_manu_habit(form, conn, item, user_id, fern):
    '''Modifies a manual habit using the posted data'''
    from taskenizer.functions import crypto
................................................................................
            crypt_name,
            form["frequency_" + itnum].value,
            form["habit-next-advance_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE ManuHabit
                     SET name = ?, freq = ?, due = ?
                     WHERE id = ?;''', tup)

        inc_change_num(conn, 2, None, task_id)

    if operation == 'modify_defer_page':
        if task_id == '':
            raise ValueError("ID missing :S.")  # bot attack?
        if form["task-name_" + itnum].value == '':
................................................................................
            nom,
            form["task-next-day_" + itnum].value,
            form["task-next-month_" + itnum].value,
            form["task-next-year_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE ManuHabit Set name = ?,
                        def_days = ?,
                        def_months = ?,
                        def_years = ?
                        WHERE id = ?;''', tup)

        inc_change_num(conn, 2, form["data-category"].value, None)


def done_auto_habit(conn, task_id, cur_time, user_id, conf):
    '''Updates selected habit with new `due_*' values.'''
    import datetime
................................................................................
    if not check_perm_task(conn, task_id, 1, user_id):
        return 'OMG, no permission!'

    # We need to find out how often this habit is done
    tup = (task_id,)
    conn.execute('''SELECT freq, freq_units
                 FROM AutoHabit
                 WHERE id = ?;''', tup)
    row = conn.fetchone()

    frequency = row[0]
    freq_units = row[1]

    # Find out the frequency with which it's supposed to be done and
    # add that much time to today's date.
................................................................................
        new_months,
        new_years,
        color,
        task_id
    )

    conn.execute('''UPDATE AutoHabit
                 SET due_days = ?,
                 due_months = ?,
                 due_years = ?,
                 color = ?
                 WHERE id = ?;''', tup)

    inc_change_num(conn, 1, None, task_id)


def done_manu_habit(conn, task_id, user_id, conf):
    '''Updates selected habit with a new `due' value.'''

................................................................................
    # First we check if we actually have permission.
    if not check_perm_task(conn, task_id, 2, user_id):
        return 'OMG, no permission!'

    tup = (task_id,)
    conn.execute('''SELECT freq
                 FROM ManuHabit
                 WHERE id = ?;''', tup)
    row = conn.fetchone()

    frequency = row[0]

    # If it's highlighted it will be set back to the default color.
    color = conf['Cosmetic']['default_task_background_color']

................................................................................
    tup = (
        frequency,
        color,
        task_id
    )

    conn.execute('''UPDATE ManuHabit
                 SET due = ?,
                 color = ?
                 WHERE id = ?;''', tup)

    inc_change_num(conn, 2, None, task_id)


def advance_manu_habits(conn, category_id, user_id, cur_time):
    '''Decrements the due value of every manual habit
    in that category'''
................................................................................
    if not check_perm_cat(conn, category_id, 2, user_id):
        return 'OMG, no permission!'

    tup = (category_id,)

    conn.execute('''UPDATE ManuHabit
                 SET due = due - 1
                 WHERE cat_id = ?;''', tup)

    # We need to find out the current time in their timezone so we can
    # remember when they last advanced.
    adv_time = find_time(conn,
                         user_id,
                         cur_time,
                         '%a %Y-%m-%d %H:%M:%S %Z%z'
................................................................................

    tup = (
        last_advanced,
        category_id
    )

    conn.execute('''UPDATE ManuHabitCat
                 SET last_advanced = ?
                 WHERE id = ?;''', tup)

    inc_change_num(conn, 2, category_id, None)


def unvance_manu_habits(conn, category_id, user_id):
    '''Increments the due value of every manual habit
    in that category, no higher than their frequency value.'''
................................................................................
    if not check_perm_cat(conn, category_id, 2, user_id):
        return 'OMG, no permission!'

    tup = (category_id,)

    conn.execute('''UPDATE ManuHabit
                 SET due = due + 1
                 WHERE cat_id = ?
                 AND due < freq''', tup)

    # The last_advanced db entry will blanked.
    last_advanced = ''

    tup = (
        last_advanced,
        category_id
    )

    conn.execute('''UPDATE ManuHabitCat
                 SET last_advanced = ?
                 WHERE id = ?;''', tup)

    inc_change_num(conn, 2, category_id, None)


def check_perm_task(conn, task_id, task_type, user_id):
    if task_type == 0:
        str_type = 'Note'
................................................................................
        str_type = 'AutoHabit'
    if task_type == 2:
        str_type = 'ManuHabit'

    tup = (task_id,)
    conn.execute('''SELECT cat_id
                 FROM %s
                 WHERE id = ?;''' % str_type, tup)
    try:
        cat_id = conn.fetchone()[0]
    except TypeError:
        return 'denied'

    tup = (cat_id, task_type, user_id)
    conn.execute('''SELECT COUNT(*)
                 FROM CatKey
                 WHERE cat_id = ?
                 AND task_type = ?
                 AND user_id = ?;''', tup)

    if conn.fetchone()[0] > 0:
        return True
    else:
        return False


def check_perm_cat(conn, cat_id, cat_type, user_id):
    tup = (cat_id, cat_type, user_id)
    conn.execute('''SELECT COUNT(*)
                 FROM CatKey
                 WHERE cat_id = ?
                 AND task_type = ?
                 AND user_id = ?;''', tup)

    if conn.fetchone()[0] > 0:
        return True
    else:
        return False


................................................................................
    if task_type == 2:
        cat_type = 'ManuHabit'

    # Get all deferred tasks in this category
    conn.execute('''SELECT id, def_days, def_months,
                 def_years
                 FROM %s
                 WHERE cat_id = ?
                 AND user_id = ?
                 AND deferred = 1;''' % cat_type, tup)
    def_tasks = conn.fetchall()

    for task in def_tasks:
        tasid = task[0]
        days = task[1]
        months = task[2]
................................................................................
        # If that's before now, un-defer it
        if time_due <= cur_time:
            tup = (tasid, user_id)

            # Note that it doesn't clear the `next_days',
            # `next_months' etc values.
            conn.execute('''UPDATE %s SET deferred = 0
                         WHERE id = ?
                         AND user_id = ?''' % cat_type, tup)


def cookie_auth(cook):
    """Checks for three auth cookies. If all of them are present, returns them.

    The first element of the tuple is always 0 for all cookies found or 1 otherwize.
    """
................................................................................


def record_login_failure(conn, remote_ip, cur_time):
    """Dumps an IP address and a date into the LoginFail table."""

    tup = (remote_ip, cur_time)
    conn.execute('''INSERT INTO LoginFail (ip_address, date)
                 VALUES (?, ?);''', tup)


def check_credentials(conn, cook, form, cur_time, conf, remote_ip, logging):
    # If it's a success it returns the user_id. If they authenticated
    # by post it responds such. If neither error.

    # return arg 1, exit status: 0=success, 1=error, 2=log_out, 3=no_credentials_provided
................................................................................
        # The first thing we do here is to check that the rate limit has not been exceeded
        hour_ago = cur_time - 3600
        fail_lim = int(conf['System']['loginfailnum'])

        tup = (remote_ip, hour_ago)
        conn.execute('''SELECT COUNT(*)
                     FROM LoginFail
                     WHERE ip_address = ?
                     AND date > ?;''', tup)
        numfails = conn.fetchone()[0]

        if numfails >= fail_lim:
            logging.info('IP address ' + remote_ip + ' is stopped from exceeding the login attempt limit of ' + str(fail_lim) + '/hour.')

            return (1, "Your IP address is failing a lot of passphrase attempts and has been rate-limited.",)

        tup = (postman[1],)
        conn.execute('''SELECT id, passhash, salt, migstat
                     FROM User
                     WHERE username = ?;''', tup)
        try:
            ans = conn.fetchone()
            user_id = ans[0]
            correcthash = ans[1]
            salt = base64.b64decode(ans[2].encode('ASCII'))
            migstat = ans[3]
        except Exception:
................................................................................
            user_id,
            session_id,
            cur_time
        )

        conn.execute('''SELECT COUNT(*)
                     FROM Session
                     WHERE user_id = ?
                     AND id = ?
                     AND expires > ?;''', tup)
        result = conn.fetchone()

        if result[0] > 0:  # If the session exists
            # Now let's see if they wanna log out
            try:
                action = form['action'].value
            except KeyError:
................................................................................
                # logging out until they've successfully authenticated
                # first.
                tup = (
                    user_id,
                    session_id
                )
                conn.execute('''DELETE FROM Session
                             WHERE user_id = ?
                             AND id = ?;''', tup)

                return (2, conf['Cosmetic']['successfully_logged_out'],)

            return (0, None, 'cookies', user_id, session_id, cryptohash)
        else:
            return (1, conf['Cosmetic']['not_logged_in_message'],)

................................................................................
    utc = pytz.utc
    utc_dt = utc.localize(datetime.datetime.utcfromtimestamp(cur_time))

    # We need to find out their timezone.
    tup = (user_id,)
    conn.execute('''SELECT tz
                 FROM User
                 WHERE id = ?;''', tup)

    tzo = conn.fetchone()[0]
    au_tz = pytz.timezone(tzo)
    au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))

    return au_dt.strftime(fmt)

................................................................................
    """Retrieves all notes from this category and decrypts."""
    from taskenizer.functions import crypto

    # Get the notes
    tup = (cat_id,)
    conn.execute('''SELECT id, color, name
                 FROM Note
                 WHERE cat_id = ?
                 AND deferred = 0
                 ORDER BY id ASC;''', tup)
    rows = conn.fetchall()

    # Decrypt the names
    list_of_notes = [[elem[0], elem[1], crypto.decrypt_name(elem[2], fern)] for elem in rows]

    return list_of_notes


def gen_note_future_list(conn, cat_id, fern, cur_time, user_id, foo_timezone, dayso):
    '''Generates a list of notes due in $days future and decrypts.

................................................................................

    tup = (cat_id, user_id,)

    # Get all deferred tasks in this category
    conn.execute('''SELECT id, def_days, def_months,
                 def_years, color, name
                 FROM Note
                 WHERE cat_id = ?
                 AND user_id = ?
                 AND deferred = 1;''', tup)
    def_tasks = conn.fetchall()

    list_of_notes = []

    for task in def_tasks:
        tasid = task[0]
................................................................................
    import datetime

    tup = (cat_id,)
    conn.execute('''SELECT id, color, name, freq,
                 freq_units, due_days,
                 due_months, due_years
                 FROM AutoHabit
                 WHERE cat_id = ?
                 AND deferred = 0
                 ORDER BY id ASC;''', tup)
    rows = conn.fetchall()

    list_of_habits = []

    for row in rows:
................................................................................

            # Calculate an order sorting number
            sort = freq_in_days - (overdue_rounded / 86400)

            # Calculate a color sorting number
            color_sort = overdue_rounded / freq_in_seconds

            decrypted_name = crypto.decrypt_name(name, fern)

            # Make a html color
            warning = calc_warning(color_sort)

            stats = auto_stats(
                overdue, freq, freq_units)

................................................................................

    from taskenizer.functions import crypto
    from operator import itemgetter

    tup = (cat_id,)
    conn.execute('''SELECT id, color, name, freq, due
                 FROM ManuHabit
                 WHERE cat_id = ?
                 AND deferred = 0
                 ORDER BY id ASC;''', tup)
    rows = conn.fetchall()

    list_of_habits = []

    for row in rows:
................................................................................
    """Just gets the user's timezone settings out of the database"""

    import pytz

    tup = (user_id,)
    conn.execute('''SELECT tz
                 FROM User
                 WHERE id = ?;''', tup)

    tzo = conn.fetchone()[0]
    timezone = pytz.timezone(tzo)

    return timezone

def gen_date_list(cur_time, timezone):
................................................................................

def delete_account(conn, user_id):
    """Deletes alll trace of the account from the database."""

    tup = (user_id,)

    conn.execute('''DELETE FROM Notification
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM Note
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM AutoHabit
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM ManuHabit
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM Biscuit
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM NoteCat
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM AutoHabitCat
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM ManuHabitCat
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM CatKey
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM PageContent
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM Page
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM Session
                    WHERE user_id = ?''', tup)
    conn.execute('''DELETE FROM User
                    WHERE id = ?''', tup)







|







|







 







|







 







|



|






|







 







|
|







 







|







 







|







 







|










|
|







 







|







 







|







 







|







 







|







 







|







 







|
|
|
|







 







|
|
|
|







 







|
|
|
|
|







 







|
|







 







|
|
|
|
|







 







|







 







|
|
|
|
|







 







|







 







|
|
|







 







|







 







|
|







 







|











|
|







 







|








|
|
|











|
|
|







 







|
|







 







|
|







 







|







 







|
|










|







 







|
|
|







 







|
|







 







|







 







|





|







 







|
|







 







|







 







|







 







|







 







|







 







|

|

|

|

|

|

|

|

|

|

|

|

|
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
...
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
...
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
...
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
...
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
...
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
...
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
...
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
...
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
...
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
...
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
...
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
...
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
...
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
....
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
....
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
....
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
....
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
....
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
....
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
....
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
....
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
....
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
....
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
....
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
....
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
....
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
....
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
....
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
....
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
....
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
....
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
....
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
....
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
....
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
....
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
....
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
        tab_name = 'ManuHabit'

    if cat_id is None:
        # Find out what category this task belongs to
        tup = (task_id,)
        conn.execute('''SELECT cat_id
                     FROM %s
                     WHERE id = %%s;''' % tab_name, tup)
        cat_id = conn.fetchone()[0]

    tab_name += 'Cat'

    tup = (cat_id,)
    conn.execute('''UPDATE %s
                 SET change_num = change_num + 1
                 WHERE id = %%s;''' % tab_name, tup)


def check_change_num(conn, cat_type, cat_id, num):
    """checks to see if the change number is upto date

    returns either True or False

................................................................................
        tab_name = 'AutoHabitCat'
    if cat_type == 2:
        tab_name = 'ManuHabitCat'

    tup = (cat_id,)
    conn.execute('''SELECT change_num
                 FROM %s
                 WHERE id = %%s;''' % tab_name, tup)

    # If the category has been deleted since the page was last loaded this will
    # return "TypeError: 'NoneType' object is not subscriptable".
    try:
        change_num = conn.fetchone()[0]
    except TypeError:
        return False    # Kind-of a kludge. Perhaps a whole-page reload
................................................................................
                                   biscuits_key,
                                   biscuits_enabled,
                                   last_forced_reload_day,
                                   ip_address,
                                   reg_date,
                                   actheme
                                   )
                 VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);''', tup)

    tup = (remote_ip, cur_time)

    conn.execute('''INSERT INTO AcReg (ip_address, date) VALUES (%s, %s);''', tup)

    # Annoyingly, I now need to find out the id of the account I just created
    tup = (username,)

    conn.execute('''SELECT id
                 FROM User
                 WHERE username = %s;''', tup)

    user_id = conn.fetchall()[0][0]

    populate_new_account(conn, user_id, cur_time, cryptohash, conf)

    return (user_id, cryptohash)

................................................................................
    # First, the rate limit check
    hour_ago = cur_time - 3600
    reg_lim = int(conf['System']['accregnum'])

    tup = (remote_ip, hour_ago)
    conn.execute('''SELECT COUNT(*)
                 FROM AcReg
                 WHERE ip_address = %s
                 AND date > %s;''', tup)
    numregs = conn.fetchone()[0]

    if numregs >= reg_lim:
        logging.info('IP address ' + remote_ip + ' is stopped from exceeding the account registration limit of ' + str(reg_lim) + '/hour.')

        raise ValueError('Your IP address is registering accounts too fast. Please contact us about this error.')

................................................................................

    # Check there's no silly characters. This will raise ValueError is there is.
    check_username(form['username'].value)

    tup = (form['username'].value,)
    conn.execute('''SELECT COUNT(*)
                 FROM User
                 WHERE username = %s;''', tup)
    result1 = conn.fetchone()

    if result1[0] > 0:
        raise ValueError('That username is already taken.')
    if form['timezone'].value not in common_timezones:
        raise ValueError('Invalid timezone data...')  # under attack?
    if form['new_passphrase_1'].value != form['new_passphrase_2'].value:
................................................................................
        page_id,
        name,
        new_number,
        user_id
    ]

    conn.execute('''INSERT INTO Page (id, name, seq, user_id)
                 VALUES (%s, %s, %s, %s)''', tup)

    return page_id


def add_cat(conn, user_id, name, cur_time, cryptohash, cat_type):
    """Adds a category to the database using supplied info. Includes
    generating an encryption key for this new category."""
................................................................................
        name,
        user_id,
        1
    )

    conn.execute('''INSERT INTO %s
                 (id, name, user_id, change_num)
                 VALUES (%%s, %%s, %%s, %%s)''' % cat_type, tup)

    if cat_type == 'NoteCat':
        task_type = 0
    elif cat_type == 'AutoHabitCat':
        task_type = 1
    elif cat_type == 'ManuHabitCat':
        task_type = 2

    tup = (task_type, new_id, user_id, cat_iv, token,)
    conn.execute('''INSERT INTO CatKey
                 (task_type, cat_id, user_id, iv, thekey)
                 VALUES (%s, %s, %s, %s, %s)''', tup)

    return new_id


def add_page_entry(conn, user_id, new_number, cur_time, page_id, entry_type,
                   entry_id):
    """Adds a category to a page."""
................................................................................
        new_number,
        user_id
    ]

    conn.execute('''INSERT INTO PageContent (id, page_id,
                                          entry_type, entry_id,
                                          seq, user_id)
                 VALUES (%s, %s, %s, %s, %s, %s)''', tup)


def add_new_note(conn, user_id, cur_time, cat_id, color, name, deferred,
                 def_days, def_months, def_years, cryptohash):
    """Just encrypts and adds a note."""

    from taskenizer.functions import crypto
................................................................................
                                       color,
                                       name,
                                       deferred,
                                       def_days,
                                       def_months,
                                       def_years,
                                       user_id)
                     VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)''', tup)

        inc_change_num(conn, 0, cat_id, None)


def populate_new_account(conn, user_id, cur_time, cryptohash, conf):
    """Puts sample entries into a new account.

................................................................................
                                        due_years,
                                        color,
                                        deferred,
                                        def_days,
                                        def_months,
                                        def_years,
                                        user_id)
                 VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''', to_be_inserted)

    inc_change_num(conn, 1, form["data-category"].value, None)


def add_manu_habit(form, conn, user_id, cryptohash, cur_time, opt_color):
    """Processes form data and adds a ManuHabit. It is called from:
    - add_manu_habit_page - for obvious reasons,
................................................................................
                                        due,
                                        color,
                                        deferred,
                                        def_days,
                                        def_months,
                                        def_years,
                                        user_id)
              VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''', to_be_inserted)

    inc_change_num(conn, 2, form["data-category"].value, None)


def add_deferred_note(form, conn, user_id, cryptohash, cur_time, conf):
    from taskenizer.functions import crypto

................................................................................
        form["note-next-year"].value,
        user_id
    ]

    conn.execute('''INSERT INTO Note
                 (id, cat_id, color, name, deferred,
                 def_days, def_months, def_years, user_id)
                 VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)''', to_be_inserted)

    inc_change_num(conn, 0, form["data-category"].value, None)


def defer_task(form, conn, item, user_id, fern, conf, cat_type, task_type):
    from taskenizer.functions import crypto

................................................................................
        task_id
    )

    if not check_perm_task(conn, task_id, task_type, user_id):
        return 'OMG, no permission!'

    conn.execute('''UPDATE %s
                 SET deferred = 1, def_days = %%s,
                 def_months = %%s, def_years = %%s,
                 color = %%s, name = %%s
                 WHERE id = %%s;''' % cat_type, tup)

    inc_change_num(conn, task_type, None, task_id)


def modify_auto_habit(form, conn, item, user_id, fern):
    '''Modifies an automatic habit using the posted data'''
    from taskenizer.functions import crypto
................................................................................
            form["habit-next-day_" + itnum].value,
            form["habit-next-month_" + itnum].value,
            form["habit-next-year_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE AutoHabit
                     SET name = %s, freq = %s, freq_units = %s,
                     due_days = %s, due_months = %s,
                     due_years = %s
                     WHERE id = %s;''', tup)

        inc_change_num(conn, 1, None, task_id)

    if operation == 'modify_defer_page':
        if task_id == '':
            raise ValueError("ID missing :S.")  # bot attack?
        if form["task-name_" + itnum].value == '':
................................................................................
            nom,
            form["task-next-day_" + itnum].value,
            form["task-next-month_" + itnum].value,
            form["task-next-year_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE AutoHabit Set name = %s,
                        def_days = %s,
                        def_months = %s,
                        def_years = %s
                        WHERE id = %s;''', tup)

        inc_change_num(conn, 1, form["data-category"].value, None)


def modify_manu_habit(form, conn, item, user_id, fern):
    '''Modifies a manual habit using the posted data'''
    from taskenizer.functions import crypto
................................................................................
            crypt_name,
            form["frequency_" + itnum].value,
            form["habit-next-advance_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE ManuHabit
                     SET name = %s, freq = %s, due = %s
                     WHERE id = %s;''', tup)

        inc_change_num(conn, 2, None, task_id)

    if operation == 'modify_defer_page':
        if task_id == '':
            raise ValueError("ID missing :S.")  # bot attack?
        if form["task-name_" + itnum].value == '':
................................................................................
            nom,
            form["task-next-day_" + itnum].value,
            form["task-next-month_" + itnum].value,
            form["task-next-year_" + itnum].value,
            task_id
        )

        conn.execute('''UPDATE ManuHabit Set name = %s,
                        def_days = %s,
                        def_months = %s,
                        def_years = %s
                        WHERE id = %s;''', tup)

        inc_change_num(conn, 2, form["data-category"].value, None)


def done_auto_habit(conn, task_id, cur_time, user_id, conf):
    '''Updates selected habit with new `due_*' values.'''
    import datetime
................................................................................
    if not check_perm_task(conn, task_id, 1, user_id):
        return 'OMG, no permission!'

    # We need to find out how often this habit is done
    tup = (task_id,)
    conn.execute('''SELECT freq, freq_units
                 FROM AutoHabit
                 WHERE id = %s;''', tup)
    row = conn.fetchone()

    frequency = row[0]
    freq_units = row[1]

    # Find out the frequency with which it's supposed to be done and
    # add that much time to today's date.
................................................................................
        new_months,
        new_years,
        color,
        task_id
    )

    conn.execute('''UPDATE AutoHabit
                 SET due_days = %s,
                 due_months = %s,
                 due_years = %s,
                 color = %s
                 WHERE id = %s;''', tup)

    inc_change_num(conn, 1, None, task_id)


def done_manu_habit(conn, task_id, user_id, conf):
    '''Updates selected habit with a new `due' value.'''

................................................................................
    # First we check if we actually have permission.
    if not check_perm_task(conn, task_id, 2, user_id):
        return 'OMG, no permission!'

    tup = (task_id,)
    conn.execute('''SELECT freq
                 FROM ManuHabit
                 WHERE id = %s;''', tup)
    row = conn.fetchone()

    frequency = row[0]

    # If it's highlighted it will be set back to the default color.
    color = conf['Cosmetic']['default_task_background_color']

................................................................................
    tup = (
        frequency,
        color,
        task_id
    )

    conn.execute('''UPDATE ManuHabit
                 SET due = %s,
                 color = %s
                 WHERE id = %s;''', tup)

    inc_change_num(conn, 2, None, task_id)


def advance_manu_habits(conn, category_id, user_id, cur_time):
    '''Decrements the due value of every manual habit
    in that category'''
................................................................................
    if not check_perm_cat(conn, category_id, 2, user_id):
        return 'OMG, no permission!'

    tup = (category_id,)

    conn.execute('''UPDATE ManuHabit
                 SET due = due - 1
                 WHERE cat_id = %s;''', tup)

    # We need to find out the current time in their timezone so we can
    # remember when they last advanced.
    adv_time = find_time(conn,
                         user_id,
                         cur_time,
                         '%a %Y-%m-%d %H:%M:%S %Z%z'
................................................................................

    tup = (
        last_advanced,
        category_id
    )

    conn.execute('''UPDATE ManuHabitCat
                 SET last_advanced = %s
                 WHERE id = %s;''', tup)

    inc_change_num(conn, 2, category_id, None)


def unvance_manu_habits(conn, category_id, user_id):
    '''Increments the due value of every manual habit
    in that category, no higher than their frequency value.'''
................................................................................
    if not check_perm_cat(conn, category_id, 2, user_id):
        return 'OMG, no permission!'

    tup = (category_id,)

    conn.execute('''UPDATE ManuHabit
                 SET due = due + 1
                 WHERE cat_id = %s
                 AND due < freq''', tup)

    # The last_advanced db entry will blanked.
    last_advanced = ''

    tup = (
        last_advanced,
        category_id
    )

    conn.execute('''UPDATE ManuHabitCat
                 SET last_advanced = %s
                 WHERE id = %s;''', tup)

    inc_change_num(conn, 2, category_id, None)


def check_perm_task(conn, task_id, task_type, user_id):
    if task_type == 0:
        str_type = 'Note'
................................................................................
        str_type = 'AutoHabit'
    if task_type == 2:
        str_type = 'ManuHabit'

    tup = (task_id,)
    conn.execute('''SELECT cat_id
                 FROM %s
                 WHERE id = %%s;''' % str_type, tup)
    try:
        cat_id = conn.fetchone()[0]
    except TypeError:
        return 'denied'

    tup = (cat_id, task_type, user_id)
    conn.execute('''SELECT COUNT(*)
                 FROM CatKey
                 WHERE cat_id = %s
                 AND task_type = %s
                 AND user_id = %s;''', tup)

    if conn.fetchone()[0] > 0:
        return True
    else:
        return False


def check_perm_cat(conn, cat_id, cat_type, user_id):
    tup = (cat_id, cat_type, user_id)
    conn.execute('''SELECT COUNT(*)
                 FROM CatKey
                 WHERE cat_id = %s
                 AND task_type = %s
                 AND user_id = %s;''', tup)

    if conn.fetchone()[0] > 0:
        return True
    else:
        return False


................................................................................
    if task_type == 2:
        cat_type = 'ManuHabit'

    # Get all deferred tasks in this category
    conn.execute('''SELECT id, def_days, def_months,
                 def_years
                 FROM %s
                 WHERE cat_id = %%s
                 AND user_id = %%s
                 AND deferred = 1;''' % cat_type, tup)
    def_tasks = conn.fetchall()

    for task in def_tasks:
        tasid = task[0]
        days = task[1]
        months = task[2]
................................................................................
        # If that's before now, un-defer it
        if time_due <= cur_time:
            tup = (tasid, user_id)

            # Note that it doesn't clear the `next_days',
            # `next_months' etc values.
            conn.execute('''UPDATE %s SET deferred = 0
                         WHERE id = %%s
                         AND user_id = %%s''' % cat_type, tup)


def cookie_auth(cook):
    """Checks for three auth cookies. If all of them are present, returns them.

    The first element of the tuple is always 0 for all cookies found or 1 otherwize.
    """
................................................................................


def record_login_failure(conn, remote_ip, cur_time):
    """Dumps an IP address and a date into the LoginFail table."""

    tup = (remote_ip, cur_time)
    conn.execute('''INSERT INTO LoginFail (ip_address, date)
                 VALUES (%s, %s);''', tup)


def check_credentials(conn, cook, form, cur_time, conf, remote_ip, logging):
    # If it's a success it returns the user_id. If they authenticated
    # by post it responds such. If neither error.

    # return arg 1, exit status: 0=success, 1=error, 2=log_out, 3=no_credentials_provided
................................................................................
        # The first thing we do here is to check that the rate limit has not been exceeded
        hour_ago = cur_time - 3600
        fail_lim = int(conf['System']['loginfailnum'])

        tup = (remote_ip, hour_ago)
        conn.execute('''SELECT COUNT(*)
                     FROM LoginFail
                     WHERE ip_address = %s
                     AND date > %s;''', tup)
        numfails = conn.fetchone()[0]

        if numfails >= fail_lim:
            logging.info('IP address ' + remote_ip + ' is stopped from exceeding the login attempt limit of ' + str(fail_lim) + '/hour.')

            return (1, "Your IP address is failing a lot of passphrase attempts and has been rate-limited.",)

        tup = (postman[1],)
        conn.execute('''SELECT id, passhash, salt, migstat
                     FROM User
                     WHERE username = %s;''', tup)
        try:
            ans = conn.fetchone()
            user_id = ans[0]
            correcthash = ans[1]
            salt = base64.b64decode(ans[2].encode('ASCII'))
            migstat = ans[3]
        except Exception:
................................................................................
            user_id,
            session_id,
            cur_time
        )

        conn.execute('''SELECT COUNT(*)
                     FROM Session
                     WHERE user_id = %s
                     AND id = %s
                     AND expires > %s;''', tup)
        result = conn.fetchone()

        if result[0] > 0:  # If the session exists
            # Now let's see if they wanna log out
            try:
                action = form['action'].value
            except KeyError:
................................................................................
                # logging out until they've successfully authenticated
                # first.
                tup = (
                    user_id,
                    session_id
                )
                conn.execute('''DELETE FROM Session
                             WHERE user_id = %s
                             AND id = %s;''', tup)

                return (2, conf['Cosmetic']['successfully_logged_out'],)

            return (0, None, 'cookies', user_id, session_id, cryptohash)
        else:
            return (1, conf['Cosmetic']['not_logged_in_message'],)

................................................................................
    utc = pytz.utc
    utc_dt = utc.localize(datetime.datetime.utcfromtimestamp(cur_time))

    # We need to find out their timezone.
    tup = (user_id,)
    conn.execute('''SELECT tz
                 FROM User
                 WHERE id = %s;''', tup)

    tzo = conn.fetchone()[0]
    au_tz = pytz.timezone(tzo)
    au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))

    return au_dt.strftime(fmt)

................................................................................
    """Retrieves all notes from this category and decrypts."""
    from taskenizer.functions import crypto

    # Get the notes
    tup = (cat_id,)
    conn.execute('''SELECT id, color, name
                 FROM Note
                 WHERE cat_id = %s
                 AND deferred = 0
                 ORDER BY id ASC;''', tup)
    rows = conn.fetchall()

    # Decrypt the names
    list_of_notes = [[elem[0], elem[1], crypto.decrypt_name(bytes(elem[2], 'utf-8'), fern)] for elem in rows]

    return list_of_notes


def gen_note_future_list(conn, cat_id, fern, cur_time, user_id, foo_timezone, dayso):
    '''Generates a list of notes due in $days future and decrypts.

................................................................................

    tup = (cat_id, user_id,)

    # Get all deferred tasks in this category
    conn.execute('''SELECT id, def_days, def_months,
                 def_years, color, name
                 FROM Note
                 WHERE cat_id = %s
                 AND user_id = %s
                 AND deferred = 1;''', tup)
    def_tasks = conn.fetchall()

    list_of_notes = []

    for task in def_tasks:
        tasid = task[0]
................................................................................
    import datetime

    tup = (cat_id,)
    conn.execute('''SELECT id, color, name, freq,
                 freq_units, due_days,
                 due_months, due_years
                 FROM AutoHabit
                 WHERE cat_id = %s
                 AND deferred = 0
                 ORDER BY id ASC;''', tup)
    rows = conn.fetchall()

    list_of_habits = []

    for row in rows:
................................................................................

            # Calculate an order sorting number
            sort = freq_in_days - (overdue_rounded / 86400)

            # Calculate a color sorting number
            color_sort = overdue_rounded / freq_in_seconds

            decrypted_name = crypto.decrypt_name(bytes(name, 'utf-8'), fern)

            # Make a html color
            warning = calc_warning(color_sort)

            stats = auto_stats(
                overdue, freq, freq_units)

................................................................................

    from taskenizer.functions import crypto
    from operator import itemgetter

    tup = (cat_id,)
    conn.execute('''SELECT id, color, name, freq, due
                 FROM ManuHabit
                 WHERE cat_id = %s
                 AND deferred = 0
                 ORDER BY id ASC;''', tup)
    rows = conn.fetchall()

    list_of_habits = []

    for row in rows:
................................................................................
    """Just gets the user's timezone settings out of the database"""

    import pytz

    tup = (user_id,)
    conn.execute('''SELECT tz
                 FROM User
                 WHERE id = %s;''', tup)

    tzo = conn.fetchone()[0]
    timezone = pytz.timezone(tzo)

    return timezone

def gen_date_list(cur_time, timezone):
................................................................................

def delete_account(conn, user_id):
    """Deletes alll trace of the account from the database."""

    tup = (user_id,)

    conn.execute('''DELETE FROM Notification
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM Note
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM AutoHabit
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM ManuHabit
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM Biscuit
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM NoteCat
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM AutoHabitCat
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM ManuHabitCat
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM CatKey
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM PageContent
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM Page
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM Session
                    WHERE user_id = %s''', tup)
    conn.execute('''DELETE FROM User
                    WHERE id = %s''', tup)

Changes to taskenizer/functions/process_data.py.

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
...
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
...
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
...
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
...
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
...
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
...
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
...
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
...
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
...
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
...
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
...
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
...
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
...
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
...
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
...
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
...
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
...
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
...
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
....
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
....
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
....
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
....
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
....
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
....
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
....
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
....
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
....
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
....
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
....
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
....
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
....
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
....
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
....
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
....
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
....
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
....
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
....
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
....
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
....
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 0, user_id):
                        tup = (task_id,)
                        conn.execute('''DELETE FROM Note
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'add new' or form["action"].value == 'add-bop':
            # AJAX
            color = 'default'

................................................................................

                    if check_perm_task(conn, task_id, 0, user_id):
                        # Highlight blue.
                        color = 'blue'

                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'highlight-red':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 0, user_id):
                        # Highlight red.
                        color = 'red'

                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'highlight-green':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 0, user_id):
                        # Highlight green.
                        color = 'green'

                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'highlight-none':
            # AJAX
            color = conf['Cosmetic']['default_task_background_color']

................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 0, user_id):
                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'move':
            # Mini page

            # If this function returns something, that means it
................................................................................
                                nom,
                                form["task-next-day_" + itnum].value,
                                form["task-next-month_" + itnum].value,
                                form["task-next-year_" + itnum].value,
                                task_id
                            )

                            conn.execute('''UPDATE Note Set name = ?,
                                         def_days = ?,
                                         def_months = ?,
                                         def_years = ?
                                         WHERE id = ?;''', tup)
                        except ValueError as error:
                            print('error: ' + error.args[0])

                inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'defer':
            # Mini page
................................................................................

                            if check_perm_task(conn, task_id, 0, user_id):
                                # Defer set ammount
                                color = conf['Cosmetic']['default_defered_task_background_color']

                                tup = (deferday, defermonth, deferyear, color, task_id)
                                conn.execute('''UPDATE Note
                                             SET deferred = 1, def_days = ?,
                                             def_months = ?, def_years = ?,
                                             color = ?
                                             WHERE id = ?;''', tup)

                                inc_change_num(conn, 0, None, task_id)

                elif ajaxdefer.group(1) == 'add deferred':
                    # This is not a mini page. This is an AJAX call.

                    # Let's get the date it's being deferred to.
................................................................................
                            deferyear,
                            user_id
                        ]

                        conn.execute('''INSERT INTO Note
                                     (id, cat_id, color, name, deferred,
                                     def_days, def_months, def_years, user_id)
                                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''', to_be_inserted)

                        inc_change_num(conn, 0, form["data-category"].value, None)


    elif form["task-type"].value == 'auto_habit':
        cat_id = form["data-category"].value

................................................................................

                    if check_perm_task(conn, task_id, 1, user_id):
                        # Highlight blue.
                        color = 'blue'

                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'highlight-red':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 1, user_id):
                        # Highlight red.
                        color = 'red'

                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'highlight-green':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 1, user_id):
                        # Highlight green.
                        color = 'green'

                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'highlight-none':
            # AJAX
            color = conf['Cosmetic']['default_task_background_color']

................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 1, user_id):
                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'save all':
            # Normal form submit

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)
................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 1, user_id):
                        tup = (task_id,)
                        conn.execute('''DELETE FROM AutoHabit
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'defer':
            # Mini page

            # If this function returns something, that means it
................................................................................

                        if check_perm_task(conn, task_id, 1, user_id):
                            # Defer set ammount
                            color = conf['Cosmetic']['default_defered_task_background_color']

                            tup = (deferday, defermonth, deferyear, color, task_id)
                            conn.execute('''UPDATE AutoHabit
                                         SET deferred = 1, def_days = ?,
                                         def_months = ?, def_years = ?,
                                         color = ?
                                         WHERE id = ?;''', tup)

                            inc_change_num(conn, 1, None, task_id)

    elif form["task-type"].value == 'biscuit':
        # There must be an action
        try:
            form["action"].value
................................................................................
                    color,
                    nom,
                    timestamp,
                    user_id,
                )
                conn.execute('''INSERT INTO Biscuit (id,
                             color, name, timestamp, user_id)
                             VALUES (?, ?, ?, ?, ?)''', tup)

        if form["action"].value == 'delete':
            # AJAX
            for key in form:
                if re.search('^taskid_', key):
                    tup = (form[key].value, user_id)

                    conn.execute('''DELETE FROM Biscuit
                                 WHERE id = ?
                                 AND user_id = ?''', tup)

        elif form["action"].value == 'modify':
            # Mini page

            # If this function returns something, that means it
            # displayed a mini page, so we return it's output to the
            # caller function.
................................................................................

                    if check_perm_task(conn, task_id, 2, user_id):
                        # Highlight blue.
                        color = 'blue'

                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'highlight-red':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 2, user_id):
                        # Highlight red.
                        color = 'red'

                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'highlight-green':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 2, user_id):
                        # Highlight green.
                        color = 'green'

                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'highlight-none':
            # AJAX
            color = conf['Cosmetic']['default_task_background_color']

................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 2, user_id):
                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = ?
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'save all':
            # Normal form submit

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)
................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 2, user_id):
                        tup = (task_id,)
                        conn.execute('''DELETE FROM ManuHabit
                                     WHERE id = ?;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'defer':
            # Mini page

            # If this function returns something, that means it
................................................................................

                        if check_perm_task(conn, task_id, 2, user_id):
                            # Defer set ammount
                            color = conf['Cosmetic']['default_defered_task_background_color']

                            tup = (deferday, defermonth, deferyear, color, task_id)
                            conn.execute('''UPDATE ManuHabit
                                         SET deferred = 1, def_days = ?,
                                         def_months = ?, def_years = ?,
                                         color = ?
                                         WHERE id = ?;''', tup)

                            inc_change_num(conn, 2, None, task_id)

    elif form["task-type"].value == 'note_cat':
        try:
            action = form["action"].value
        except KeyError:
................................................................................
                    if check_perm_cat(conn, cat_id, 0, user_id):
                        tup = (
                            form["notecat-name_" + itnum].value,
                            cat_id
                        )

                        conn.execute('''UPDATE NoteCat
                                     SET name = ?
                                     WHERE id = ?;''', tup)

        # Search if they want to delete something
        for key in form:
            if re.search('^action_del_notecat_', key):
                delete = key.split('_')[-1]

                # We only delete it if there's no pages using this category
                tup = (0, delete, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = ?
                             AND entry_id = ?
                             AND user_id = ?;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to delete it if there are other users using
                # this category.
                tup = (0, delete)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = ?
                             AND cat_id = ?;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users < 2:
                    # Delete everything in that category
                    tup = (delete,)
                    conn.execute('''DELETE FROM Note
                                 WHERE cat_id = ?;''', tup)

                    # Delete the category
                    tup = (delete,)
                    conn.execute('''DELETE FROM NoteCat
                                 WHERE id = ?;''', tup)

                    # Delete our CatKey entry
                    tup = (0, delete, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = ?
                                 AND cat_id = ?
                                 AND user_id = ?;''', tup)

        # Search if they want to revoke their own access to something
        for key in form:
            if re.search('^action_revoke_notecat_', key):
                revoke = key.split('_')[-1]

                # We only revoke it if there's no pages using this category
                tup = (0, revoke, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = ?
                             AND entry_id = ?
                             AND user_id = ?;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to revoke if there aren't other users using
                # this category, because then it should be deleted.
                tup = (0, revoke)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = ?
                             AND cat_id = ?;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users > 1:
                    # Delete our CatKey entry
                    tup = (0, revoke, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = ?
                                 AND cat_id = ?
                                 AND user_id = ?;''', tup)

        # Search if they want to copy this category
        for key in form:
            if re.search('^action_copy_notecat_', key):
                copy = key.split('_')[-1]

                # Check they have permission to this category
                if check_perm_cat(conn, copy, 0, user_id):
                    # Find out the name of the category
                    tup = (copy,)
                    conn.execute('''SELECT name
                                 FROM NoteCat
                                 WHERE id = ?;''', tup)
                    orig_name = conn.fetchone()[0]

                    # Add the word `(copy)' to the name of the category
                    new_name = orig_name + ' (copy)'

                    # Create a new category with that name
                    new_cat_id = add_cat(conn, user_id, new_name, cur_time,
................................................................................
                    conn.execute('''SELECT color,
                                        name,
                                        deferred,
                                        def_days,
                                        def_months,
                                        def_years
                                 FROM Note
                                 WHERE cat_id = ?
                                 ORDER BY id ASC;''', tup)
                    rows = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[3], elem[
                        4], elem[5]] for elem in conn.fetchall()]

                    # For every task, add it to the new category.
                    for row in rows:
                        color = row[0]
................................................................................
                    if check_perm_cat(conn, cat_id, 1, user_id):
                        tup = (
                            form["autohabitcat-name_" + itnum].value,
                            cat_id
                        )

                        conn.execute('''UPDATE AutoHabitCat
                                     SET name = ?
                                     WHERE id = ?;''', tup)

        # Search if they want to delete something
        for key in form:
            if re.search('^action_del_autocat_', key):
                delete = key.split('_')[-1]

                # We only delete it if there's no pages using this category
                tup = (1, delete, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type=?
                             AND entry_id = ?
                             AND user_id = ?''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to delete it if there are other users using
                # this category.
                tup = (1, delete)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = ?
                             AND cat_id = ?;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users < 2:
                    # Delete everything in that category
                    tup = (delete,)
                    conn.execute('''DELETE FROM AutoHabit
                                 WHERE cat_id = ?;''', tup)

                    # Delete the category
                    tup = (delete,)
                    conn.execute('''DELETE FROM AutoHabitCat
                                 WHERE id = ?;''', tup)

                    tup = (1, delete, user_id)
                    # Delete our CatKey entry
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = ?
                                 AND cat_id = ?
                                 AND user_id = ?;''', tup)

        # Search if they want to revoke their own access to something
        for key in form:
            if re.search('^action_revoke_autocat_', key):
                revoke = key.split('_')[-1]

                # We only revoke it if there's no pages using this category
                tup = (1, revoke, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = ?
                             AND entry_id = ?
                             AND user_id = ?;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to revoke if there aren't other users using
                # this category, because then it should be deleted.
                tup = (1, revoke)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = ?
                             AND cat_id = ?;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users > 1:
                    # Delete our CatKey entry
                    tup = (1, revoke, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = ?
                                 AND cat_id = ?
                                 AND user_id = ?;''', tup)

        # Search if they want to copy this category
        for key in form:
            if re.search('^action_copy_autocat_', key):
                copy = key.split('_')[-1]

                # Check they have permission to this category
                if check_perm_cat(conn, copy, 1, user_id):
                    # Find out the name of the category
                    tup = (copy,)
                    conn.execute('''SELECT name
                                 FROM AutoHabitCat
                                 WHERE id = ?;''', tup)
                    orig_name = conn.fetchone()[0]

                    # Add the word `(copy)' to the name of the category
                    new_name = orig_name + ' (copy)'

                    # Create a new category with that name
                    new_cat_id = add_cat(conn, user_id, new_name, cur_time,
................................................................................
                                        name,
                                        freq,
                                        freq_units,
                                        due_days,
                                        due_months,
                                        due_years
                                 FROM AutoHabit
                                 WHERE cat_id = ?
                                 ORDER BY id ASC;''', tup)
                    rows = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[3], elem[
                        4], elem[5], elem[6]] for elem in conn.fetchall()]

                    # For every task, add it to the new category.
                    for row in rows:
                        color = row[0]
................................................................................
                    if check_perm_cat(conn, cat_id, 2, user_id):
                        tup = (
                            form["manuhabitcat-name_" + itnum].value,
                            cat_id
                        )

                        conn.execute('''UPDATE ManuHabitCat
                                     SET name = ?
                                     WHERE id = ?;''', tup)

        # Search if they want to delete something
        for key in form:
            if re.search('^action_del_manucat_', key):
                delete = key.split('_')[-1]

                # We only delete it if there's no pages using this category
                tup = (2, delete, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = ?
                             AND entry_id = ?
                             AND user_id = ?;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to delete it if there are other users using
                # this category.
                tup = (2, delete)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = ?
                             AND cat_id = ?;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users < 2:
                    # Delete everything in that category
                    tup = (delete,)
                    conn.execute('''DELETE FROM ManuHabit
                                 WHERE cat_id = ?;''', tup)

                    # Delete the category
                    tup = (delete,)
                    conn.execute('''DELETE FROM ManuHabitCat
                                 WHERE id = ?;''', tup)

                    tup = (2, delete, user_id)
                    # Delete our CatKey entry
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = ?
                                 AND cat_id = ?
                                 AND user_id = ?;''', tup)

        # Search if they want to revoke their own access to something
        for key in form:
            if re.search('^action_revoke_manucat_', key):
                revoke = key.split('_')[-1]

                # We only revoke it if there's no pages using this category
                tup = (2, revoke, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = ?
                             AND entry_id = ?
                             AND user_id = ?;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to revoke if there aren't other users using
                # this category, because then it should be deleted.
                tup = (2, revoke)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = ?
                             AND cat_id = ?;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users > 1:
                    # Delete our CatKey entry
                    tup = (2, revoke, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = ?
                                 AND cat_id = ?
                                 AND user_id = ?;''', tup)

        # Search if they want to copy this category
        for key in form:
            if re.search('^action_copy_manucat_', key):
                copy = key.split('_')[-1]

                # Check they have permission to this category
                if check_perm_cat(conn, copy, 2, user_id):
                    # Find out the name of the category
                    tup = (copy,)
                    conn.execute('''SELECT name
                                 FROM ManuHabitCat
                                 WHERE id = ?;''', tup)
                    orig_name = conn.fetchone()[0]

                    # Add the word `(copy)' to the name of the category
                    new_name = orig_name + ' (copy)'

                    # Create a new category with that name
                    new_cat_id = add_cat(conn, user_id, new_name, cur_time,
................................................................................
                    # Get all tasks, with the name decrypted
                    tup = (copy,)
                    conn.execute('''SELECT color,
                                        name,
                                        freq,
                                        due
                                 FROM ManuHabit
                                 WHERE cat_id = ?
                                 ORDER BY id ASC;''', tup)
                    rows = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[
                        3]] for elem in conn.fetchall()]

                    # For every task, add it to the new category.
                    for row in rows:
                        color = row[0]
................................................................................
            # Delete every line that was selected.
            for key in form:
                if re.search('^check_page_', key):
                    tup = (form[key].value, user_id)

                    # Delete all entries in this page
                    conn.execute('''DELETE FROM PageContent
                                 WHERE page_id = ?
                                 AND user_id = ?''', tup)

                    # Delete the page
                    conn.execute('''DELETE FROM Page
                                 WHERE id = ?
                                 AND user_id = ?''', tup)

        elif action == 'save all':
            for key in form:
                if re.search('^hide_page_', key):
                    itnum = key.split('_')[-1]
                    pageid = form[key].value

................................................................................
                    tup = (
                        form["page-name_" + itnum].value,
                        pageid,
                        user_id
                    )

                    conn.execute('''UPDATE Page
                                 SET name = ?
                                 WHERE id = ?
                                 AND user_id = ?;''', tup)

        # Find if they want to add a category to the page
        for key in form:
            if re.search('^action_add_to_page_', key):
                # Cut out the page id
                page_id = key.split('_')[-1]

................................................................................
                if check_perm_cat(conn, entry_id, entry_type,
                                  user_id):
                    # Find out the highest sequence number of any entry on
                    # that page and add one.
                    tup = (page_id, user_id)
                    conn.execute('''SELECT seq
                                 FROM PageContent
                                 WHERE page_id = ?
                                 AND user_id = ?
                                 ORDER BY seq;''', tup)
                    try:
                        highest_number = conn.fetchall()[-1][0]
                        new_number = highest_number + 1
                    except Exception:  # if there is no other entry
                        new_number = 0

................................................................................
        for key in form:
            if re.search('^action_remove_entry_', key):
                # Cut out the content id
                content_id = key.split('_')[-1]

                tup = (content_id, user_id)
                conn.execute('''DELETE FROM PageContent
                             WHERE id = ?
                             AND user_id = ?;''', tup)

        # Find if they want to move a page entry up
        for key in form:
            if re.search('^action_up_entry_', key):
                # Cut out the page and entry ids
                page_id = key.split('_')[-1]
                entry_id = key.split('_')[-3]
................................................................................
                # entry. Then insert it one before. Then make a new
                # list giving a sequence number to all entries. And
                # write the new sequence numbers to the database where
                # they've changed.
                tup = (page_id, user_id)
                conn.execute("""SELECT id
                             FROM PageContent
                             WHERE page_id = ?
                             AND user_id = ?
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE PageContent
                                         SET seq = ?
                                         WHERE id = ?
                                         AND user_id = ?''', tup)

        # Find if they want to move a page entry down
        for key in form:
            if re.search('^action_down_entry_', key):
                # Cut out the page and entry ids
                page_id = key.split('_')[-1]
                entry_id = key.split('_')[-3]
................................................................................
                # list.  Then del that entry. Then insert it one
                # after. Then make a new list giving a sequence
                # number to all entries. And write the new sequence
                # numbers to the database where they've changed.
                tup = (page_id, user_id)
                conn.execute("""SELECT id
                             FROM PageContent
                             WHERE page_id = ?
                             AND user_id = ?
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE PageContent
                                         SET seq = ?
                                         WHERE id = ?
                                         AND user_id = ?''', tup)

        # Find if they want to move a page up
        for key in form:
            if re.search('^action_up_page_', key):
                # Cut out the page id
                page_id = key.split('_')[-1]

................................................................................
                # it's not 0. Then del that entry. Then insert it one
                # before. Then make a new list giving a sequence
                # number to all entries. And write the new sequence
                # numbers to the database where they've changed.
                tup = (user_id,)
                conn.execute("""SELECT id
                             FROM Page
                             WHERE user_id = ?
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE Page
                                         SET seq = ?
                                         WHERE id = ?
                                         AND user_id = ?;''', tup)

        # Find if they want to move a page down
        for key in form:
            if re.search('^action_down_page_', key):
                # Cut out the page id
                page_id = key.split('_')[-1]

................................................................................
                # entry. Then insert it one after. Then make a new
                # list giving a sequence number to all entries. And
                # write the new sequence numbers to the database where
                # they've changed.
                tup = (user_id,)
                conn.execute("""SELECT id
                             FROM Page
                             WHERE user_id = ?
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE Page
                                         SET seq = ?
                                         WHERE id = ?
                                         AND user_id = ?;''', tup)

        # Find out if they want to add a page
        for key in form:
            if re.search('^action_add_page', key):
                # Get the new page's name
                name = form['new_page'].value
                # Check it's not blank.
                if name != '':
                    # Find out the highest sequence number of any page
                    # and add one.
                    tup = (user_id,)
                    conn.execute('''SELECT seq
                                 FROM Page
                                 WHERE user_id = ?
                                 ORDER BY seq;''', tup)
                    try:
                        highest_number = conn.fetchall()[-1][0]
                        new_number = highest_number + 1
                    except Exception:  # if there is no other page
                        new_number = 0

................................................................................
                b_enabled = 2
        except KeyError:
            b_enabled = 0

        if b_enabled != 2:
            tup = (b_enabled, user_id)
            conn.execute('''UPDATE User
                         SET biscuits_enabled = ?
                         WHERE id = ?;''', tup)

        # Find out if they want to change their timezone
        try:
            fieldcheck = form['action_tz_change'].value
        except KeyError:
            fieldcheck = None

................................................................................

            tup = (
                new_tz,
                user_id
            )

            conn.execute('''UPDATE User
                         SET tz = ?
                         WHERE id = ?''', tup)

        # Find out if they want to change their username
        try:
            fieldcheck = form['action_modify_username'].value
        except KeyError:
            fieldcheck = None

................................................................................

            tup = (
                newtheme,
                user_id
            )

            conn.execute('''UPDATE User
                         SET actheme = ?
                         WHERE id = ?''', tup)

            return ('theme updated', 'no', 'nothing_printed')

        # Find out if they want to logout other devices
        try:
            fieldcheck = form['action_del_other_sessions'].value
        except KeyError:
................................................................................
        # so we get straight to it.
        for key in form:
            if re.search('^button_notification_', key):
                notification_id = re.sub('^button_notification_', '', key)

                tup = (notification_id, user_id)
                conn.execute('''DELETE FROM Notification
                             WHERE id = ?
                             AND user_id = ?;''', tup)

    return ('nothing printed', 'no', 'nothing_printed')







|







 







|
|







 







|
|







 







|
|







 







|
|







 







|
|
|
|
|







 







|
|
|
|







 







|







 







|
|







 







|
|







 







|
|







 







|
|







 







|







 







|
|
|
|







 







|








|
|







 







|
|







 







|
|







 







|
|







 







|
|







 







|







 







|
|
|
|







 







|
|









|
|
|







|
|






|




|




|
|
|









|
|
|







|
|






|
|
|












|







 







|







 







|
|









|
|
|







|
|






|




|




|
|
|









|
|
|







|
|






|
|
|












|







 







|







 







|
|









|
|
|







|
|






|




|




|
|
|









|
|
|







|
|






|
|
|












|







 







|







 







|
|



|
|







 







|
|
|







 







|
|







 







|
|







 







|
|







 







|
|
|







 







|
|







 







|
|
|







 







|







 







|
|
|







 







|







 







|
|
|













|







 







|
|







 







|
|







 







|
|







 







|
|


110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
...
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
...
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
...
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
...
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
...
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
...
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
...
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
...
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
...
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
...
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
...
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
...
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
...
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
...
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
...
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
...
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
...
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
...
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
....
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
....
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
....
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
....
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
....
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
....
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
....
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
....
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
....
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
....
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
....
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
....
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
....
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
....
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
....
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
....
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
....
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
....
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
....
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
....
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
....
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 0, user_id):
                        tup = (task_id,)
                        conn.execute('''DELETE FROM Note
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'add new' or form["action"].value == 'add-bop':
            # AJAX
            color = 'default'

................................................................................

                    if check_perm_task(conn, task_id, 0, user_id):
                        # Highlight blue.
                        color = 'blue'

                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'highlight-red':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 0, user_id):
                        # Highlight red.
                        color = 'red'

                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'highlight-green':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 0, user_id):
                        # Highlight green.
                        color = 'green'

                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'highlight-none':
            # AJAX
            color = conf['Cosmetic']['default_task_background_color']

................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 0, user_id):
                        tup = (color, task_id)
                        conn.execute('''UPDATE Note
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'move':
            # Mini page

            # If this function returns something, that means it
................................................................................
                                nom,
                                form["task-next-day_" + itnum].value,
                                form["task-next-month_" + itnum].value,
                                form["task-next-year_" + itnum].value,
                                task_id
                            )

                            conn.execute('''UPDATE Note Set name = %s,
                                         def_days = %s,
                                         def_months = %s,
                                         def_years = %s
                                         WHERE id = %s;''', tup)
                        except ValueError as error:
                            print('error: ' + error.args[0])

                inc_change_num(conn, 0, cat_id, None)

        elif form["action"].value == 'defer':
            # Mini page
................................................................................

                            if check_perm_task(conn, task_id, 0, user_id):
                                # Defer set ammount
                                color = conf['Cosmetic']['default_defered_task_background_color']

                                tup = (deferday, defermonth, deferyear, color, task_id)
                                conn.execute('''UPDATE Note
                                             SET deferred = 1, def_days = %s,
                                             def_months = %s, def_years = %s,
                                             color = %s
                                             WHERE id = %s;''', tup)

                                inc_change_num(conn, 0, None, task_id)

                elif ajaxdefer.group(1) == 'add deferred':
                    # This is not a mini page. This is an AJAX call.

                    # Let's get the date it's being deferred to.
................................................................................
                            deferyear,
                            user_id
                        ]

                        conn.execute('''INSERT INTO Note
                                     (id, cat_id, color, name, deferred,
                                     def_days, def_months, def_years, user_id)
                                     VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)''', to_be_inserted)

                        inc_change_num(conn, 0, form["data-category"].value, None)


    elif form["task-type"].value == 'auto_habit':
        cat_id = form["data-category"].value

................................................................................

                    if check_perm_task(conn, task_id, 1, user_id):
                        # Highlight blue.
                        color = 'blue'

                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'highlight-red':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 1, user_id):
                        # Highlight red.
                        color = 'red'

                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'highlight-green':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 1, user_id):
                        # Highlight green.
                        color = 'green'

                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'highlight-none':
            # AJAX
            color = conf['Cosmetic']['default_task_background_color']

................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 1, user_id):
                        tup = (color, task_id)
                        conn.execute('''UPDATE AutoHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'save all':
            # Normal form submit

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)
................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 1, user_id):
                        tup = (task_id,)
                        conn.execute('''DELETE FROM AutoHabit
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 1, cat_id, None)

        elif form["action"].value == 'defer':
            # Mini page

            # If this function returns something, that means it
................................................................................

                        if check_perm_task(conn, task_id, 1, user_id):
                            # Defer set ammount
                            color = conf['Cosmetic']['default_defered_task_background_color']

                            tup = (deferday, defermonth, deferyear, color, task_id)
                            conn.execute('''UPDATE AutoHabit
                                         SET deferred = 1, def_days = %s,
                                         def_months = %s, def_years = %s,
                                         color = %s
                                         WHERE id = %s;''', tup)

                            inc_change_num(conn, 1, None, task_id)

    elif form["task-type"].value == 'biscuit':
        # There must be an action
        try:
            form["action"].value
................................................................................
                    color,
                    nom,
                    timestamp,
                    user_id,
                )
                conn.execute('''INSERT INTO Biscuit (id,
                             color, name, timestamp, user_id)
                             VALUES (%s, %s, %s, %s, %s)''', tup)

        if form["action"].value == 'delete':
            # AJAX
            for key in form:
                if re.search('^taskid_', key):
                    tup = (form[key].value, user_id)

                    conn.execute('''DELETE FROM Biscuit
                                 WHERE id = %s
                                 AND user_id = %s''', tup)

        elif form["action"].value == 'modify':
            # Mini page

            # If this function returns something, that means it
            # displayed a mini page, so we return it's output to the
            # caller function.
................................................................................

                    if check_perm_task(conn, task_id, 2, user_id):
                        # Highlight blue.
                        color = 'blue'

                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'highlight-red':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 2, user_id):
                        # Highlight red.
                        color = 'red'

                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'highlight-green':
            # AJAX

            for key in form:
................................................................................

                    if check_perm_task(conn, task_id, 2, user_id):
                        # Highlight green.
                        color = 'green'

                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'highlight-none':
            # AJAX
            color = conf['Cosmetic']['default_task_background_color']

................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 2, user_id):
                        tup = (color, task_id)
                        conn.execute('''UPDATE ManuHabit
                                     SET color = %s
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'save all':
            # Normal form submit

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)
................................................................................
            for key in form:
                if re.search('^taskid_', key):
                    task_id = form[key].value

                    if check_perm_task(conn, task_id, 2, user_id):
                        tup = (task_id,)
                        conn.execute('''DELETE FROM ManuHabit
                                     WHERE id = %s;''', tup)

                        inc_change_num(conn, 2, cat_id, None)

        elif form["action"].value == 'defer':
            # Mini page

            # If this function returns something, that means it
................................................................................

                        if check_perm_task(conn, task_id, 2, user_id):
                            # Defer set ammount
                            color = conf['Cosmetic']['default_defered_task_background_color']

                            tup = (deferday, defermonth, deferyear, color, task_id)
                            conn.execute('''UPDATE ManuHabit
                                         SET deferred = 1, def_days = %s,
                                         def_months = %s, def_years = %s,
                                         color = %s
                                         WHERE id = %s;''', tup)

                            inc_change_num(conn, 2, None, task_id)

    elif form["task-type"].value == 'note_cat':
        try:
            action = form["action"].value
        except KeyError:
................................................................................
                    if check_perm_cat(conn, cat_id, 0, user_id):
                        tup = (
                            form["notecat-name_" + itnum].value,
                            cat_id
                        )

                        conn.execute('''UPDATE NoteCat
                                     SET name = %s
                                     WHERE id = %s;''', tup)

        # Search if they want to delete something
        for key in form:
            if re.search('^action_del_notecat_', key):
                delete = key.split('_')[-1]

                # We only delete it if there's no pages using this category
                tup = (0, delete, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = %s
                             AND entry_id = %s
                             AND user_id = %s;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to delete it if there are other users using
                # this category.
                tup = (0, delete)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = %s
                             AND cat_id = %s;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users < 2:
                    # Delete everything in that category
                    tup = (delete,)
                    conn.execute('''DELETE FROM Note
                                 WHERE cat_id = %s;''', tup)

                    # Delete the category
                    tup = (delete,)
                    conn.execute('''DELETE FROM NoteCat
                                 WHERE id = %s;''', tup)

                    # Delete our CatKey entry
                    tup = (0, delete, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = %s
                                 AND cat_id = %s
                                 AND user_id = %s;''', tup)

        # Search if they want to revoke their own access to something
        for key in form:
            if re.search('^action_revoke_notecat_', key):
                revoke = key.split('_')[-1]

                # We only revoke it if there's no pages using this category
                tup = (0, revoke, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = %s
                             AND entry_id = %s
                             AND user_id = %s;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to revoke if there aren't other users using
                # this category, because then it should be deleted.
                tup = (0, revoke)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = %s
                             AND cat_id = %s;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users > 1:
                    # Delete our CatKey entry
                    tup = (0, revoke, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = %s
                                 AND cat_id = %s
                                 AND user_id = %s;''', tup)

        # Search if they want to copy this category
        for key in form:
            if re.search('^action_copy_notecat_', key):
                copy = key.split('_')[-1]

                # Check they have permission to this category
                if check_perm_cat(conn, copy, 0, user_id):
                    # Find out the name of the category
                    tup = (copy,)
                    conn.execute('''SELECT name
                                 FROM NoteCat
                                 WHERE id = %s;''', tup)
                    orig_name = conn.fetchone()[0]

                    # Add the word `(copy)' to the name of the category
                    new_name = orig_name + ' (copy)'

                    # Create a new category with that name
                    new_cat_id = add_cat(conn, user_id, new_name, cur_time,
................................................................................
                    conn.execute('''SELECT color,
                                        name,
                                        deferred,
                                        def_days,
                                        def_months,
                                        def_years
                                 FROM Note
                                 WHERE cat_id = %s
                                 ORDER BY id ASC;''', tup)
                    rows = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[3], elem[
                        4], elem[5]] for elem in conn.fetchall()]

                    # For every task, add it to the new category.
                    for row in rows:
                        color = row[0]
................................................................................
                    if check_perm_cat(conn, cat_id, 1, user_id):
                        tup = (
                            form["autohabitcat-name_" + itnum].value,
                            cat_id
                        )

                        conn.execute('''UPDATE AutoHabitCat
                                     SET name = %s
                                     WHERE id = %s;''', tup)

        # Search if they want to delete something
        for key in form:
            if re.search('^action_del_autocat_', key):
                delete = key.split('_')[-1]

                # We only delete it if there's no pages using this category
                tup = (1, delete, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type=%s
                             AND entry_id = %s
                             AND user_id = %s''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to delete it if there are other users using
                # this category.
                tup = (1, delete)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = %s
                             AND cat_id = %s;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users < 2:
                    # Delete everything in that category
                    tup = (delete,)
                    conn.execute('''DELETE FROM AutoHabit
                                 WHERE cat_id = %s;''', tup)

                    # Delete the category
                    tup = (delete,)
                    conn.execute('''DELETE FROM AutoHabitCat
                                 WHERE id = %s;''', tup)

                    tup = (1, delete, user_id)
                    # Delete our CatKey entry
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = %s
                                 AND cat_id = %s
                                 AND user_id = %s;''', tup)

        # Search if they want to revoke their own access to something
        for key in form:
            if re.search('^action_revoke_autocat_', key):
                revoke = key.split('_')[-1]

                # We only revoke it if there's no pages using this category
                tup = (1, revoke, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = %s
                             AND entry_id = %s
                             AND user_id = %s;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to revoke if there aren't other users using
                # this category, because then it should be deleted.
                tup = (1, revoke)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = %s
                             AND cat_id = %s;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users > 1:
                    # Delete our CatKey entry
                    tup = (1, revoke, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = %s
                                 AND cat_id = %s
                                 AND user_id = %s;''', tup)

        # Search if they want to copy this category
        for key in form:
            if re.search('^action_copy_autocat_', key):
                copy = key.split('_')[-1]

                # Check they have permission to this category
                if check_perm_cat(conn, copy, 1, user_id):
                    # Find out the name of the category
                    tup = (copy,)
                    conn.execute('''SELECT name
                                 FROM AutoHabitCat
                                 WHERE id = %s;''', tup)
                    orig_name = conn.fetchone()[0]

                    # Add the word `(copy)' to the name of the category
                    new_name = orig_name + ' (copy)'

                    # Create a new category with that name
                    new_cat_id = add_cat(conn, user_id, new_name, cur_time,
................................................................................
                                        name,
                                        freq,
                                        freq_units,
                                        due_days,
                                        due_months,
                                        due_years
                                 FROM AutoHabit
                                 WHERE cat_id = %s
                                 ORDER BY id ASC;''', tup)
                    rows = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[3], elem[
                        4], elem[5], elem[6]] for elem in conn.fetchall()]

                    # For every task, add it to the new category.
                    for row in rows:
                        color = row[0]
................................................................................
                    if check_perm_cat(conn, cat_id, 2, user_id):
                        tup = (
                            form["manuhabitcat-name_" + itnum].value,
                            cat_id
                        )

                        conn.execute('''UPDATE ManuHabitCat
                                     SET name = %s
                                     WHERE id = %s;''', tup)

        # Search if they want to delete something
        for key in form:
            if re.search('^action_del_manucat_', key):
                delete = key.split('_')[-1]

                # We only delete it if there's no pages using this category
                tup = (2, delete, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = %s
                             AND entry_id = %s
                             AND user_id = %s;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to delete it if there are other users using
                # this category.
                tup = (2, delete)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = %s
                             AND cat_id = %s;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users < 2:
                    # Delete everything in that category
                    tup = (delete,)
                    conn.execute('''DELETE FROM ManuHabit
                                 WHERE cat_id = %s;''', tup)

                    # Delete the category
                    tup = (delete,)
                    conn.execute('''DELETE FROM ManuHabitCat
                                 WHERE id = %s;''', tup)

                    tup = (2, delete, user_id)
                    # Delete our CatKey entry
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = %s
                                 AND cat_id = %s
                                 AND user_id = %s;''', tup)

        # Search if they want to revoke their own access to something
        for key in form:
            if re.search('^action_revoke_manucat_', key):
                revoke = key.split('_')[-1]

                # We only revoke it if there's no pages using this category
                tup = (2, revoke, user_id)
                conn.execute('''SELECT id FROM PageContent
                             WHERE entry_type = %s
                             AND entry_id = %s
                             AND user_id = %s;''', tup)
                num_pages_using = len(conn.fetchall())

                # We refuse to revoke if there aren't other users using
                # this category, because then it should be deleted.
                tup = (2, revoke)
                conn.execute('''SELECT user_id
                             FROM CatKey
                             WHERE task_type = %s
                             AND cat_id = %s;''', tup)
                num_users = len(conn.fetchall())

                if num_pages_using == 0 and num_users > 1:
                    # Delete our CatKey entry
                    tup = (2, revoke, user_id)
                    conn.execute('''DELETE FROM CatKey
                                 WHERE task_type = %s
                                 AND cat_id = %s
                                 AND user_id = %s;''', tup)

        # Search if they want to copy this category
        for key in form:
            if re.search('^action_copy_manucat_', key):
                copy = key.split('_')[-1]

                # Check they have permission to this category
                if check_perm_cat(conn, copy, 2, user_id):
                    # Find out the name of the category
                    tup = (copy,)
                    conn.execute('''SELECT name
                                 FROM ManuHabitCat
                                 WHERE id = %s;''', tup)
                    orig_name = conn.fetchone()[0]

                    # Add the word `(copy)' to the name of the category
                    new_name = orig_name + ' (copy)'

                    # Create a new category with that name
                    new_cat_id = add_cat(conn, user_id, new_name, cur_time,
................................................................................
                    # Get all tasks, with the name decrypted
                    tup = (copy,)
                    conn.execute('''SELECT color,
                                        name,
                                        freq,
                                        due
                                 FROM ManuHabit
                                 WHERE cat_id = %s
                                 ORDER BY id ASC;''', tup)
                    rows = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[
                        3]] for elem in conn.fetchall()]

                    # For every task, add it to the new category.
                    for row in rows:
                        color = row[0]
................................................................................
            # Delete every line that was selected.
            for key in form:
                if re.search('^check_page_', key):
                    tup = (form[key].value, user_id)

                    # Delete all entries in this page
                    conn.execute('''DELETE FROM PageContent
                                 WHERE page_id = %s
                                 AND user_id = %s''', tup)

                    # Delete the page
                    conn.execute('''DELETE FROM Page
                                 WHERE id = %s
                                 AND user_id = %s''', tup)

        elif action == 'save all':
            for key in form:
                if re.search('^hide_page_', key):
                    itnum = key.split('_')[-1]
                    pageid = form[key].value

................................................................................
                    tup = (
                        form["page-name_" + itnum].value,
                        pageid,
                        user_id
                    )

                    conn.execute('''UPDATE Page
                                 SET name = %s
                                 WHERE id = %s
                                 AND user_id = %s;''', tup)

        # Find if they want to add a category to the page
        for key in form:
            if re.search('^action_add_to_page_', key):
                # Cut out the page id
                page_id = key.split('_')[-1]

................................................................................
                if check_perm_cat(conn, entry_id, entry_type,
                                  user_id):
                    # Find out the highest sequence number of any entry on
                    # that page and add one.
                    tup = (page_id, user_id)
                    conn.execute('''SELECT seq
                                 FROM PageContent
                                 WHERE page_id = %s
                                 AND user_id = %s
                                 ORDER BY seq;''', tup)
                    try:
                        highest_number = conn.fetchall()[-1][0]
                        new_number = highest_number + 1
                    except Exception:  # if there is no other entry
                        new_number = 0

................................................................................
        for key in form:
            if re.search('^action_remove_entry_', key):
                # Cut out the content id
                content_id = key.split('_')[-1]

                tup = (content_id, user_id)
                conn.execute('''DELETE FROM PageContent
                             WHERE id = %s
                             AND user_id = %s;''', tup)

        # Find if they want to move a page entry up
        for key in form:
            if re.search('^action_up_entry_', key):
                # Cut out the page and entry ids
                page_id = key.split('_')[-1]
                entry_id = key.split('_')[-3]
................................................................................
                # entry. Then insert it one before. Then make a new
                # list giving a sequence number to all entries. And
                # write the new sequence numbers to the database where
                # they've changed.
                tup = (page_id, user_id)
                conn.execute("""SELECT id
                             FROM PageContent
                             WHERE page_id = %s
                             AND user_id = %s
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE PageContent
                                         SET seq = %s
                                         WHERE id = %s
                                         AND user_id = %s''', tup)

        # Find if they want to move a page entry down
        for key in form:
            if re.search('^action_down_entry_', key):
                # Cut out the page and entry ids
                page_id = key.split('_')[-1]
                entry_id = key.split('_')[-3]
................................................................................
                # list.  Then del that entry. Then insert it one
                # after. Then make a new list giving a sequence
                # number to all entries. And write the new sequence
                # numbers to the database where they've changed.
                tup = (page_id, user_id)
                conn.execute("""SELECT id
                             FROM PageContent
                             WHERE page_id = %s
                             AND user_id = %s
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE PageContent
                                         SET seq = %s
                                         WHERE id = %s
                                         AND user_id = %s''', tup)

        # Find if they want to move a page up
        for key in form:
            if re.search('^action_up_page_', key):
                # Cut out the page id
                page_id = key.split('_')[-1]

................................................................................
                # it's not 0. Then del that entry. Then insert it one
                # before. Then make a new list giving a sequence
                # number to all entries. And write the new sequence
                # numbers to the database where they've changed.
                tup = (user_id,)
                conn.execute("""SELECT id
                             FROM Page
                             WHERE user_id = %s
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE Page
                                         SET seq = %s
                                         WHERE id = %s
                                         AND user_id = %s;''', tup)

        # Find if they want to move a page down
        for key in form:
            if re.search('^action_down_page_', key):
                # Cut out the page id
                page_id = key.split('_')[-1]

................................................................................
                # entry. Then insert it one after. Then make a new
                # list giving a sequence number to all entries. And
                # write the new sequence numbers to the database where
                # they've changed.
                tup = (user_id,)
                conn.execute("""SELECT id
                             FROM Page
                             WHERE user_id = %s
                             ORDER BY seq;""", tup)
                contents = conn.fetchall()

                # We have a list of lists but we only want a list of ids.
                fixed = [var[0] for var in contents]
                new_list = list(fixed)

................................................................................
                        # Check if it's at the same index as it was
                        # before. If not, write the change to the
                        # database.
                        if fixed[idx] != item:
                            tup = (idx, item, user_id)

                            conn.execute('''UPDATE Page
                                         SET seq = %s
                                         WHERE id = %s
                                         AND user_id = %s;''', tup)

        # Find out if they want to add a page
        for key in form:
            if re.search('^action_add_page', key):
                # Get the new page's name
                name = form['new_page'].value
                # Check it's not blank.
                if name != '':
                    # Find out the highest sequence number of any page
                    # and add one.
                    tup = (user_id,)
                    conn.execute('''SELECT seq
                                 FROM Page
                                 WHERE user_id = %s
                                 ORDER BY seq;''', tup)
                    try:
                        highest_number = conn.fetchall()[-1][0]
                        new_number = highest_number + 1
                    except Exception:  # if there is no other page
                        new_number = 0

................................................................................
                b_enabled = 2
        except KeyError:
            b_enabled = 0

        if b_enabled != 2:
            tup = (b_enabled, user_id)
            conn.execute('''UPDATE User
                         SET biscuits_enabled = %s
                         WHERE id = %s;''', tup)

        # Find out if they want to change their timezone
        try:
            fieldcheck = form['action_tz_change'].value
        except KeyError:
            fieldcheck = None

................................................................................

            tup = (
                new_tz,
                user_id
            )

            conn.execute('''UPDATE User
                         SET tz = %s
                         WHERE id = %s''', tup)

        # Find out if they want to change their username
        try:
            fieldcheck = form['action_modify_username'].value
        except KeyError:
            fieldcheck = None

................................................................................

            tup = (
                newtheme,
                user_id
            )

            conn.execute('''UPDATE User
                         SET actheme = %s
                         WHERE id = %s''', tup)

            return ('theme updated', 'no', 'nothing_printed')

        # Find out if they want to logout other devices
        try:
            fieldcheck = form['action_del_other_sessions'].value
        except KeyError:
................................................................................
        # so we get straight to it.
        for key in form:
            if re.search('^button_notification_', key):
                notification_id = re.sub('^button_notification_', '', key)

                tup = (notification_id, user_id)
                conn.execute('''DELETE FROM Notification
                             WHERE id = %s
                             AND user_id = %s;''', tup)

    return ('nothing printed', 'no', 'nothing_printed')

Changes to taskenizer/functions/task_funcs.py.

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
...
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
...
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
...
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
...
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    activetheme = installtheme

    # Find out their account theme. If this fails it dun't matter.
    tup = (user_id,)

    conn.execute('''SELECT actheme
                 FROM User
                 WHERE id = ?;''', tup)

    accounttheme = conn.fetchall()[0][0]

    # Check this theme even exists, else use installtheme
    try:
        conf[accounttheme]['background']

................................................................................
def make_session(conn, user_id, cur_time, expires, ex_head):
    from taskenizer.functions import operations

    session_id = operations.genid(cur_time)

    tup = (session_id, user_id, expires)
    conn.execute('''INSERT INTO Session (id, user_id, expires)
                 VALUES (?, ?, ?);''', tup)

    # Now we have created a session! The user now needs to be
    # given the user_id and session ID in cookies, with the
    # expires date set appropriately.

    # Initiate the response_headers var to an empty list
    response_headers = []
................................................................................
def derive_key(conn, user_id, raw_pass, ex_head):
    import base64

    # Get the cyryptohash salt
    tup = (user_id,)
    conn.execute('''SELECT cryptsalt
                 FROM User
                 WHERE id = ?;''', tup)
    ans = conn.fetchone()
    cryptosalt = base64.b64decode(ans[0].encode('ASCII'))

    # Encode the provided passphrase to binary
    cryptopass = raw_pass.encode('utf-8')

    # Use PKDF2 to convert the passphrase into an encryption key, with
................................................................................
    import os
    from taskenizer.functions import operations

    tup = (user_id,)
    conn.execute('''SELECT id, connected, iv
                 FROM CatKey
                 WHERE connected != 'yes'
                 AND user_id = ?;''', tup)

    for catkey in conn.fetchall():
        catkeyid = catkey[0]
        shmfile = catkey[1]
        cativ = catkey[2]

        if os.path.isfile(shmfile):
................................................................................
                            )
            encryptor = cipher.encryptor()

            token = encryptor.update(key) + encryptor.finalize()

            tup = (token, catkeyid)
            conn.execute('''UPDATE CatKey
                         SET connected = 'yes', key = ?
                         WHERE id = ?;''', tup)

            os.remove(shmfile)

            # Add a notification for the user.

            # We need to find out the date in this user's timezone.
            their_date = operations.find_time(conn,
................................................................................
                                              user_id,
                                              cur_time,
                                              '%Y-%m-%d'
                                              )

            tup = (their_date + new_shared_text, user_id)
            conn.execute('''INSERT INTO Notification (name, user_id)
                         VALUES (?, ?);''', tup)

        else:
            # It's too late, the shm file no longer exists. So we delete the
            # category.
            tup = (catkeyid,)
            conn.execute('''DELETE FROM CatKey
                         WHERE id = ?;''', tup)


def pwchnge_new_cryptohash(conn, user_id, session_id, changed_pass):
    # I need to generate the expires header. But to do
    # that I need to find out when it should expire by
    # looking up the session.
    import time

    tup = (session_id, user_id)
    conn.execute('''SELECT expires
                 FROM Session
                 WHERE id = ?
                 AND user_id = ?;''', tup)
    ans = conn.fetchall()

    expires = float(ans[0][0])

    exp_header = time.strftime("%a, %d %b %Y %T GMT",
                               time.gmtime(expires)
                               )

    # Their new cryptohash cookie
    return [('Set-Cookie', 'cryptohash=' + changed_pass +
             '; expires=' + exp_header +
             '; path=/; Secure; HttpOnly')]







|







 







|







 







|







 







|







 







|
|







 







|






|











|
|












52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
...
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
...
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
...
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
...
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    activetheme = installtheme

    # Find out their account theme. If this fails it dun't matter.
    tup = (user_id,)

    conn.execute('''SELECT actheme
                 FROM User
                 WHERE id = %s;''', tup)

    accounttheme = conn.fetchall()[0][0]

    # Check this theme even exists, else use installtheme
    try:
        conf[accounttheme]['background']

................................................................................
def make_session(conn, user_id, cur_time, expires, ex_head):
    from taskenizer.functions import operations

    session_id = operations.genid(cur_time)

    tup = (session_id, user_id, expires)
    conn.execute('''INSERT INTO Session (id, user_id, expires)
                 VALUES (%s, %s, %s);''', tup)

    # Now we have created a session! The user now needs to be
    # given the user_id and session ID in cookies, with the
    # expires date set appropriately.

    # Initiate the response_headers var to an empty list
    response_headers = []
................................................................................
def derive_key(conn, user_id, raw_pass, ex_head):
    import base64

    # Get the cyryptohash salt
    tup = (user_id,)
    conn.execute('''SELECT cryptsalt
                 FROM User
                 WHERE id = %s;''', tup)
    ans = conn.fetchone()
    cryptosalt = base64.b64decode(ans[0].encode('ASCII'))

    # Encode the provided passphrase to binary
    cryptopass = raw_pass.encode('utf-8')

    # Use PKDF2 to convert the passphrase into an encryption key, with
................................................................................
    import os
    from taskenizer.functions import operations

    tup = (user_id,)
    conn.execute('''SELECT id, connected, iv
                 FROM CatKey
                 WHERE connected != 'yes'
                 AND user_id = %s;''', tup)

    for catkey in conn.fetchall():
        catkeyid = catkey[0]
        shmfile = catkey[1]
        cativ = catkey[2]

        if os.path.isfile(shmfile):
................................................................................
                            )
            encryptor = cipher.encryptor()

            token = encryptor.update(key) + encryptor.finalize()

            tup = (token, catkeyid)
            conn.execute('''UPDATE CatKey
                         SET connected = 'yes', key = %s
                         WHERE id = %s;''', tup)

            os.remove(shmfile)

            # Add a notification for the user.

            # We need to find out the date in this user's timezone.
            their_date = operations.find_time(conn,
................................................................................
                                              user_id,
                                              cur_time,
                                              '%Y-%m-%d'
                                              )

            tup = (their_date + new_shared_text, user_id)
            conn.execute('''INSERT INTO Notification (name, user_id)
                         VALUES (%s, %s);''', tup)

        else:
            # It's too late, the shm file no longer exists. So we delete the
            # category.
            tup = (catkeyid,)
            conn.execute('''DELETE FROM CatKey
                         WHERE id = %s;''', tup)


def pwchnge_new_cryptohash(conn, user_id, session_id, changed_pass):
    # I need to generate the expires header. But to do
    # that I need to find out when it should expire by
    # looking up the session.
    import time

    tup = (session_id, user_id)
    conn.execute('''SELECT expires
                 FROM Session
                 WHERE id = %s
                 AND user_id = %s;''', tup)
    ans = conn.fetchall()

    expires = float(ans[0][0])

    exp_header = time.strftime("%a, %d %b %Y %T GMT",
                               time.gmtime(expires)
                               )

    # Their new cryptohash cookie
    return [('Set-Cookie', 'cryptohash=' + changed_pass +
             '; expires=' + exp_header +
             '; path=/; Secure; HttpOnly')]

Changes to taskenizer/mini_pages/ac_deletion.py.

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
            except KeyError:
                raise ValueError("An error has occured.")

            # Passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = ?''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))
            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')

            from cryptography.hazmat.primitives import hashes







|







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
            except KeyError:
                raise ValueError("An error has occured.")

            # Passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = %s''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))
            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')

            from cryptography.hazmat.primitives import hashes

Changes to taskenizer/mini_pages/defer_task_page.py.

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
...
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

            break

    # Find out what category this task belongs to
    tup = (task_id,)
    conn.execute('''SELECT cat_id
                 FROM %s
                 WHERE id = ?;''' % cat_type, tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, task_type, cat_id)

    if fern is None:
        return_value += '<p>Category access denied</p>'
................................................................................
            if re.search('^taskid_', key):
                # The template needs an ID, color and a text content
                task_id = form[key].value

                tup = (task_id,)
                conn.execute('''SELECT id, color, name
                             FROM %s
                             WHERE id = ?;''' % cat_type, tup)

                entry = conn.fetchone()

                tasks += [entry]

        # Decrypt the names
        tasks = [[elem[0], elem[1], crypto.decrypt_name(







|







 







|







57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
...
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

            break

    # Find out what category this task belongs to
    tup = (task_id,)
    conn.execute('''SELECT cat_id
                 FROM %s
                 WHERE id = %%s;''' % cat_type, tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, task_type, cat_id)

    if fern is None:
        return_value += '<p>Category access denied</p>'
................................................................................
            if re.search('^taskid_', key):
                # The template needs an ID, color and a text content
                task_id = form[key].value

                tup = (task_id,)
                conn.execute('''SELECT id, color, name
                             FROM %s
                             WHERE id = %%s;''' % cat_type, tup)

                entry = conn.fetchone()

                tasks += [entry]

        # Decrypt the names
        tasks = [[elem[0], elem[1], crypto.decrypt_name(

Changes to taskenizer/mini_pages/del_other.py.

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
..
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
            except KeyError:
                raise ValueError("An error has occured.")

            # Current passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = ?;''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))
            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')

            from cryptography.hazmat.primitives import hashes
................................................................................

            tup = (
                user_id,
                session_id
            )

            conn.execute('''DELETE FROM Session
                         WHERE user_id = ?
                         AND id != ?;''', tup)

            # Here i will display the confirmation page
            return_value += display.bottom_of_header(conn, environ, templates,
                                                     'Logout other devices',
                                                     '', '', user_id, False,
                                                     'dummy', conf,
                                                     javascript_name,







|







 







|
|







38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
..
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
            except KeyError:
                raise ValueError("An error has occured.")

            # Current passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = %s;''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))
            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')

            from cryptography.hazmat.primitives import hashes
................................................................................

            tup = (
                user_id,
                session_id
            )

            conn.execute('''DELETE FROM Session
                         WHERE user_id = %s
                         AND id != %s;''', tup)

            # Here i will display the confirmation page
            return_value += display.bottom_of_header(conn, environ, templates,
                                                     'Logout other devices',
                                                     '', '', user_id, False,
                                                     'dummy', conf,
                                                     javascript_name,

Changes to taskenizer/mini_pages/modify_auto_habit_page.py.

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

            break

    # Find out what category this habit belongs to
    tup = (habit_id,)
    conn.execute('''SELECT cat_id
                 FROM AutoHabit
                 WHERE id = ?;''', tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)

    if fern is None:
        return_value += display.bottom_of_header(conn, environ, templates,
................................................................................
            # days, months, years, and a text content
            tasid = form[key].value

            tup = (tasid,)
            conn.execute('''SELECT id, freq, freq_units,
                         due_days, due_months, due_years, name
                         FROM AutoHabit
                         WHERE id = ?;''', tup)

            entry = conn.fetchone()

            habits += [[entry[0], entry[1], entry[2], entry[3],
                        entry[4], entry[5], crypto.decrypt_name(entry[6], fern)]]

    return_value += templates['modify_auto_habit'].render(







|







 







|







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
...
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

            break

    # Find out what category this habit belongs to
    tup = (habit_id,)
    conn.execute('''SELECT cat_id
                 FROM AutoHabit
                 WHERE id = %s;''', tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)

    if fern is None:
        return_value += display.bottom_of_header(conn, environ, templates,
................................................................................
            # days, months, years, and a text content
            tasid = form[key].value

            tup = (tasid,)
            conn.execute('''SELECT id, freq, freq_units,
                         due_days, due_months, due_years, name
                         FROM AutoHabit
                         WHERE id = %s;''', tup)

            entry = conn.fetchone()

            habits += [[entry[0], entry[1], entry[2], entry[3],
                        entry[4], entry[5], crypto.decrypt_name(entry[6], fern)]]

    return_value += templates['modify_auto_habit'].render(

Changes to taskenizer/mini_pages/modify_biscuit_page.py.

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

                    valid_items += [(e_new_name, biscuit_id, user_id)]

            # Only once all itnums have been sanity checked without
            # incident can we modify the biscuits.
            for item in valid_items:
                conn.execute('''UPDATE Biscuit
                             SET name = ?
                             WHERE id = ?
                             AND user_id = ?;''', item)

            # If the biscuits were modified sucessfully then we can exit
            # so that the normal page can be displayed.
            return 'nothing_printed'

        except ValueError as error:
            error_msg = error.args[0]
................................................................................
            # The template needs an ID, color and a text content
            biscuit_id = form[key].value

            tup = (biscuit_id, user_id)
            # Find out the name
            conn.execute('''SELECT id, color, name
                         FROM Biscuit
                         WHERE id = ?
                         AND user_id = ?;''', tup)

            entry = conn.fetchone()

            biscuits += [entry]

    # Decrypt the names
    biscuits = [[elem[0], elem[1], crypto.decrypt_name(







|
|
|







 







|
|







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

                    valid_items += [(e_new_name, biscuit_id, user_id)]

            # Only once all itnums have been sanity checked without
            # incident can we modify the biscuits.
            for item in valid_items:
                conn.execute('''UPDATE Biscuit
                             SET name = %s
                             WHERE id = %s
                             AND user_id = %s;''', item)

            # If the biscuits were modified sucessfully then we can exit
            # so that the normal page can be displayed.
            return 'nothing_printed'

        except ValueError as error:
            error_msg = error.args[0]
................................................................................
            # The template needs an ID, color and a text content
            biscuit_id = form[key].value

            tup = (biscuit_id, user_id)
            # Find out the name
            conn.execute('''SELECT id, color, name
                         FROM Biscuit
                         WHERE id = %s
                         AND user_id = %s;''', tup)

            entry = conn.fetchone()

            biscuits += [entry]

    # Decrypt the names
    biscuits = [[elem[0], elem[1], crypto.decrypt_name(

Changes to taskenizer/mini_pages/modify_manu_habit_page.py.

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
..
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

            break

    # Find out what category this habit belongs to
    tup = (habit_id,)
    conn.execute('''SELECT cat_id
                 FROM ManuHabit
                 WHERE id = ?;''', tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)

    if fern is None:
        return_value += display.bottom_of_header(conn, environ, templates,
................................................................................
            # The template needs an ID, frequency, due, and
            # a text content
            tasid = form[key].value

            tup = (tasid,)
            conn.execute('''SELECT id, freq, due, name
                         FROM ManuHabit
                         WHERE id = ?;''', tup)

            entry = conn.fetchone()

            habits += [[entry[0], entry[1], entry[2],
                        crypto.decrypt_name(entry[3], fern)]]

    return_value += templates['modify_manu_habit'].render(







|







 







|







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
..
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

            break

    # Find out what category this habit belongs to
    tup = (habit_id,)
    conn.execute('''SELECT cat_id
                 FROM ManuHabit
                 WHERE id = %s;''', tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)

    if fern is None:
        return_value += display.bottom_of_header(conn, environ, templates,
................................................................................
            # The template needs an ID, frequency, due, and
            # a text content
            tasid = form[key].value

            tup = (tasid,)
            conn.execute('''SELECT id, freq, due, name
                         FROM ManuHabit
                         WHERE id = %s;''', tup)

            entry = conn.fetchone()

            habits += [[entry[0], entry[1], entry[2],
                        crypto.decrypt_name(entry[3], fern)]]

    return_value += templates['modify_manu_habit'].render(

Changes to taskenizer/mini_pages/modify_note_page.py.

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
..
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
...
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

            break

    # Find out what category this note belongs to
    tup = (note_id,)
    conn.execute('''SELECT cat_id
                 FROM Note
                 WHERE id = ?;''', tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0, cat_id)

    if fern is None:
        return_value += '<p>Category access denied</p>'
................................................................................

                        valid_items += [(e_new_name, note_id)]

                # Only once all itnums have been sanity checked without
                # incident can we modify the notes.
                for item in valid_items:
                    conn.execute('''UPDATE Note
                                 SET name = ?
                                 WHERE id = ?;''', item)

                operations.inc_change_num(conn, 0, cat_id, None)

                # If the notes were modified sucessfully then we can exit
                # so that the normal page can be displayed.
                return 'nothing_printed'

................................................................................
                # The template needs an ID, color and a text content
                note_id = form[key].value

                tup = (note_id,)
                # Find out the name
                conn.execute('''SELECT id, color, name
                             FROM Note
                             WHERE id = ?;''', tup)

                entry = conn.fetchone()

                notes += [entry]

        # Decrypt the names
        notes = [[elem[0], elem[1], crypto.decrypt_name(







|







 







|
|







 







|







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
..
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
...
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

            break

    # Find out what category this note belongs to
    tup = (note_id,)
    conn.execute('''SELECT cat_id
                 FROM Note
                 WHERE id = %s;''', tup)
    entry = conn.fetchone()
    cat_id = entry[0]

    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0, cat_id)

    if fern is None:
        return_value += '<p>Category access denied</p>'
................................................................................

                        valid_items += [(e_new_name, note_id)]

                # Only once all itnums have been sanity checked without
                # incident can we modify the notes.
                for item in valid_items:
                    conn.execute('''UPDATE Note
                                 SET name = %s
                                 WHERE id = %s;''', item)

                operations.inc_change_num(conn, 0, cat_id, None)

                # If the notes were modified sucessfully then we can exit
                # so that the normal page can be displayed.
                return 'nothing_printed'

................................................................................
                # The template needs an ID, color and a text content
                note_id = form[key].value

                tup = (note_id,)
                # Find out the name
                conn.execute('''SELECT id, color, name
                             FROM Note
                             WHERE id = %s;''', tup)

                entry = conn.fetchone()

                notes += [entry]

        # Decrypt the names
        notes = [[elem[0], elem[1], crypto.decrypt_name(

Changes to taskenizer/mini_pages/modify_pass.py.

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
...
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
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
...
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
            if np1 != np2:
                raise ValueError("Passphrases do no match.")

            # Current passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = ?''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))

            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')
            from cryptography.hazmat.primitives import hashes
................................................................................
                store_pass_salt,
                passhash,
                store_cryp_salt,
                user_id
            )

            conn.execute('''UPDATE User
                         SET salt = ?, passhash = ?, cryptsalt = ?
                         WHERE id = ?''', tup)

            # Now we must re-encrypt all of the category keys using
            # the new passphrase

            # Get every catkey entry
            tup = (user_id,)
            conn.execute('''SELECT id, iv, key
                         FROM CatKey
                         WHERE user_id = ?;''', tup)

            # For every CatKey entry:
            for catkey in conn.fetchall():
                catkey_id = catkey[0]
                cur_iv = catkey[1]
                key = catkey[2]

................................................................................

                token = encryptor.update(catkey) + encryptor.finalize()

                # OK good so now we have the iv and encrypted
                # key. Now we write it to the database.
                tup = (cat_iv, token, user_id, catkey_id)
                conn.execute('''UPDATE CatKey
                             SET iv = ?, key = ?
                             WHERE user_id = ?
                             AND id = ?;''', tup)

            # Time to re-encrypt their biscuit key

            # I need to find out the biscuits iv and key
            tup = (user_id,)
            conn.execute('''SELECT biscuits_iv, biscuits_key
                         FROM User
                         WHERE id = ?;''', tup)
            ans = conn.fetchone()
            biscuits_iv = ans[0]
            biscuits_key = ans[1]

            # De-crypt the fernet key using AES. Here we
            # are using the old cryptohash and the old iv.
            backend = default_backend()
................................................................................
            token = encryptor.update(bicy_key) + encryptor.finalize()

            # OK good so now we have the iv and encrypted
            # key. Now we write it to the database.

            tup = (new_bicy_iv, token, user_id)
            conn.execute('''UPDATE User
                         SET biscuits_iv = ?, biscuits_key = ?
                         WHERE id = ?;''', tup)

            # Now log out all other devices, as their encrption keys
            # are now invalid.
            tup = (
                user_id,
                session_id
            )

            conn.execute('''DELETE FROM Session
                         WHERE user_id = ?
                         AND id != ?;''', tup)

            # Here i will display the confirmation page
            return_value += display.bottom_of_header(conn, environ, templates,
                                                     'Modify passphrase', '',
                                                     '', user_id, False,
                                                     'dummy', conf,
                                                     javascript_name,







|







 







|
|






|

|







 







|
|
|







|







 







|
|









|
|







58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
...
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
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
...
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
            if np1 != np2:
                raise ValueError("Passphrases do no match.")

            # Current passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = %s''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))

            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')
            from cryptography.hazmat.primitives import hashes
................................................................................
                store_pass_salt,
                passhash,
                store_cryp_salt,
                user_id
            )

            conn.execute('''UPDATE User
                         SET salt = %s, passhash = %s, cryptsalt = %s
                         WHERE id = %s''', tup)

            # Now we must re-encrypt all of the category keys using
            # the new passphrase

            # Get every catkey entry
            tup = (user_id,)
            conn.execute('''SELECT id, iv, thekey
                         FROM CatKey
                         WHERE user_id = %s;''', tup)

            # For every CatKey entry:
            for catkey in conn.fetchall():
                catkey_id = catkey[0]
                cur_iv = catkey[1]
                key = catkey[2]

................................................................................

                token = encryptor.update(catkey) + encryptor.finalize()

                # OK good so now we have the iv and encrypted
                # key. Now we write it to the database.
                tup = (cat_iv, token, user_id, catkey_id)
                conn.execute('''UPDATE CatKey
                             SET iv = %s, thekey = %s
                             WHERE user_id = %s
                             AND id = %s;''', tup)

            # Time to re-encrypt their biscuit key

            # I need to find out the biscuits iv and key
            tup = (user_id,)
            conn.execute('''SELECT biscuits_iv, biscuits_key
                         FROM User
                         WHERE id = %s;''', tup)
            ans = conn.fetchone()
            biscuits_iv = ans[0]
            biscuits_key = ans[1]

            # De-crypt the fernet key using AES. Here we
            # are using the old cryptohash and the old iv.
            backend = default_backend()
................................................................................
            token = encryptor.update(bicy_key) + encryptor.finalize()

            # OK good so now we have the iv and encrypted
            # key. Now we write it to the database.

            tup = (new_bicy_iv, token, user_id)
            conn.execute('''UPDATE User
                         SET biscuits_iv = %s, biscuits_key = %s
                         WHERE id = %s;''', tup)

            # Now log out all other devices, as their encrption keys
            # are now invalid.
            tup = (
                user_id,
                session_id
            )

            conn.execute('''DELETE FROM Session
                         WHERE user_id = %s
                         AND id != %s;''', tup)

            # Here i will display the confirmation page
            return_value += display.bottom_of_header(conn, environ, templates,
                                                     'Modify passphrase', '',
                                                     '', user_id, False,
                                                     'dummy', conf,
                                                     javascript_name,

Changes to taskenizer/mini_pages/modify_username.py.

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
..
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
            if user == '':
                raise ValueError("Can't have a blank username.")
            if re.search('@', user):
                raise ValueError("Username may not contain `@' symbols.")
            tup = (user,)
            conn.execute('''SELECT COUNT(*)
                         FROM User
                         WHERE username = ?''', tup)
            if conn.fetchone()[0] > 0:
                raise ValueError("That username is already in use.")

            # Passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = ?''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))
            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')

            from cryptography.hazmat.primitives import hashes
................................................................................
            if passhash != correcthash:
                raise ValueError("Incorrect passphrase.")

            # Well, all the sanity checks passed so we can now change
            # their username :)
            tup = (user, user_id)
            conn.execute('''UPDATE User
                         SET username = ?
                         WHERE id = ?''', tup)

            # If the username was modified sucessfully then we can exit
            # so that the normal page can be displayed.
            return 'nothing_printed'

        except ValueError as error:
            error_msg = error.args[0]







|







|







 







|
|







48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
..
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
            if user == '':
                raise ValueError("Can't have a blank username.")
            if re.search('@', user):
                raise ValueError("Username may not contain `@' symbols.")
            tup = (user,)
            conn.execute('''SELECT COUNT(*)
                         FROM User
                         WHERE username = %s''', tup)
            if conn.fetchone()[0] > 0:
                raise ValueError("That username is already in use.")

            # Passphrase check
            tup = (user_id,)
            conn.execute('''SELECT passhash, salt
                         FROM User
                         WHERE id = %s''', tup)
            ans = conn.fetchone()
            correcthash = ans[0]
            salt = base64.b64decode(ans[1].encode('ASCII'))
            # The passphrase will be utf-8 encoded before being hashed
            enc_passw = passw.encode('utf-8')

            from cryptography.hazmat.primitives import hashes
................................................................................
            if passhash != correcthash:
                raise ValueError("Incorrect passphrase.")

            # Well, all the sanity checks passed so we can now change
            # their username :)
            tup = (user, user_id)
            conn.execute('''UPDATE User
                         SET username = %s
                         WHERE id = %s''', tup)

            # If the username was modified sucessfully then we can exit
            # so that the normal page can be displayed.
            return 'nothing_printed'

        except ValueError as error:
            error_msg = error.args[0]

Changes to taskenizer/mini_pages/move_page.py.

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
...
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
...
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
...
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
...
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
...
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
                    if fern is None:
                        raise ValueError("Category access denied.")

                    # Now we get the habit
                    tup = (tasid,)
                    conn.execute('''SELECT name
                                 FROM AutoHabit
                                 WHERE id = ?;''', tup)
                    rows = conn.fetchall()

                    name = crypto.decrypt_name(rows[0][0], fern)

                    # Encrypt the name with the new category's key.
                    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1,
                                               form["new-category"].value)
................................................................................
                    # I need to generate a new id because tasks are
                    # ordered by their id.
                    new_id = operations.genid(cur_time)

                    tup = (new_id, form["new-category"].value, new_coding, tasid)

                    conn.execute('''UPDATE AutoHabit
                                 SET id = ?, cat_id = ?, name = ?
                                 WHERE id = ?;''', tup)

                    operations.inc_change_num(conn, 1, cur_cat, None)
                    operations.inc_change_num(conn, 1, form["new-category"].value,
                                              None)

                elif task_type == 'manu_habit':
                    # I need to get the key for this category
................................................................................
                    if fern is None:
                        raise ValueError("Category access denied.")

                    # Now we get the habit
                    tup = (tasid,)
                    conn.execute('''SELECT name
                                 FROM ManuHabit
                                 WHERE id = ?;''', tup)
                    rows = conn.fetchall()

                    name = crypto.decrypt_name(rows[0][0], fern)

                    # Encrypt the name with the new category's key.
                    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2,
                                               form["new-category"].value)
................................................................................
                    # I need to generate a new id because tasks are
                    # ordered by their id.
                    new_id = operations.genid(cur_time)

                    tup = (new_id, form["new-category"].value, new_coding, tasid)

                    conn.execute('''UPDATE ManuHabit
                                 SET id = ?, cat_id = ?, name = ?
                                 WHERE id = ?;''', tup)

                    operations.inc_change_num(conn, 2, cur_cat, None)
                    operations.inc_change_num(
                        conn, 2, form["new-category"].value, None)

                elif task_type == 'note':
                    # I need to get the key for this category
................................................................................
                    if fern is None:
                        raise ValueError("Category access denied.")

                    # Now we get the note
                    tup = (tasid,)
                    conn.execute('''SELECT name
                                 FROM Note
                                 WHERE id = ?;''', tup)
                    rows = conn.fetchall()

                    name = crypto.decrypt_name(rows[0][0], fern)

                    # If the destination is Biscuits then we follow a
                    # different code path
                    if form["new-category"].value == "666":
................................................................................
                            color,
                            nom,
                            timestamp,
                            user_id,
                        )
                        conn.execute('''INSERT INTO Biscuit (id,
                                        color, name, timestamp, user_id)
                                        VALUES (?, ?, ?, ?, ?)''', tup)

                        # OK now we must delete the note
                        if operations.check_perm_task(conn, tasid, 0, user_id):
                            tup = (tasid,)
                            conn.execute('''DELETE FROM Note
                                            WHERE id = ?;''', tup)

                            operations.inc_change_num(conn, 0, cur_cat, None)

                    else:
                        # Encrypt the name with the new category's key.
                        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0,
                                                      form["new-category"].value)
................................................................................
                        # I need to generate a new id because tasks are
                        # ordered by their id.
                        new_id = operations.genid(cur_time)

                        tup = (new_id, form["new-category"].value, new_coding, tasid)

                        conn.execute('''UPDATE Note
                                        SET id = ?, cat_id = ?, name = ?
                                        WHERE id = ?;''', tup)

                        operations.inc_change_num(conn, 0, cur_cat, None)
                        operations.inc_change_num(conn, 0, form["new-category"].value,
                                                  None)

            # If the tasks were moved sucessfully then we can exit
            # so that the normal page can be displayed.
................................................................................
    # The template needs a list of all categories of the same task-type
    cats = []

    if task_type == 'auto_habit':
        tup = (1, user_id)
        conn.execute('''SELECT cat_id
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?
                     ORDER BY id ASC;''', tup)
        selected = conn.fetchall()

        for tup in selected:
            conn.execute('''SELECT id, name
                         FROM AutoHabitCat
                         WHERE id = ?;''', tup)

            cats += conn.fetchall()

    elif task_type == 'manu_habit':
        tup = (2, user_id)
        conn.execute('''SELECT cat_id
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?
                     ORDER BY id ASC;''', tup)
        selected = conn.fetchall()

        for tup in selected:
            conn.execute('''SELECT id, name
                         FROM ManuHabitCat
                         WHERE id = ?;''', tup)

            cats += conn.fetchall()

    elif task_type == 'note':
        tup = (0, user_id)
        conn.execute('''SELECT cat_id
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?
                     ORDER BY id ASC;''', tup)
        selected = conn.fetchall()

        for tup in selected:
            conn.execute('''SELECT id, name
                         FROM NoteCat
                         WHERE id = ?;''', tup)

            cats += conn.fetchall()

        # Are biscuits enabled?
        tup = (user_id,)
        conn.execute('''SELECT biscuits_enabled
                        FROM User
                        WHERE id = ?;''', tup)
        b_enabled = conn.fetchall()[0][0]

        # Biscuits are enabled so biscuits is a possible destination
        if b_enabled:
            cats += ((666, "Biscuits"),)

    return_value += templates['move'].render(







|







 







|
|







 







|







 







|
|







 







|







 







|





|







 







|
|







 







|
|






|







|
|






|







|
|






|







|







82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
...
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
...
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
...
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
...
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
...
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
                    if fern is None:
                        raise ValueError("Category access denied.")

                    # Now we get the habit
                    tup = (tasid,)
                    conn.execute('''SELECT name
                                 FROM AutoHabit
                                 WHERE id = %s;''', tup)
                    rows = conn.fetchall()

                    name = crypto.decrypt_name(rows[0][0], fern)

                    # Encrypt the name with the new category's key.
                    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1,
                                               form["new-category"].value)
................................................................................
                    # I need to generate a new id because tasks are
                    # ordered by their id.
                    new_id = operations.genid(cur_time)

                    tup = (new_id, form["new-category"].value, new_coding, tasid)

                    conn.execute('''UPDATE AutoHabit
                                 SET id = %s, cat_id = %s, name = %s
                                 WHERE id = %s;''', tup)

                    operations.inc_change_num(conn, 1, cur_cat, None)
                    operations.inc_change_num(conn, 1, form["new-category"].value,
                                              None)

                elif task_type == 'manu_habit':
                    # I need to get the key for this category
................................................................................
                    if fern is None:
                        raise ValueError("Category access denied.")

                    # Now we get the habit
                    tup = (tasid,)
                    conn.execute('''SELECT name
                                 FROM ManuHabit
                                 WHERE id = %s;''', tup)
                    rows = conn.fetchall()

                    name = crypto.decrypt_name(rows[0][0], fern)

                    # Encrypt the name with the new category's key.
                    fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2,
                                               form["new-category"].value)
................................................................................
                    # I need to generate a new id because tasks are
                    # ordered by their id.
                    new_id = operations.genid(cur_time)

                    tup = (new_id, form["new-category"].value, new_coding, tasid)

                    conn.execute('''UPDATE ManuHabit
                                 SET id = %s, cat_id = %s, name = %s
                                 WHERE id = %s;''', tup)

                    operations.inc_change_num(conn, 2, cur_cat, None)
                    operations.inc_change_num(
                        conn, 2, form["new-category"].value, None)

                elif task_type == 'note':
                    # I need to get the key for this category
................................................................................
                    if fern is None:
                        raise ValueError("Category access denied.")

                    # Now we get the note
                    tup = (tasid,)
                    conn.execute('''SELECT name
                                 FROM Note
                                 WHERE id = %s;''', tup)
                    rows = conn.fetchall()

                    name = crypto.decrypt_name(rows[0][0], fern)

                    # If the destination is Biscuits then we follow a
                    # different code path
                    if form["new-category"].value == "666":
................................................................................
                            color,
                            nom,
                            timestamp,
                            user_id,
                        )
                        conn.execute('''INSERT INTO Biscuit (id,
                                        color, name, timestamp, user_id)
                                        VALUES (%s, %s, %s, %s, %s)''', tup)

                        # OK now we must delete the note
                        if operations.check_perm_task(conn, tasid, 0, user_id):
                            tup = (tasid,)
                            conn.execute('''DELETE FROM Note
                                            WHERE id = %s;''', tup)

                            operations.inc_change_num(conn, 0, cur_cat, None)

                    else:
                        # Encrypt the name with the new category's key.
                        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0,
                                                      form["new-category"].value)
................................................................................
                        # I need to generate a new id because tasks are
                        # ordered by their id.
                        new_id = operations.genid(cur_time)

                        tup = (new_id, form["new-category"].value, new_coding, tasid)

                        conn.execute('''UPDATE Note
                                        SET id = %s, cat_id = %s, name = %s
                                        WHERE id = %s;''', tup)

                        operations.inc_change_num(conn, 0, cur_cat, None)
                        operations.inc_change_num(conn, 0, form["new-category"].value,
                                                  None)

            # If the tasks were moved sucessfully then we can exit
            # so that the normal page can be displayed.
................................................................................
    # The template needs a list of all categories of the same task-type
    cats = []

    if task_type == 'auto_habit':
        tup = (1, user_id)
        conn.execute('''SELECT cat_id
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s
                     ORDER BY id ASC;''', tup)
        selected = conn.fetchall()

        for tup in selected:
            conn.execute('''SELECT id, name
                         FROM AutoHabitCat
                         WHERE id = %s;''', tup)

            cats += conn.fetchall()

    elif task_type == 'manu_habit':
        tup = (2, user_id)
        conn.execute('''SELECT cat_id
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s
                     ORDER BY id ASC;''', tup)
        selected = conn.fetchall()

        for tup in selected:
            conn.execute('''SELECT id, name
                         FROM ManuHabitCat
                         WHERE id = %s;''', tup)

            cats += conn.fetchall()

    elif task_type == 'note':
        tup = (0, user_id)
        conn.execute('''SELECT cat_id
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s
                     ORDER BY id ASC;''', tup)
        selected = conn.fetchall()

        for tup in selected:
            conn.execute('''SELECT id, name
                         FROM NoteCat
                         WHERE id = %s;''', tup)

            cats += conn.fetchall()

        # Are biscuits enabled?
        tup = (user_id,)
        conn.execute('''SELECT biscuits_enabled
                        FROM User
                        WHERE id = %s;''', tup)
        b_enabled = conn.fetchall()[0][0]

        # Biscuits are enabled so biscuits is a possible destination
        if b_enabled:
            cats += ((666, "Biscuits"),)

    return_value += templates['move'].render(

Changes to taskenizer/mini_pages/share_cat.py.

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
..
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
...
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
...
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
...
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
            except KeyError:
                no_other_user_pass = 'no'

            # Check the username exists
            tup = (username,)
            conn.execute('''SELECT id
                         FROM User
                         WHERE username = ?;''', tup)

            try:
                their_user_id = conn.fetchone()[0]
            except Exception:
                raise ValueError("No such user exists.")

            # Our passphrase check
................................................................................
                raise ValueError("Your passphrase incorrect.")

            if no_other_user_pass == 'no':
                # Their passphrase check
                tup = (their_user_id,)
                conn.execute('''SELECT passhash, salt
                             FROM User
                             WHERE id = ?;''', tup)
                ans = conn.fetchone()
                correcthash = ans[0]
                salt = base64.b64decode(ans[1].encode('ASCII'))
                # The passphrase will be utf-8 encoded before being hashed
                enc_their_pass = their_pass.encode('utf-8')

                from cryptography.hazmat.primitives import hashes
................................................................................
                    raise ValueError("Their passphrase incorrect.")

            # Check that this category hasn't already been shared with
            # this user.
            tup = (cat_type, cat_id, their_user_id)
            conn.execute('''SELECT COUNT(*)
                         FROM CatKey
                         WHERE task_type = ?
                         AND cat_id = ?
                         AND user_id = ?;''', tup)

            if conn.fetchone()[0] > 0:
                raise ValueError("This category is already shared with this "
                                 "user.")

            # Well, all the sanity checks passed so we can now share
            # the category :)

            # Decrypt the catkey
            tup = (cat_type, str(cat_id), user_id)
            conn.execute('''SELECT iv, key
                         FROM CatKey
                         WHERE task_type = ?
                         AND cat_id = ?
                         AND user_id = ?;''', tup)
            ans = conn.fetchall()

            if len(ans) == 0:
                raise ValueError("An error has occured (can't get key).")
            else:
                cur_iv = ans[0][0]
                key = ans[0][1]
................................................................................

            if no_other_user_pass == 'no':
                # Find out their cryptohash
                tup = (their_user_id,)

                conn.execute('''SELECT cryptsalt
                             FROM User
                             WHERE id = ?;''', tup)

                ans = conn.fetchone()
                cryptsalt = base64.b64decode(ans[0].encode('ASCII'))

                cryptopass = their_pass.encode('utf-8')

                from cryptography.hazmat.primitives import hashes
................................................................................
                # Put the key in it.
                with open(connected, 'wt', encoding='utf-8') as a_file:
                    a_file.write(cryptokey.decode('utf-8'))

            # We add an entry to the `CatKey' table.
            tup = (connected, token, cat_iv, cat_type, cat_id, their_user_id)
            conn.execute('''INSERT INTO CatKey (connected,
                                             key,
                                             iv,
                                             task_type,
                                             cat_id,
                                             user_id)
                         VALUES (?, ?, ?, ?, ?, ?);''', tup)

            # Add a notification for the user.

            # We need to find out the date in the other user's timezone.
            their_date = operations.find_time(conn,
                                              their_user_id,
                                              cur_time,
................................................................................
                                              '%Y-%m-%d'
                                              )

            if no_other_user_pass == 'no':
                tup = (their_date + conf['Cosmetic']['new_shared_text'],
                     their_user_id)
                conn.execute('''INSERT INTO Notification (name, user_id)
                             VALUES (?, ?);''', tup)

            # If the category was shared sucessfully then we can exit
            # so that the normal page can be displayed.
            return 'nothing_printed'

        except ValueError as error:
            error_msg = error.args[0]
................................................................................
        cat_type_name = ('AutoHabitCat', 'auto-habit', 'auto', 'auto_habit')
    elif cat_type == 2:
        cat_type_name = ('ManuHabitCat', 'manual-habit', 'manu', 'manu_habit')

    tup = (cat_id,)
    conn.execute('''SELECT name
                 FROM %s
                 WHERE id = ?;''' % cat_type_name[0], tup)

    cat_name = conn.fetchone()[0]

    return_value += templates['share_cat'].render(
        error_msg=error_msg,
        request_uri=environ['REQUEST_URI'],
        cat_id=cat_id,







|







 







|







 







|
|
|










|

|
|
|







 







|







 







|




|







 







|







 







|







58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
..
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
...
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
...
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
...
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
            except KeyError:
                no_other_user_pass = 'no'

            # Check the username exists
            tup = (username,)
            conn.execute('''SELECT id
                         FROM User
                         WHERE username = %s;''', tup)

            try:
                their_user_id = conn.fetchone()[0]
            except Exception:
                raise ValueError("No such user exists.")

            # Our passphrase check
................................................................................
                raise ValueError("Your passphrase incorrect.")

            if no_other_user_pass == 'no':
                # Their passphrase check
                tup = (their_user_id,)
                conn.execute('''SELECT passhash, salt
                             FROM User
                             WHERE id = %s;''', tup)
                ans = conn.fetchone()
                correcthash = ans[0]
                salt = base64.b64decode(ans[1].encode('ASCII'))
                # The passphrase will be utf-8 encoded before being hashed
                enc_their_pass = their_pass.encode('utf-8')

                from cryptography.hazmat.primitives import hashes
................................................................................
                    raise ValueError("Their passphrase incorrect.")

            # Check that this category hasn't already been shared with
            # this user.
            tup = (cat_type, cat_id, their_user_id)
            conn.execute('''SELECT COUNT(*)
                         FROM CatKey
                         WHERE task_type = %s
                         AND cat_id = %s
                         AND user_id = %s;''', tup)

            if conn.fetchone()[0] > 0:
                raise ValueError("This category is already shared with this "
                                 "user.")

            # Well, all the sanity checks passed so we can now share
            # the category :)

            # Decrypt the catkey
            tup = (cat_type, str(cat_id), user_id)
            conn.execute('''SELECT iv, thekey
                         FROM CatKey
                         WHERE task_type = %s
                         AND cat_id = %s
                         AND user_id = %s;''', tup)
            ans = conn.fetchall()

            if len(ans) == 0:
                raise ValueError("An error has occured (can't get key).")
            else:
                cur_iv = ans[0][0]
                key = ans[0][1]
................................................................................

            if no_other_user_pass == 'no':
                # Find out their cryptohash
                tup = (their_user_id,)

                conn.execute('''SELECT cryptsalt
                             FROM User
                             WHERE id = %s;''', tup)

                ans = conn.fetchone()
                cryptsalt = base64.b64decode(ans[0].encode('ASCII'))

                cryptopass = their_pass.encode('utf-8')

                from cryptography.hazmat.primitives import hashes
................................................................................
                # Put the key in it.
                with open(connected, 'wt', encoding='utf-8') as a_file:
                    a_file.write(cryptokey.decode('utf-8'))

            # We add an entry to the `CatKey' table.
            tup = (connected, token, cat_iv, cat_type, cat_id, their_user_id)
            conn.execute('''INSERT INTO CatKey (connected,
                                             thekey,
                                             iv,
                                             task_type,
                                             cat_id,
                                             user_id)
                         VALUES (%s, %s, %s, %s, %s, %s);''', tup)

            # Add a notification for the user.

            # We need to find out the date in the other user's timezone.
            their_date = operations.find_time(conn,
                                              their_user_id,
                                              cur_time,
................................................................................
                                              '%Y-%m-%d'
                                              )

            if no_other_user_pass == 'no':
                tup = (their_date + conf['Cosmetic']['new_shared_text'],
                     their_user_id)
                conn.execute('''INSERT INTO Notification (name, user_id)
                             VALUES (%s, %s);''', tup)

            # If the category was shared sucessfully then we can exit
            # so that the normal page can be displayed.
            return 'nothing_printed'

        except ValueError as error:
            error_msg = error.args[0]
................................................................................
        cat_type_name = ('AutoHabitCat', 'auto-habit', 'auto', 'auto_habit')
    elif cat_type == 2:
        cat_type_name = ('ManuHabitCat', 'manual-habit', 'manu', 'manu_habit')

    tup = (cat_id,)
    conn.execute('''SELECT name
                 FROM %s
                 WHERE id = %%s;''' % cat_type_name[0], tup)

    cat_name = conn.fetchone()[0]

    return_value += templates['share_cat'].render(
        error_msg=error_msg,
        request_uri=environ['REQUEST_URI'],
        cat_id=cat_id,

Changes to taskenizer/pages/auto_habits.py.

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
                                             conf, javascript_name,
                                             themeinfo['activetheme'])

    # Make a list of all note categories this user has access to.
    tup = (1, user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = ?
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    cats = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM AutoHabitCat
                     WHERE id = ?;''', tup)
        cats += conn.fetchall()

    for cat in cats:
        cat_id = cat[0]
        cat_name = cat[1]

        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)
................................................................................
        else:
            # We decide whether to display move buttons or
            # not. There's no point of displaying them if there's
            # only one category.
            tup = (1, user_id,)
            conn.execute('''SELECT COUNT(*)
                         FROM CatKey
                         WHERE task_type = ?
                         AND user_id = ?;''', tup)
            num_cats = conn.fetchone()

            tup = (cat_id,)
            conn.execute('''SELECT id, name, freq, freq_units,
                         due_days, due_months, due_years, color
                         FROM AutoHabit
                         WHERE cat_id = ?
                         ORDER BY id ASC;''', tup)
            habits = conn.fetchall()

            # Decrypt the names
            habits = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[3], elem[
                4], elem[5], elem[6], elem[7]] for elem in habits]








|
|






|







 







|
|






|







29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
                                             conf, javascript_name,
                                             themeinfo['activetheme'])

    # Make a list of all note categories this user has access to.
    tup = (1, user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = %s
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    cats = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM AutoHabitCat
                     WHERE id = %s;''', tup)
        cats += conn.fetchall()

    for cat in cats:
        cat_id = cat[0]
        cat_name = cat[1]

        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)
................................................................................
        else:
            # We decide whether to display move buttons or
            # not. There's no point of displaying them if there's
            # only one category.
            tup = (1, user_id,)
            conn.execute('''SELECT COUNT(*)
                         FROM CatKey
                         WHERE task_type = %s
                         AND user_id = %s;''', tup)
            num_cats = conn.fetchone()

            tup = (cat_id,)
            conn.execute('''SELECT id, name, freq, freq_units,
                         due_days, due_months, due_years, color
                         FROM AutoHabit
                         WHERE cat_id = %s
                         ORDER BY id ASC;''', tup)
            habits = conn.fetchall()

            # Decrypt the names
            habits = [[elem[0], crypto.decrypt_name(elem[1], fern), elem[2], elem[3], elem[
                4], elem[5], elem[6], elem[7]] for elem in habits]

Changes to taskenizer/pages/biscuits.py.

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

    # We need to decide whether to display move buttons or
    # not. There's no point of displaying them if there's
    # only one category.
    tup = (0, user_id,)
    conn.execute('''SELECT COUNT(*)
                 FROM CatKey
                 WHERE task_type = ?
                 AND user_id = ?;''', tup)
    num_note_cats = conn.fetchone()

    # Now we get the biscuits
    tup = (user_id,)
    conn.execute('''SELECT id, color, name, timestamp
                 FROM Biscuit
                 WHERE user_id = ?
                 ORDER BY id DESC;''', tup)
    rows = conn.fetchall()

    # Decrypt the names
    rows = [[elem[0], elem[1], escape(crypto.decrypt_name(elem[2], fern)), elem[
        3]] for elem in rows]








|
|






|







35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

    # We need to decide whether to display move buttons or
    # not. There's no point of displaying them if there's
    # only one category.
    tup = (0, user_id,)
    conn.execute('''SELECT COUNT(*)
                 FROM CatKey
                 WHERE task_type = %s
                 AND user_id = %s;''', tup)
    num_note_cats = conn.fetchone()

    # Now we get the biscuits
    tup = (user_id,)
    conn.execute('''SELECT id, color, name, timestamp
                 FROM Biscuit
                 WHERE user_id = %s
                 ORDER BY id DESC;''', tup)
    rows = conn.fetchall()

    # Decrypt the names
    rows = [[elem[0], elem[1], escape(crypto.decrypt_name(elem[2], fern)), elem[
        3]] for elem in rows]

Changes to taskenizer/pages/configuration.py.

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
76
77
78
79
80
81
82
83
84
85
86
..
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
...
112
113
114
115
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
144
...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
...
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
...
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
...
246
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
...
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
                                             )

    # Get all note cats that this user has permission to access.
    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 0
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    note_cats_1 = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM NoteCat
                     WHERE id = ?;''', tup)
        note_cats_1 += conn.fetchall()

    note_cats = []

    # Find out if they are in use by any page (if not they may be
    # deleted) and if they are shared with any other users.
    for cat in note_cats_1:
................................................................................
        cat_id = cat[0]
        name = cat[1]

        tup = (cat_id, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM PageContent
                     WHERE entry_type=0
                     AND entry_id=?
                     AND user_id = ?;''', tup)
        num_cats = conn.fetchone()[0]

        tup = (cat_id,)
        conn.execute('''SELECT user_id
                     FROM CatKey
                     WHERE task_type = 0
                     AND cat_id = ?
                     ORDER BY id ASC;''', tup)
        userids = conn.fetchall()

        note_share_usernames = []

        for userid in userids:
            tup = (userid[0],)
            conn.execute('''SELECT username
                         FROM User
                         WHERE id = ?;''', tup)
            note_share_usernames += conn.fetchone()

        num_users = len(userids)

        if num_users > 3:
            num_users = 3

................................................................................
            note_cats += [[cat_id, name, 0, num_users, note_share_usernames]]

    # Get all auto-habit cats that this user has permission to access.
    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 1
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    auto_cats_1 = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM AutoHabitCat
                     WHERE id = ?;''', tup)
        auto_cats_1 += conn.fetchall()

    auto_cats = []

    # Find out if they are in use by any page (if not they may be
    # deleted) and if they are shared with any other users.
    for cat in auto_cats_1:
................................................................................
        cat_id = cat[0]
        name = cat[1]

        tup = (cat_id, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM PageContent
                     WHERE entry_type=1
                     AND entry_id = ?
                     AND user_id = ?;''', tup)
        num_cats = conn.fetchone()[0]

        tup = (cat_id,)
        conn.execute('''SELECT user_id
                     FROM CatKey
                     WHERE task_type = 1
                     AND cat_id = ?
                     ORDER BY id ASC;''', tup)
        userids = conn.fetchall()

        auto_share_usernames = []

        for userid in userids:
            tup = (userid[0],)
            conn.execute('''SELECT username
                         FROM User
                         WHERE id = ?''', tup)
            auto_share_usernames += conn.fetchone()

        num_users = len(userids)

        if num_users > 3:
            num_users = 3

................................................................................
            auto_cats += [[cat_id, name, 0, num_users, auto_share_usernames]]

    # Get all manu-habit cats that this user has permission to access.
    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 2
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    manu_cats_1 = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM ManuHabitCat
                     WHERE id = ?;''', tup)
        manu_cats_1 += conn.fetchall()

    manu_cats = []

    # Find out if they are in use by any page (if not they may be
    # deleted) and if they are shared with any other users.
    for cat in manu_cats_1:
................................................................................
        cat_id = cat[0]
        name = cat[1]

        tup = (cat_id, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM PageContent
                     WHERE entry_type=2
                     AND entry_id = ?
                     AND user_id = ?;''', tup)
        num_cats = conn.fetchone()[0]

        tup = (cat_id,)
        conn.execute('''SELECT user_id
                     FROM CatKey
                     WHERE task_type = 2
                     AND cat_id = ?
                     ORDER BY id ASC;''', tup)
        userids = conn.fetchall()

        manu_share_usernames = []

        for userid in userids:
            tup = (userid[0],)
            conn.execute('''SELECT username
                         FROM User
                         WHERE id = ?''', tup)
            manu_share_usernames += conn.fetchone()

        num_users = len(userids)

        if num_users > 3:
            num_users = 3

................................................................................
    # page_entry[2] = name
    uber_pages = []

    # Get all the pages
    tup = (user_id,)
    conn.execute('''SELECT id, name
                 FROM Page
                 WHERE user_id = ?
                 ORDER BY seq;''', tup)
    pages = conn.fetchall()

    # For each page, get all of the contents
    for page in pages:
        page_id = page[0]
        page_name = page[1]

        tup = (page_id, user_id)
        conn.execute("""SELECT id, entry_type, entry_id
                     FROM PageContent
                     WHERE page_id = ?
                     AND user_id = ?
                     ORDER BY seq;""", tup)
        contents = conn.fetchall()

        page_entries = []

        # For each content, get the category.
        for content in contents:
................................................................................
            entry_type = content[1]
            entry_id = content[2]

            tup = (entry_id,)
            if entry_type == 0:  # Note
                conn.execute("""SELECT name
                             FROM NoteCat
                             WHERE id = ?;""", tup)
                entry = conn.fetchone()
                page_entry = [cat_id, entry_id] + list(entry)
                page_entry[2] += ' notes'
            elif entry_type == 1:  # Auto-habit
                conn.execute("""SELECT name
                             FROM AutoHabitCat
                             WHERE id = ?;""", tup)
                entry = conn.fetchone()
                page_entry = [cat_id, entry_id] + list(entry)
                page_entry[2] += ' auto-habits'
            elif entry_type == 2:  # Manu-habit
                conn.execute("""SELECT name
                             FROM ManuHabitCat
                             WHERE id = ?;""", tup)
                entry = conn.fetchone()
                page_entry = [cat_id, entry_id] + list(entry)
                page_entry[2] += ' manu-habits'

            page_entries += [page_entry]

        uber_pages += [[page_id, page_name, page_entries]]
................................................................................

    all_cats = []

    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 0
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    for tup in conn.fetchall():
        conn.execute("""SELECT id, name
                     FROM NoteCat
                     WHERE id = ?""", tup)
        all_cats += [ruin_everything(elem, 'notes') for elem in conn.fetchall()]

    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 1
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    for tup in conn.fetchall():
        conn.execute("""SELECT id, name
                     FROM AutoHabitCat
                     WHERE id = ?""", tup)
        all_cats += [ruin_everything(elem, 'auto-habits')
                     for elem in conn.fetchall()]

    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 2
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    for tup in conn.fetchall():
        conn.execute("""SELECT id, name
                     FROM ManuHabitCat
                     WHERE id = ?""", tup)
        all_cats += [ruin_everything(elem, 'manu-habits') for elem in
                     conn.fetchall()]

    # Find out their timezone settings
    tup = (user_id,)
    conn.execute('''SELECT tz, username, biscuits_enabled
                 FROM User
                 WHERE id = ?;''', tup)

    ans = conn.fetchone()

    cur_zone = ans[0]
    username = ans[1]
    biscuits_enabled = ans[2]

................................................................................
        user_id,
        session_id,
        cur_time
    )

    conn.execute('''SELECT COUNT(*)
                 FROM Session
                 WHERE user_id = ?
                 AND id != ?
                 AND expires > ?;''', tup)
    sessions = conn.fetchone()[0]

    return_value += templates['configuration'].\
        render(note_cats=note_cats,
               auto_cats=auto_cats,
               manu_cats=manu_cats,
               uber_pages=uber_pages,







|






|







 







|
|






|









|







 







|






|







 







|
|






|









|







 







|






|







 







|
|






|









|







 







|











|
|







 







|






|






|







 







|





|






|





|







|





|







|







 







|
|
|







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
76
77
78
79
80
81
82
83
84
85
86
..
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
...
112
113
114
115
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
144
...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
...
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
...
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
...
246
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
...
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
                                             )

    # Get all note cats that this user has permission to access.
    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 0
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    note_cats_1 = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM NoteCat
                     WHERE id = %s;''', tup)
        note_cats_1 += conn.fetchall()

    note_cats = []

    # Find out if they are in use by any page (if not they may be
    # deleted) and if they are shared with any other users.
    for cat in note_cats_1:
................................................................................
        cat_id = cat[0]
        name = cat[1]

        tup = (cat_id, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM PageContent
                     WHERE entry_type=0
                     AND entry_id=%s
                     AND user_id = %s;''', tup)
        num_cats = conn.fetchone()[0]

        tup = (cat_id,)
        conn.execute('''SELECT user_id
                     FROM CatKey
                     WHERE task_type = 0
                     AND cat_id = %s
                     ORDER BY id ASC;''', tup)
        userids = conn.fetchall()

        note_share_usernames = []

        for userid in userids:
            tup = (userid[0],)
            conn.execute('''SELECT username
                         FROM User
                         WHERE id = %s;''', tup)
            note_share_usernames += conn.fetchone()

        num_users = len(userids)

        if num_users > 3:
            num_users = 3

................................................................................
            note_cats += [[cat_id, name, 0, num_users, note_share_usernames]]

    # Get all auto-habit cats that this user has permission to access.
    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 1
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    auto_cats_1 = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM AutoHabitCat
                     WHERE id = %s;''', tup)
        auto_cats_1 += conn.fetchall()

    auto_cats = []

    # Find out if they are in use by any page (if not they may be
    # deleted) and if they are shared with any other users.
    for cat in auto_cats_1:
................................................................................
        cat_id = cat[0]
        name = cat[1]

        tup = (cat_id, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM PageContent
                     WHERE entry_type=1
                     AND entry_id = %s
                     AND user_id = %s;''', tup)
        num_cats = conn.fetchone()[0]

        tup = (cat_id,)
        conn.execute('''SELECT user_id
                     FROM CatKey
                     WHERE task_type = 1
                     AND cat_id = %s
                     ORDER BY id ASC;''', tup)
        userids = conn.fetchall()

        auto_share_usernames = []

        for userid in userids:
            tup = (userid[0],)
            conn.execute('''SELECT username
                         FROM User
                         WHERE id = %s''', tup)
            auto_share_usernames += conn.fetchone()

        num_users = len(userids)

        if num_users > 3:
            num_users = 3

................................................................................
            auto_cats += [[cat_id, name, 0, num_users, auto_share_usernames]]

    # Get all manu-habit cats that this user has permission to access.
    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 2
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    manu_cats_1 = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM ManuHabitCat
                     WHERE id = %s;''', tup)
        manu_cats_1 += conn.fetchall()

    manu_cats = []

    # Find out if they are in use by any page (if not they may be
    # deleted) and if they are shared with any other users.
    for cat in manu_cats_1:
................................................................................
        cat_id = cat[0]
        name = cat[1]

        tup = (cat_id, user_id)
        conn.execute('''SELECT COUNT(*)
                     FROM PageContent
                     WHERE entry_type=2
                     AND entry_id = %s
                     AND user_id = %s;''', tup)
        num_cats = conn.fetchone()[0]

        tup = (cat_id,)
        conn.execute('''SELECT user_id
                     FROM CatKey
                     WHERE task_type = 2
                     AND cat_id = %s
                     ORDER BY id ASC;''', tup)
        userids = conn.fetchall()

        manu_share_usernames = []

        for userid in userids:
            tup = (userid[0],)
            conn.execute('''SELECT username
                         FROM User
                         WHERE id = %s''', tup)
            manu_share_usernames += conn.fetchone()

        num_users = len(userids)

        if num_users > 3:
            num_users = 3

................................................................................
    # page_entry[2] = name
    uber_pages = []

    # Get all the pages
    tup = (user_id,)
    conn.execute('''SELECT id, name
                 FROM Page
                 WHERE user_id = %s
                 ORDER BY seq;''', tup)
    pages = conn.fetchall()

    # For each page, get all of the contents
    for page in pages:
        page_id = page[0]
        page_name = page[1]

        tup = (page_id, user_id)
        conn.execute("""SELECT id, entry_type, entry_id
                     FROM PageContent
                     WHERE page_id = %s
                     AND user_id = %s
                     ORDER BY seq;""", tup)
        contents = conn.fetchall()

        page_entries = []

        # For each content, get the category.
        for content in contents:
................................................................................
            entry_type = content[1]
            entry_id = content[2]

            tup = (entry_id,)
            if entry_type == 0:  # Note
                conn.execute("""SELECT name
                             FROM NoteCat
                             WHERE id = %s;""", tup)
                entry = conn.fetchone()
                page_entry = [cat_id, entry_id] + list(entry)
                page_entry[2] += ' notes'
            elif entry_type == 1:  # Auto-habit
                conn.execute("""SELECT name
                             FROM AutoHabitCat
                             WHERE id = %s;""", tup)
                entry = conn.fetchone()
                page_entry = [cat_id, entry_id] + list(entry)
                page_entry[2] += ' auto-habits'
            elif entry_type == 2:  # Manu-habit
                conn.execute("""SELECT name
                             FROM ManuHabitCat
                             WHERE id = %s;""", tup)
                entry = conn.fetchone()
                page_entry = [cat_id, entry_id] + list(entry)
                page_entry[2] += ' manu-habits'

            page_entries += [page_entry]

        uber_pages += [[page_id, page_name, page_entries]]
................................................................................

    all_cats = []

    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 0
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    for tup in conn.fetchall():
        conn.execute("""SELECT id, name
                     FROM NoteCat
                     WHERE id = %s""", tup)
        all_cats += [ruin_everything(elem, 'notes') for elem in conn.fetchall()]

    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 1
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    for tup in conn.fetchall():
        conn.execute("""SELECT id, name
                     FROM AutoHabitCat
                     WHERE id = %s""", tup)
        all_cats += [ruin_everything(elem, 'auto-habits')
                     for elem in conn.fetchall()]

    tup = (user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = 2
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    for tup in conn.fetchall():
        conn.execute("""SELECT id, name
                     FROM ManuHabitCat
                     WHERE id = %s""", tup)
        all_cats += [ruin_everything(elem, 'manu-habits') for elem in
                     conn.fetchall()]

    # Find out their timezone settings
    tup = (user_id,)
    conn.execute('''SELECT tz, username, biscuits_enabled
                 FROM User
                 WHERE id = %s;''', tup)

    ans = conn.fetchone()

    cur_zone = ans[0]
    username = ans[1]
    biscuits_enabled = ans[2]

................................................................................
        user_id,
        session_id,
        cur_time
    )

    conn.execute('''SELECT COUNT(*)
                 FROM Session
                 WHERE user_id = %s
                 AND id != %s
                 AND expires > %s;''', tup)
    sessions = conn.fetchone()[0]

    return_value += templates['configuration'].\
        render(note_cats=note_cats,
               auto_cats=auto_cats,
               manu_cats=manu_cats,
               uber_pages=uber_pages,

Changes to taskenizer/pages/deferred_tasks.py.

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
..
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
            ecmaname = "manu_habit"
            display_name = 'manual-habit'

        # I need to find out the name of this category.
        tup = (cat_id,)
        conn.execute('''SELECT name
                     FROM %s
                     WHERE id = ?;''' % catcat, tup)
        cat_name = conn.fetchone()[0]

        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, task_type, cat_id)

        if fern is False:
            return '<h2>Category access denied</h2>'

        # We need to find deferred tasks in the category
        tup = (cat_id,)
        conn.execute('''SELECT id, color, name, def_days,
                     def_months, def_years
                     FROM %s
                     WHERE cat_id = ?
                     AND deferred = 1
                     ORDER BY id ASC;''' % cat_type, tup)
        rows = conn.fetchall()

        # Decrypt the names and find out the unixtime that they're due
        rows = [[elem[0], elem[1], crypto.decrypt_name(elem[2], fern), elem[3], elem[4], elem[5], when_due(cur_time, timezone, elem[3], elem[4], elem[5])] for elem in rows]

................................................................................

        # We decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (task_type, user_id,)
        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = ?
                     AND user_id = ?;''', tup)
        num_task_cats = conn.fetchone()

        return templates['deferred_tasks'].render(
            request_uri=environ['REQUEST_URI'], cat_id=cat_id,
            num_task_cats=num_task_cats, rows=rows, cat_name=cat_name,
            deflt_color=conf['Cosmetic']['default_task_background_color'],
            ecmaname=ecmaname, display_name=display_name)
................................................................................
    cats_wth_dfrd = []
    cats_non_dfrd = []

    # Make a list of all categories this user has access to.
    tup = (user_id,)
    conn.execute('''SELECT cat_id, task_type
                 FROM CatKey
                 WHERE user_id = ?
                 ORDER BY id ASC;''', tup)

    # For each category, run "un_defer_any" and record if the category
    # has any deferred tasks.
    for cat in conn.fetchall():
        cat_id = cat[0]
        task_type = cat[1]
................................................................................
            cat_type = 'AutoHabit'
        if task_type == 2:
            cat_type = 'ManuHabit'

        tup = (cat_id,)
        conn.execute('''SELECT cat_id
                     FROM %s
                     WHERE cat_id = ?
                     AND deferred=1;''' % cat_type, tup)
        resp = conn.fetchone()

        if resp is not None:
            cats_wth_dfrd += (cat,)
        else:
            cats_non_dfrd += (cat,)







|












|







 







|
|







 







|







 







|







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
..
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
...
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
            ecmaname = "manu_habit"
            display_name = 'manual-habit'

        # I need to find out the name of this category.
        tup = (cat_id,)
        conn.execute('''SELECT name
                     FROM %s
                     WHERE id = %%s;''' % catcat, tup)
        cat_name = conn.fetchone()[0]

        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, task_type, cat_id)

        if fern is False:
            return '<h2>Category access denied</h2>'

        # We need to find deferred tasks in the category
        tup = (cat_id,)
        conn.execute('''SELECT id, color, name, def_days,
                     def_months, def_years
                     FROM %s
                     WHERE cat_id = %%s
                     AND deferred = 1
                     ORDER BY id ASC;''' % cat_type, tup)
        rows = conn.fetchall()

        # Decrypt the names and find out the unixtime that they're due
        rows = [[elem[0], elem[1], crypto.decrypt_name(elem[2], fern), elem[3], elem[4], elem[5], when_due(cur_time, timezone, elem[3], elem[4], elem[5])] for elem in rows]

................................................................................

        # We decide whether to display move buttons or
        # not. There's no point of displaying them if there's
        # only one category.
        tup = (task_type, user_id,)
        conn.execute('''SELECT COUNT(*)
                     FROM CatKey
                     WHERE task_type = %s
                     AND user_id = %s;''', tup)
        num_task_cats = conn.fetchone()

        return templates['deferred_tasks'].render(
            request_uri=environ['REQUEST_URI'], cat_id=cat_id,
            num_task_cats=num_task_cats, rows=rows, cat_name=cat_name,
            deflt_color=conf['Cosmetic']['default_task_background_color'],
            ecmaname=ecmaname, display_name=display_name)
................................................................................
    cats_wth_dfrd = []
    cats_non_dfrd = []

    # Make a list of all categories this user has access to.
    tup = (user_id,)
    conn.execute('''SELECT cat_id, task_type
                 FROM CatKey
                 WHERE user_id = %s
                 ORDER BY id ASC;''', tup)

    # For each category, run "un_defer_any" and record if the category
    # has any deferred tasks.
    for cat in conn.fetchall():
        cat_id = cat[0]
        task_type = cat[1]
................................................................................
            cat_type = 'AutoHabit'
        if task_type == 2:
            cat_type = 'ManuHabit'

        tup = (cat_id,)
        conn.execute('''SELECT cat_id
                     FROM %s
                     WHERE cat_id = %%s
                     AND deferred=1;''' % cat_type, tup)
        resp = conn.fetchone()

        if resp is not None:
            cats_wth_dfrd += (cat,)
        else:
            cats_non_dfrd += (cat,)

Changes to taskenizer/pages/main.py.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
..
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
...
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
...
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    return_value_middle = ''
    return_value_bottom = ''

    # Find out the name of this page
    tup = (page_id, user_id)
    conn.execute('''SELECT name
                 FROM Page
                 WHERE id = ?
                 AND user_id = ?;''', tup)
    rows = conn.fetchone()

    try:
        page_name = rows[0]
    except TypeError:
        return display.redirect_to_first_page(conn, user_id, conf)

................................................................................
    future_day_active={day: 0 for day in range(1, future_day_count + 1)}

    # Now we need to find out which things are to be displayed on
    # this page.
    tup = (page_id, user_id)
    conn.execute('''SELECT entry_type, entry_id
                 FROM PageContent
                 WHERE page_id = ?
                 AND user_id = ?
                 ORDER BY seq;''', tup)
    rows = conn.fetchall()

    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # next seven days
................................................................................
        cat_id = row[1]

        if entry_type == 0:  # notodo
            # I need to find out the name and change number of this category
            tup = (str(cat_id),)
            conn.execute('''SELECT name, change_num
                         FROM NoteCat
                         WHERE id = ?;''', tup)
            ans = conn.fetchone()
            cat_name = ans[0]
            change_num = ans[1]

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0, cat_id)

            if fern is False:
................................................................................

                # We need to decide whether to display move buttons or
                # not. There's no point of displaying them if there's
                # only one category.
                tup = (0, user_id,)
                conn.execute('''SELECT COUNT(*)
                             FROM CatKey
                             WHERE task_type = ?
                             AND user_id = ?''', tup)
                num_note_cats = conn.fetchone()

                return_value_bottom += templates['note_category'].render(
                    cat_name=cat_name,
                    cat_id=cat_id,
                    change_num=change_num,
                    num_note_cats=num_note_cats,
................................................................................
                )

        elif entry_type == 1:  # autohabit
            # I need to find out the name and change number of this category
            tup = (str(cat_id),)
            conn.execute('''SELECT name, change_num
                         FROM AutoHabitCat
                         WHERE id = ?;''', tup)
            ans = conn.fetchone()
            cat_name = ans[0]
            change_num = ans[1]

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)

            if fern is False:
................................................................................

                # We decide whether to display move buttons or
                # not. There's no point of displaying them if there's
                # only one category.
                tup = (1, user_id,)
                conn.execute('''SELECT COUNT(*)
                             FROM CatKey
                             WHERE task_type = ?
                             AND user_id = ?;''', tup)
                num_cats = conn.fetchone()

                return_value_bottom += templates['auto_habit_category'].render(
                    cat_name=cat_name,
                    cat_id=cat_id,
                    change_num=change_num,
                    list_of_habits=list_of_habits,
................................................................................

        elif entry_type == 2:  # manuhabit
            # I need to find out the name, last advanced time and
            # change number of this category
            tup = (str(cat_id),)
            conn.execute('''SELECT name, last_advanced, change_num
                         FROM ManuHabitCat
                         WHERE id = ?;''', tup)
            ans = conn.fetchone()

            cat_name = ans[0]
            last_advanced = ans[1]
            change_num = ans[2]

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)
................................................................................

                # We decide whether to display move buttons or
                # not. There's no point of displaying them if there's
                # only one category.
                tup = (2, user_id,)
                conn.execute('''SELECT COUNT(*)
                             FROM CatKey
                             WHERE task_type = ?
                             AND user_id = ?;''', tup)
                num_cats = conn.fetchone()

                if last_advanced is None:
                    last_advanced = ''

                return_value_bottom += templates['manu_habit_category'].render(
                    cat_name=cat_name,







|
|







 







|
|







 







|







 







|
|







 







|







 







|
|







 







|







 







|
|







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
..
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
...
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
...
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
    return_value_middle = ''
    return_value_bottom = ''

    # Find out the name of this page
    tup = (page_id, user_id)
    conn.execute('''SELECT name
                 FROM Page
                 WHERE id = %s
                 AND user_id = %s;''', tup)
    rows = conn.fetchone()

    try:
        page_name = rows[0]
    except TypeError:
        return display.redirect_to_first_page(conn, user_id, conf)

................................................................................
    future_day_active={day: 0 for day in range(1, future_day_count + 1)}

    # Now we need to find out which things are to be displayed on
    # this page.
    tup = (page_id, user_id)
    conn.execute('''SELECT entry_type, entry_id
                 FROM PageContent
                 WHERE page_id = %s
                 AND user_id = %s
                 ORDER BY seq;''', tup)
    rows = conn.fetchall()

    # user's timezone
    timezone = operations.get_tz_settings(conn, user_id)

    # next seven days
................................................................................
        cat_id = row[1]

        if entry_type == 0:  # notodo
            # I need to find out the name and change number of this category
            tup = (str(cat_id),)
            conn.execute('''SELECT name, change_num
                         FROM NoteCat
                         WHERE id = %s;''', tup)
            ans = conn.fetchone()
            cat_name = ans[0]
            change_num = ans[1]

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 0, cat_id)

            if fern is False:
................................................................................

                # We need to decide whether to display move buttons or
                # not. There's no point of displaying them if there's
                # only one category.
                tup = (0, user_id,)
                conn.execute('''SELECT COUNT(*)
                             FROM CatKey
                             WHERE task_type = %s
                             AND user_id = %s''', tup)
                num_note_cats = conn.fetchone()

                return_value_bottom += templates['note_category'].render(
                    cat_name=cat_name,
                    cat_id=cat_id,
                    change_num=change_num,
                    num_note_cats=num_note_cats,
................................................................................
                )

        elif entry_type == 1:  # autohabit
            # I need to find out the name and change number of this category
            tup = (str(cat_id),)
            conn.execute('''SELECT name, change_num
                         FROM AutoHabitCat
                         WHERE id = %s;''', tup)
            ans = conn.fetchone()
            cat_name = ans[0]
            change_num = ans[1]

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 1, cat_id)

            if fern is False:
................................................................................

                # We decide whether to display move buttons or
                # not. There's no point of displaying them if there's
                # only one category.
                tup = (1, user_id,)
                conn.execute('''SELECT COUNT(*)
                             FROM CatKey
                             WHERE task_type = %s
                             AND user_id = %s;''', tup)
                num_cats = conn.fetchone()

                return_value_bottom += templates['auto_habit_category'].render(
                    cat_name=cat_name,
                    cat_id=cat_id,
                    change_num=change_num,
                    list_of_habits=list_of_habits,
................................................................................

        elif entry_type == 2:  # manuhabit
            # I need to find out the name, last advanced time and
            # change number of this category
            tup = (str(cat_id),)
            conn.execute('''SELECT name, last_advanced, change_num
                         FROM ManuHabitCat
                         WHERE id = %s;''', tup)
            ans = conn.fetchone()

            cat_name = ans[0]
            last_advanced = ans[1]
            change_num = ans[2]

            fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)
................................................................................

                # We decide whether to display move buttons or
                # not. There's no point of displaying them if there's
                # only one category.
                tup = (2, user_id,)
                conn.execute('''SELECT COUNT(*)
                             FROM CatKey
                             WHERE task_type = %s
                             AND user_id = %s;''', tup)
                num_cats = conn.fetchone()

                if last_advanced is None:
                    last_advanced = ''

                return_value_bottom += templates['manu_habit_category'].render(
                    cat_name=cat_name,

Changes to taskenizer/pages/manu_habits.py.

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
                                             conf, javascript_name,
                                             themeinfo['activetheme'])

    # Make a list of all manu-habit categories this user has access to.
    tup = (2, user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = ?
                 AND user_id = ?
                 ORDER BY id ASC;''', tup)

    cats = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM ManuHabitCat
                     WHERE id = ?;''', tup)
        cats += conn.fetchall()

    for cat in cats:
        cat_id = cat[0]
        cat_name = cat[1]

        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)
................................................................................
        else:
            # We decide whether to display move buttons or
            # not. There's no point of displaying them if there's
            # only one category.
            tup = (2, user_id,)
            conn.execute('''SELECT COUNT(*)
                         FROM CatKey
                         WHERE task_type = ?
                         AND user_id = ?;''', tup)
            num_cats = conn.fetchone()

            tup = (cat_id,)
            conn.execute('''SELECT id, name, freq, due, color
                         FROM ManuHabit
                         WHERE cat_id = ?
                         ORDER BY id ASC;''', tup)







|
|






|







 







|
|







29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
                                             conf, javascript_name,
                                             themeinfo['activetheme'])

    # Make a list of all manu-habit categories this user has access to.
    tup = (2, user_id,)
    conn.execute('''SELECT cat_id
                 FROM CatKey
                 WHERE task_type = %s
                 AND user_id = %s
                 ORDER BY id ASC;''', tup)

    cats = []
    for tup in conn.fetchall():
        conn.execute('''SELECT id, name
                     FROM ManuHabitCat
                     WHERE id = %s;''', tup)
        cats += conn.fetchall()

    for cat in cats:
        cat_id = cat[0]
        cat_name = cat[1]

        fern = crypto.prepare_cryptor(conn, user_id, cryptohash, 2, cat_id)
................................................................................
        else:
            # We decide whether to display move buttons or
            # not. There's no point of displaying them if there's
            # only one category.
            tup = (2, user_id,)
            conn.execute('''SELECT COUNT(*)
                         FROM CatKey
                         WHERE task_type = %s
                         AND user_id = %s;''', tup)
            num_cats = conn.fetchone()

            tup = (cat_id,)
            conn.execute('''SELECT id, name, freq, due, color
                         FROM ManuHabit
                         WHERE cat_id = ?
                         ORDER BY id ASC;''', tup)

Changes to taskenizer/taskenizer.py.

27
28
29
30
31
32
33
34

35
36
37
38
39
40
41
..
72
73
74
75
76
77
78
79
80
81



82
83
84
85
86
87
88
import sys
import gzip
import time
import atexit
import hashlib
import configparser
import base64
import sqlite3

import logging

from flufl.lock import Lock
from flufl.lock import TimeOutError

# Read the arguments
config_file = sys.argv[1]
................................................................................

handler.setFormatter(formatter)

log.addHandler(handler)

# Connect to the database

dbconn = sqlite3.connect(conf['System']['dblocation'])
conn = dbconn.cursor()
conn.execute("PRAGMA foreign_keys=ON;")




# Load all the templates

templates = task_funcs.load_templates(conf['System']['code_location'],
                                      'taskenizer/templates/'
                                      )








|
>







 







|
|
|
>
>
>







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import sys
import gzip
import time
import atexit
import hashlib
import configparser
import base64
#import sqlite3
import mysql.connector as mariadb
import logging

from flufl.lock import Lock
from flufl.lock import TimeOutError

# Read the arguments
config_file = sys.argv[1]
................................................................................

handler.setFormatter(formatter)

log.addHandler(handler)

# Connect to the database

# dbconn = sqlite3.connect(conf['System']['dblocation'])
# conn = dbconn.cursor()
# conn.execute("PRAGMA foreign_keys=ON;")

dbconn = mariadb.connect(user=conf['System']['dbuser'], password=conf['System']['dbpass'], database=conf['System']['dbname'], host=conf['System']['dbhost'], port=conf['System']['dbport'])
conn = dbconn.cursor()

# Load all the templates

templates = task_funcs.load_templates(conf['System']['code_location'],
                                      'taskenizer/templates/'
                                      )

Changes to taskenizerctl.

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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
290
291
292
293
            echo "Error: a Taskenizer instance using this config file seems to already be running. 😕"

            exit 1
        fi
    fi

    # Now we check what the database version is and see if it needs to
    # be migrated.
    dbversion=$(sqlite3 "${dblocation}" "SELECT version FROM Extradata" 2>/dev/null)

    # If it's so old that the field does not exist yet
    [[ -z "${dbversion}" ]] && dbversion=0

    if (( dbversion < 1 ))
    then
        echo "Upgrading database to new format."

        # AutoHabit
        sqlite3 "${dblocation}" "ALTER TABLE AutoHabit ADD deferred INTEGER;"
        sqlite3 "${dblocation}" "UPDATE AutoHabit SET deferred = 0;"

        sqlite3 "${dblocation}" "ALTER TABLE AutoHabit ADD def_days INTEGER;"
        sqlite3 "${dblocation}" "UPDATE AutoHabit SET def_days = 0;"

        sqlite3 "${dblocation}" "ALTER TABLE AutoHabit ADD def_months INTEGER;"
        sqlite3 "${dblocation}" "UPDATE AutoHabit SET def_months = 0;"

        sqlite3 "${dblocation}" "ALTER TABLE AutoHabit ADD def_years INTEGER;"
        sqlite3 "${dblocation}" "UPDATE AutoHabit SET def_years = 0;"

        # ManuHabit
        sqlite3 "${dblocation}" "ALTER TABLE ManuHabit ADD deferred INTEGER;"
        sqlite3 "${dblocation}" "UPDATE ManuHabit SET deferred = 0;"

        sqlite3 "${dblocation}" "ALTER TABLE ManuHabit ADD def_days INTEGER;"
        sqlite3 "${dblocation}" "UPDATE ManuHabit SET def_days = 0;"

        sqlite3 "${dblocation}" "ALTER TABLE ManuHabit ADD def_months INTEGER;"
        sqlite3 "${dblocation}" "UPDATE ManuHabit SET def_months = 0;"

        sqlite3 "${dblocation}" "ALTER TABLE ManuHabit ADD def_years INTEGER;"
        sqlite3 "${dblocation}" "UPDATE ManuHabit SET def_years = 0;"

        # Last we add the "Extradata" table and set the version to "1".
        sqlite3 "${dblocation}" "CREATE TABLE Extradata (version INT);"
        sqlite3 "${dblocation}" "INSERT INTO Extradata (version) VALUES (1)"
    fi
    
    if (( dbversion < 2 ))
    then
        echo "Upgrading database to format 2."

        sqlite3 "${dblocation}" "ALTER TABLE User ADD ip_address TEXT;"
        sqlite3 "${dblocation}" "ALTER TABLE User ADD reg_date INTEGER;"

        sqlite3 "${dblocation}" "CREATE TABLE LoginFail (ip_address TEXT, date INT);"

        # Set the db version
        sqlite3 "${dblocation}" "UPDATE Extradata SET version = 2;"
    fi

    if (( dbversion < 3 ))
    then
        echo "Upgrading database to format 3."

        sqlite3 "${dblocation}" "ALTER TABLE User ADD actheme TEXT;"
        sqlite3 "${dblocation}" "UPDATE User SET actheme = 'bliblablib';"

        # Set the db version
        sqlite3 "${dblocation}" "UPDATE Extradata SET version = 3;"
    fi
    
    if (( dbversion < 4 ))
    then
        echo "Upgrading database to format 4."

        sqlite3 "${dblocation}" "CREATE TABLE AcReg (ip_address TEXT, date INT);"

        # Set the db version
        sqlite3 "${dblocation}" "UPDATE Extradata SET version = 4;"
    fi

    # Populate the static files directory.

    # Let's copy over the static files we need.

    rm -rf "${servlocation}"*








|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







206
207
208
209
210
211
212
213









































































214
215
216
217
218
219
220
            echo "Error: a Taskenizer instance using this config file seems to already be running. 😕"

            exit 1
        fi
    fi

    # Now we check what the database version is and see if it needs to
    # be migrated. THIS CODE WAS REMOVED BEAUSE WE'RE NOW ON MYSQL INSTEAD OF SQLITE










































































    # Populate the static files directory.

    # Let's copy over the static files we need.

    rm -rf "${servlocation}"*