def output_cohorts_info(obj, format_string, path):
    from psmdlsyncer.sql import MoodleDBSession
    from psmdlsyncer.php import ModUserEnrollments
    from psmdlsyncer.sql import MoodleDBSession

    from psmdlsyncer.models.datastores.moodle import MoodleTree

    moodle = MoodleTree()
    moodle.process()

    m = MoodleDBSession()
    mod = ModUserEnrollments()

    if path is None:
        import sys
        output_func = sys.stdout.write
    else:
        output_func = path.write

    format_string += '\n'

    for idnumber, username, cohort in m.get_cohorts_with_username():
        if cohort:
            if moodle.teachers.get_from_attribute('username', username):
                output_func(format_string.format(idnumber=idnumber, cohort=cohort, username=username))
def portfolios_by_class(obj, file_):
    output_list = []
    from psmdlsyncer.models.datastores.autosend import AutoSendTree
    from psmdlsyncer.models.datastores.moodle import MoodleTree
    import re
    autosend = AutoSendTree()
    moodle = MoodleTree()
    autosend.process()
    moodle.process()


    for student_key in autosend.students.get_keys():
        student = autosend.students.get_key(student_key)
        m_student = moodle.students.get_key(student_key)
        if student.homeroom == "1DB" or student.grade in [4, 5]:
            item = type("Student", (), {})
            f = re.sub('[^a-z]', '', student.first.lower())
            item.firstname = student.first
            item.lastname = student.last
            item.student_id = student.idnumber
            item.name = student.first + ' ' + student.last
            item.homeroom = student.homeroom
            item.teacher_email = student.homeroom_teacher.email
            item.student_email = student.email
            item.slug = f + item.student_id
            item.blog_url = 'http://portfolios.ssis-suzhou.net/' + item.slug

            output_list.append([item.name, item.homeroom, item.blog_url])

    output_list.sort(key=lambda x: x[1])
    for line in output_list:
        file_.write("\t".join(line) + '\n')
def output_portfolios(obj, file_):
    from psmdlsyncer.models.datastores.autosend import AutoSendTree
    from psmdlsyncer.models.datastores.moodle import MoodleTree
    import re
    from cli.portfolio_commands import portfolio_commands
    autosend = AutoSendTree()
    moodle = MoodleTree()
    autosend.process()
    moodle.process()

    #   firstname  student_id  homeroom  email
    #import_list = [ ('Adam',      '99999',    '5UK',  '*****@*****.**') ]

    for student_key in autosend.students.get_keys():
        # Use moodle's info
        student = moodle.students.get_key(student_key)
        if not student:
            continue
        #if student.grade in [4, 5]:
        if student.homeroom == "1DB":
            item = type("Student", (), {})
            f = re.sub('[^a-z]', '', student.first.lower())
            item.firstname = student.first
            item.student_id = student.idnumber
            item.homeroom = student.homeroom
            item.teacher_email = '*****@*****.**'
            item.student_email = student.email
            item.slug = f + item.student_id

            file_.write('# {}:\n'.format(item.slug))
            for command in portfolio_commands.split('\n'):
                file_.write(command.format(item) + '\n')
def dragonnet_user(which, subbranch=None, attribute=None, value=None, **kwargs):
    """
    Check out the information that is provided by PowerSchool and compare that to Moodle
    """
    click.echo("Hi there, starting up our syncing software (patience is a virtue).")
    if which.lower() == 'autosend':
        from psmdlsyncer.models.datastores.autosend import AutoSendTree
        autosend = AutoSendTree()
        moodle = None
    elif which.lower() == 'moodle':
        from psmdlsyncer.models.datastores.moodle import MoodleTree
        moodle = MoodleTree()
        autosend = None
    elif which.lower() == 'both':
        from psmdlsyncer.models.datastores.autosend import AutoSendTree
        from psmdlsyncer.models.datastores.moodle import MoodleTree
        moodle = MoodleTree()
        autosend = AutoSendTree()

    click.echo('Begin processing...')
    autosend.process() if autosend else None
    moodle.process() if moodle else None
    click.echo('...done processing.')

    if not subbranch:
        subbranch = click.prompt("Enter subbranch are looking for: ", default='students')
    if not attribute:
        attribute = click.prompt("Enter the attribute you are looking for: ", default="idnumber")
    if not value:
        value = click.prompt("Enter the value you are looking for: ")

    autosend_item = getattr(autosend, subbranch).get_from_attribute(attribute, value) if autosend else None
    moodle_item = getattr(moodle, subbranch).get_from_attribute(attribute, value) if moodle else None
    click.echo(autosend_item.output(indent=4, add={'branch':'autosend'})) if autosend_item else None
    click.echo(moodle_item.output(indent=4, add={'branch':'moodle'})) if moodle_item else None
def launch(obj, inspect=False, output=None, analyze=False, teachersonly=False, studentsonly=False):
    """
    Launch syncer stuff
    """
    import socket
    hostname = socket.gethostname()
    if 'dragonnet' in hostname:
        from psmdlsyncer.models.datastores.moodle import MoodleTree
        from psmdlsyncer.models.datastores.autosend import AutoSendTree
        from psmdlsyncer.syncing.templates import MoodleTemplate
        from psmdlsyncer.syncing.differences import DetermineChanges

        # To get the groups right we need to process AutosendTree first and send it over to Moodle

        right = AutoSendTree()
        right.process()
        left = MoodleTree()
        #left.groups.section_maps = {v:k for k, v in right.groups.section_maps.items()}  # items become the keys
        left.process()

        d = DetermineChanges(left, right, MoodleTemplate, teachersonly, studentsonly)

        if output:
            for item in d.subtract():
                output.write(str(item))
                output.write('\n')
            exit()
        if inspect:
            from IPython import embed
            embed()
            exit()
        if analyze:
            keys = list(left.groups.section_maps.keys)
            print(keys)
            from IPython import embed;embed()
            ss = [k for k in keys if left.groups.get_key(k).idnumber.endswith('S')]
            for s in ss:
                swa = s + 'WA1'
                swas1 = [k for k in keys if swa in keys[k]]
                print(swas1)
                swa = s + 'WA2'
                swas2 = [k for k in keys if swa in keys[k]]
                print(swas2)
            exit()
        d.go()

    elif 'student' in hostname:
        from psmdlsyncer.models.datastores.autosend import AutoSendTree
        autosend = AutoSendTree()
        autosend.process()
        autosend.build_automagic_emails(make_new_students=True)
        autosend.output_all_aliases()
        autosend.run_newaliases()

    else:
        print("Can't run, is the hostname wrong?")
def update_portfolios(obj, file_):
    from psmdlsyncer.models.datastores.autosend import AutoSendTree
    from psmdlsyncer.models.datastores.moodle import MoodleTree
    import re
    from cli.portfolio_commands import portfolio_commands
    autosend = AutoSendTree()
    moodle = MoodleTree()
    autosend.process()
    moodle.process()

    #   firstname  student_id  homeroom  email
    #import_list = [ ('Adam',      '99999',    '5UK',  '*****@*****.**') ]

    for student_key in autosend.students.get_keys():
        student = autosend.students.get_key(student_key)
        m_student = moodle.students.get_key(student_key)
        if student.homeroom == "1DB" or student.grade in ["4", "5"]:
            file_.write('wp --path=/var/www/portfolios user update {0.email} --first_name=\'{0.first}\' --last_name=\'{0.last}\' --display_name=\'{0.first}\'\n'.format(student))
from psmdlsyncer.models.datastores.autosend import AutoSendTree
from collections import defaultdict
from psmdlsyncer.php import CallPHP
from psmdlsyncer.db.MoodleDB import GroupsMember as Member
import datetime

from psmdlsyncer.db import DBSession
from psmdlsyncer.sql import MoodleDBSession
from sqlalchemy import and_

test = False
really = not test

if __name__ == "__main__":

    moodle = MoodleTree()
    autosend = AutoSendTree()
    moodle.process()
    autosend.process()

    sql = MoodleDBSession()
    db = MoodleDBSession()

    Group = db.table_string_to_class('groups')
    User = db.table_string_to_class('user')
    Enrol = db.table_string_to_class('user_enrolments')
    php = CallPHP()

    renames = defaultdict(list)

    for student in moodle.students.get_objects():