def m_email(request):
    """Send an Email Notification about a Maintenance"""

    logger.debug('%s view being executed.' % 'maintenance.m_email')

    # Check the form elements
    form = EmailMaintenanceForm(request.GET)
    logger.debug('Form submit (GET): %s, with result: %s' %
                 ('EmailMaintenanceForm', form))

    if form.is_valid():
        # Obtain the cleaned data
        id = form.cleaned_data['id']

        # Obtain the email address id
        recipient_id = Event.objects.filter(id=id).values(
            'event_email__email__id')[0]['event_email__email__id']

        # If there is no recipient defined, give them an error message and send back to the list view
        if not recipient_id:
            messages.add_message(
                request, messages.ERROR,
                'There is no recipient defined for maintenance id:%s.  Please add one before sending email notifications.'
                % id)

        # Only send the email if email functionality is enabled.
        if Config_Email.objects.filter(id=Config_Email.objects.values(
                'id')[0]['id']).values('enabled')[0]['enabled'] == 1:
            email = notify.email()
            email_status = email.email_event(id, recipient_id,
                                             request.timezone, False)

            if email_status == 'success':
                messages.add_message(
                    request, messages.SUCCESS,
                    'Email successfully sent for maintenance id:%s.' % id)
            else:
                messages.add_message(
                    request, messages.ERROR,
                    'Email failed for maintenance id:%s.  Error message: %s' %
                    (id, email_status))
        else:
            messages.add_message(request, messages.ERROR,
                                 'Email functionality is disabled.')
    else:
        messages.add_message(request, messages.ERROR, 'Request failed.')

    # Redirect to the open incidents page
    return HttpResponseRedirect('/admin/m_list')
def m_email(request):
    """Send an Email Notification about a Maintenance"""

    logger.debug('%s view being executed.' % 'maintenance.m_email')

    # Check the form elements
    form = EmailMaintenanceForm(request.GET)
    logger.debug('Form submit (GET): %s, with result: %s' % ('EmailMaintenanceForm',form))

    if form.is_valid():
        # Obtain the cleaned data
        id = form.cleaned_data['id']

        # Obtain the email address id
        recipient_id = Event.objects.filter(id=id).values('event_email__email__id')[0]['event_email__email__id']

        # If there is no recipient defined, give them an error message and send back to the list view
        if not recipient_id:
            messages.add_message(request, messages.ERROR, 'There is no recipient defined for maintenance id:%s.  Please add one before sending email notifications.' % id)

        # Only send the email if email functionality is enabled.
        if Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]['id']).values('enabled')[0]['enabled'] == 1:
            email = notify.email()
            email_status = email.email_event(id,recipient_id,request.timezone,False)

            if email_status == 'success':
                messages.add_message(request, messages.SUCCESS, 'Email successfully sent for maintenance id:%s.' % id)
            else:
                messages.add_message(request, messages.ERROR, 'Email failed for maintenance id:%s.  Error message: %s' % (id,email_status))
        else:
            messages.add_message(request, messages.ERROR, 'Email functionality is disabled.')
    else:
        messages.add_message(request, messages.ERROR, 'Request failed.')

    # Redirect to the open incidents page
    return HttpResponseRedirect('/admin/m_list')
def incident(request):
    """Create Incident Page

    Create a new incident

    """

    logger.debug('%s view being executed.' % 'incidents.incident')


    # If this is a POST, then validate the form and save the data
    # Some validation must take place manually
    if request.method == 'POST':

        # If this is a form submit that fails, we want to reset whatever services were selected
        # by the user.  Templates do not allow access to Arrays stored in QueryDict objects so we have
        # to determine the list and send back to the template on failed form submits
        affected_svcs = request.POST.getlist('service')

        # Check the form elements
        form = AddIncidentForm(request.POST)
        logger.debug('Form submit (POST): %s, with result: %s' % ('AddIncidentForm',form))

        if form.is_valid():
            # Obtain the cleaned data
            s_date = form.cleaned_data['s_date']
            s_time = form.cleaned_data['s_time']
            e_date = form.cleaned_data['e_date']
            e_time = form.cleaned_data['e_time']
            description = form.cleaned_data['description']
            broadcast = form.cleaned_data['broadcast']
            email_id = form.cleaned_data['email_id']

            # Combine the dates and times into datetime objects and set the timezones
            tz = pytz.timezone(request.timezone)
            start = datetime.datetime.combine(s_date, s_time)
            start = tz.localize(start)
            if e_date and e_time:
                end = datetime.datetime.combine(e_date, e_time)
                end = tz.localize(end)
                # If there is an end date, the status is now closed
                status = 'closed'
            else:
                end = None
                # Status is still open
                status='open'

            # Create the event and obtain the ID
            e = Event.objects.create(
                                     type_id=Type.objects.filter(type='incident').values('id')[0]['id'],
                                     description=description,
                                     status_id=Status.objects.filter(status=status).values('id')[0]['id'],
                                     start=start,
                                     end=end,
                                     user_id=request.user.id
                                    )
            event_id = e.pk

            # Add the email recipient, if requested.
            # Form validation ensures that a valid email is selected if broadcast is selected.
            if broadcast:
                Event_Email(event_id=event_id,email_id=email_id).save()

            # Find out which services this impacts and associate the services with the event
            # Form validation confirms that there is at least 1 service
            for service_id in affected_svcs:
                # Should be number only -- can't figure out how to validate
                # multiple checkboxes in the form
                if re.match(r'^\d+$', service_id):
                    Event_Service(service_id=service_id,event_id=event_id).save()


            # Send an email notification to the appropriate list about this issue if requested.  Broadcast won't be
            # allowed to be true if an email address is not defined or if global email is disabled.
            if Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]['id']).values('enabled')[0]['enabled'] == 1 and broadcast:
                email = notify.email()
                email.email_event(event_id,email_id,request.timezone,True)

            # Clear the cache - don't discriminate and just clear everything that impacts events
            cache.delete_many(['timeline','events_ns','event_count_ns'])

            # Set a success message
            messages.add_message(request, messages.SUCCESS, 'Incident successfully created.')

            # Send them to the incident detail page for this newly created
            # incident
            return HttpResponseRedirect('/i_detail?id=%s' % event_id)

        else:
            messages.add_message(request, messages.ERROR, 'Invalid data entered, please correct the errors below:')

    # Not a POST so create a blank form
    else:
        # There are no affected services selected yet
        affected_svcs = []

        # Create a blank form
        form = AddIncidentForm()

    # Obtain all services
    services = Service.objects.values('id','service_name').order_by('service_name')

    # Obtain all current email addresses for the selector
    emails = Email.objects.values('id','email')

    # Print the page
    return render_to_response(
       'incidents/incident.html',
       {
          'title':'System Status Dashboard | Create Incident',
          'services':services,
          'emails':emails,
          'affected_svcs':tuple(affected_svcs),
          'form':form,
          'email_enabled':Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]['id']).values('enabled')[0]['enabled'],
          'nav_section':'event',
          'nav_sub':'incident'

       },
       context_instance=RequestContext(request)
    )
def i_update(request):
    """Update Incident Page

    Update an incident

    """

    logger.debug('%s view being executed.' % 'incidents.i_update')

    # If this is a POST, then validate the form and save the data
    # Some validation must take place manually (service
    # addition/subtraction
    if request.method == 'POST':

        # If this is a form submit that fails, we want to reset whatever services were selected
        # by the user.  Templates do not allow access to Arrays stored in QueryDict objects so we have
        # to determine the list and send back to the template on failed form submits
        affected_svcs = request.POST.getlist('service')

        # Check the form elements
        form = UpdateIncidentForm(request.POST)
        logger.debug('Form submit (POST): %s, with result: %s' % ('UpdateIncidentForm',form))

        if form.is_valid():

            # Obtain the cleaned data
            id = form.cleaned_data['id']
            description = form.cleaned_data['description']
            s_date = form.cleaned_data['s_date']
            s_time = form.cleaned_data['s_time']
            e_date = form.cleaned_data['e_date']
            e_time = form.cleaned_data['e_time']
            update = form.cleaned_data['update']
            broadcast = form.cleaned_data['broadcast']
            email_id = form.cleaned_data['email_id']

            # Combine the dates and times into datetime objects and set the timezones
            tz = pytz.timezone(request.timezone)
            start = datetime.datetime.combine(s_date, s_time)
            start = tz.localize(start)
            if e_date and e_time:
                end = datetime.datetime.combine(e_date, e_time)
                end = tz.localize(end)
                # If there is an end date, the status is now closed
                status = 'closed'
            else:
                end = None
                # Status is still open
                status='open'

            # Update the event
            Event.objects.filter(id=id).update(
                                     description=description,
                                     status=Status.objects.filter(status=status).values('id')[0]['id'],
                                     start=start,
                                     end=end)

            # Add the update, if there is one, using the current time
            if update:
                # Create a datetime object for right now and add the server's timezone (whatever DJango has)
                time_now = datetime.datetime.now()
                time_now = pytz.timezone(settings.TIME_ZONE).localize(time_now)
                Event_Update(event_id=id, date=time_now, update=update, user_id=request.user.id).save()

            # Add the email recipient.  If an email recipient is missing, then the broadcast email will not be checked.
            # In both cases, delete the existing email (because it will be re-added)
            Event_Email.objects.filter(event_id=id).delete()
            if email_id:
                Event_Email(event_id=id,email_id=email_id).save()

            # See if we are adding or subtracting services
            # The easiest thing to do here is remove all affected
            # services and re-add the ones indicated here

            # Remove first
            Event_Service.objects.filter(event_id=id).delete()

            # Now add (form validation confirms that there is at least 1)
            for service_id in affected_svcs:
                # Should be number only -- can't figure out how to validate
                # multiple checkboxes in the form
                if re.match(r'^\d+$', service_id):
                    Event_Service(event_id=id,service_id=service_id).save()

            # Send an email notification to the appropriate list about this issue if requested.  Broadcast won't be
            # allowed to be true if an email address is not defined or if global email is disabled.
            if Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]['id']).values('enabled')[0]['enabled'] == 1 and broadcast:
                email = notify.email()
                email.email_event(id,email_id,request.timezone,False)

            # Clear the cache - don't discriminate and just clear everything that impacts events
            cache.delete_many(['timeline','events_ns','event_count_ns'])

            # Set a success message
            messages.add_message(request, messages.SUCCESS, 'Incident successfully updated')

            # All done so redirect to the incident detail page so
            # the new data can be seen.
            return HttpResponseRedirect('/i_detail?id=%s' % id)

        else:
            messages.add_message(request, messages.ERROR, 'Invalid data entered, please correct the errors below:')

            # Obtain the id so we can print the update page again
            if 'id' in request.POST:
                if re.match(r'^\d+$', request.POST['id']):
                    id = request.POST['id']
                else:
                    messages.add_message(request, messages.ERROR, 'Improperly formatted incident ID - cannot update incident')
                    return HttpResponseRedirect('/admin')
            else:
                messages.add_message(request, messages.ERROR, 'No incident ID given - cannot update incident')
                return HttpResponseRedirect('/admin')

    # Not a POST so create a blank form
    else:
        # Obtain the id
        if 'id' in request.GET:
            if re.match(r'^\d+$', request.GET['id']):
                id = request.GET['id']
            else:
                messages.add_message(request, messages.ERROR, 'Improperly formatted incident ID - cannot update incident')
                return HttpResponseRedirect('/admin')
        else:
            messages.add_message(request, messages.ERROR, 'No incident ID given - cannot update incident')
            return HttpResponseRedirect('/admin')

        # In the case of a GET, we can acquire the proper services from the DB
        affected_svcs_tmp = Event.objects.filter(id=id).values('event_service__service_id')
        affected_svcs = []
        for service_id in affected_svcs_tmp:
            affected_svcs.append(service_id['event_service__service_id'])
        affected_svcs = list(affected_svcs)

        # Create a blank form
        form = UpdateIncidentForm()

    # Obtain the details (and make sure it's an incident)
    details = Event.objects.filter(id=id,type__type='incident').values(
                                                'description',
                                                'status__status',
                                                'event_email__email__id',
                                                'start',
                                                'end',
                                                'status__status'
                                                )
    # If nothing was returned, send back to the home page
    if not details:
        messages.add_message(request, messages.ERROR, 'Invalid request: no such incident id.')
        return HttpResponseRedirect('/')

    # Obtain all services
    services = Service.objects.values('id','service_name').order_by('service_name')

    # Obtain all current email addresses
    emails = Email.objects.values('id','email')

    # Obtain any updates
    updates = Event_Update.objects.filter(event_id=id).values('id','date','update').order_by('id')

    # Print the page
    return render_to_response(
       'incidents/i_update.html',
       {
          'title':'System Status Dashboard | Update Incident',
          'details':details,
          'services':services,
          'affected_svcs':affected_svcs,
          'id':id,
          'form':form,
          'updates':updates,
          'emails':emails,
          'email_enabled':Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]['id']).values('enabled')[0]['enabled'],
          'nav_section':'event',
          'nav_sub':'i_update'
       },
       context_instance=RequestContext(request)
    )
def maintenance(request):
    """Schedule maintenance page

    """

    logger.debug('%s view being executed.' % 'maintenance.maintenance')

    # If this is a POST, then validate the form and save the data
    # Some validation must take place manually
    if request.method == 'POST':

        # If this is a form submit that fails, we want to reset whatever services were selected
        # by the user.  Templates do not allow access to Arrays stored in QueryDict objects so we have
        # to determine the list and send back to the template on failed form submits
        affected_svcs = request.POST.getlist('service')

        # Check the form elements
        form = AddMaintenanceForm(request.POST)
        logger.debug('Form submit (POST): %s, with result: %s' %
                     ('AddMaintenanceForm', form))

        if form.is_valid():
            # Obtain the cleaned data
            s_date = form.cleaned_data['s_date']
            s_time = form.cleaned_data['s_time']
            e_date = form.cleaned_data['e_date']
            e_time = form.cleaned_data['e_time']
            description = form.cleaned_data['description']
            impact = form.cleaned_data['impact']
            coordinator = form.cleaned_data['coordinator']
            broadcast = form.cleaned_data['broadcast']
            email_id = form.cleaned_data['email_id']

            # Combine the dates and times into datetime objects
            start = datetime.datetime.combine(s_date, s_time)
            end = datetime.datetime.combine(e_date, e_time)

            # Set the timezone
            tz = pytz.timezone(request.timezone)
            start = tz.localize(start)
            end = tz.localize(end)

            # Create the event and obtain the ID
            e = Event.objects.create(
                type_id=Type.objects.filter(
                    type='maintenance').values('id')[0]['id'],
                description=description,
                status_id=Status.objects.filter(
                    status='planning').values('id')[0]['id'],
                start=start,
                end=end,
                user_id=request.user.id)
            event_id = e.pk

            # Save the impact analysis
            Event_Impact(event_id=event_id, impact=impact).save()

            # Save the coordinator, if requested
            Event_Coordinator(event_id=event_id,
                              coordinator=coordinator).save()

            # Add the email recipient, if requested
            if email_id:
                Event_Email(event_id=event_id, email_id=email_id).save()

            # Find out which services this impacts and associate the services with the event
            # Form validation confirms that there is at least 1
            for service_id in affected_svcs:
                # Should be number only -- can't figure out how to validate
                # multiple checkboxes in the form
                if re.match(r'^\d+$', service_id):
                    Event_Service(service_id=service_id,
                                  event_id=event_id).save()

            # Send an email notification to the appropriate list about this maintenance, if requested.  Broadcast won't be
            # allowed to be true if an email address is not defined or if global email is disabled.
            if Config_Email.objects.filter(
                    id=Config_Email.objects.values('id')[0]['id']).values(
                        'enabled')[0]['enabled'] == 1 and broadcast:
                email = notify.email()
                email.email_event(event_id, email_id, request.timezone, True)

            # Clear the cache - don't discriminate and just clear everything that impacts events
            cache.delete_many(['timeline', 'events_ns', 'event_count_ns'])

            # Set a success message
            messages.add_message(request, messages.SUCCESS,
                                 'Maintenance successfully created.')

            # Send them to the maintenance detail page for this newly created
            # maintenance
            return HttpResponseRedirect('/m_detail?id=%s' % event_id)

        else:
            messages.add_message(
                request, messages.ERROR,
                'Invalid data entered, please correct the errors below:')

    # Not a POST so create a blank form
    else:

        # There are no affected services selected yet
        affected_svcs = []

        # Create a blank form
        form = AddMaintenanceForm()

    # Obtain all current email addresses
    emails = Email.objects.values('id', 'email')

    # Obtain all services
    services = Service.objects.values('id',
                                      'service_name').order_by('service_name')

    # Print the page
    return render_to_response('maintenance/maintenance.html', {
        'title':
        'System Status Dashboard | Scheduled Maintenance',
        'form':
        form,
        'services':
        services,
        'affected_svcs':
        tuple(affected_svcs),
        'emails':
        emails,
        'email_enabled':
        Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]
                                    ['id']).values('enabled')[0]['enabled'],
        'nav_section':
        'event',
        'nav_sub':
        'maintenance'
    },
                              context_instance=RequestContext(request))
def m_update(request):
    """Update Maintenance Page

    Accept input to update the scheduled maintenance

    """

    logger.debug('%s view being executed.' % 'maintenance.m_update')

    # If this is a POST, then validate the form and save the data
    # Some validation must take place manually (service
    # addition/subtraction
    if request.method == 'POST':

        # If this is a form submit that fails, we want to reset whatever services were selected
        # by the user.  Templates do not allow access to Arrays stored in QueryDict objects so we have
        # to determine the list and send back to the template on failed form submits
        affected_svcs = request.POST.getlist('service')

        # Check the form elements
        form = UpdateMaintenanceForm(request.POST)
        logger.debug('Form submit (POST): %s, with result: %s' %
                     ('UpdateMaintenanceForm', form))

        if form.is_valid():
            # Obtain the cleaned data
            id = form.cleaned_data['id']
            s_date = form.cleaned_data['s_date']
            s_time = form.cleaned_data['s_time']
            e_date = form.cleaned_data['e_date']
            e_time = form.cleaned_data['e_time']
            description = form.cleaned_data['description']
            impact = form.cleaned_data['impact']
            coordinator = form.cleaned_data['coordinator']
            update = form.cleaned_data['update']
            broadcast = form.cleaned_data['broadcast']
            email_id = form.cleaned_data['email_id']
            started = form.cleaned_data['started']
            completed = form.cleaned_data['completed']

            # Combine the dates and times into datetime objects
            start = datetime.datetime.combine(s_date, s_time)
            end = datetime.datetime.combine(e_date, e_time)

            # Set the timezone
            tz = pytz.timezone(request.timezone)
            start = tz.localize(start)
            end = tz.localize(end)

            # Determine the status (form validation ensures the logic here)
            if completed:
                status = 'completed'
            elif started:
                status = 'started'
            else:
                status = 'planning'

            # Update the event
            Event.objects.filter(id=id).update(
                description=description,
                status=Status.objects.filter(
                    status=status).values('id')[0]['id'],
                start=start,
                end=end)

            # Update the impact analysis (if it's blank, make sure it's deleted, maybe they added it previously)
            if impact:
                Event_Impact.objects.filter(event_id=id).update(impact=impact)
            else:
                Event_Impact.objects.filter(event_id=id).delete()

            # Update the coordinator (if it's blank, make sure it's deleted, maybe they added it previously)
            if coordinator:
                Event_Coordinator.objects.filter(event_id=id).update(
                    coordinator=coordinator)
            else:
                Event_Coordinator.objects.filter(event_id=id).delete()

            # Add the update, if there is one, using the current time
            if update:
                # Create a datetime object for right now and add the server's timezone (whatever DJango has)
                time_now = datetime.datetime.now()
                time_now = pytz.timezone(settings.TIME_ZONE).localize(time_now)
                Event_Update(event_id=id,
                             date=time_now,
                             update=update,
                             user_id=request.user.id).save()

            # Add the email recipient.  If an email recipient is missing, then the broadcast email will not be checked.
            # In both cases, delete the existing email (because it will be re-added)
            Event_Email.objects.filter(event_id=id).delete()
            if email_id:
                Event_Email(event_id=id, email_id=email_id).save()

            # See if we are adding or subtracting services
            # The easiest thing to do here is remove all affected
            # services and re-add the ones indicated here

            # Remove first
            Event_Service.objects.filter(event_id=id).delete()

            # Now add (form validation confirms that there is at least 1)
            for service_id in affected_svcs:
                # Should be number only -- can't figure out how to validate
                # multiple checkboxes in the form
                if re.match(r'^\d+$', service_id):
                    Event_Service(event_id=id, service_id=service_id).save()

            # Send an email notification to the appropriate list about this maintenance, if requested.  Broadcast won't be
            # allowed to be true if an email address is not defined or if global email is disabled.
            if Config_Email.objects.filter(
                    id=Config_Email.objects.values('id')[0]['id']).values(
                        'enabled')[0]['enabled'] == 1 and broadcast:
                email = notify.email()
                email.email_event(id, email_id, request.timezone, False)

            # Clear the cache - don't discriminate and just clear everything that impacts events
            cache.delete_many(['timeline', 'events_ns', 'event_count_ns'])

            # Set a success message
            messages.add_message(request, messages.SUCCESS,
                                 'Maintenance successfully updated')

            # All done so redirect to the maintenance detail page so
            # the new data can be seen.
            return HttpResponseRedirect('/m_detail?id=%s' % id)

        else:
            messages.add_message(
                request, messages.ERROR,
                'Invalid data entered, please correct the errors below:')

            # Obtain the id so we can print the update page again
            if 'id' in request.POST:
                if re.match(r'^\d+$', request.POST['id']):
                    id = request.POST['id']
                else:
                    messages.add_message(
                        request, messages.ERROR,
                        'Improperly formatted maintenance ID - cannot update maintenance'
                    )
                    return HttpResponseRedirect('/admin')
            else:
                messages.add_message(
                    request, messages.ERROR,
                    'No maintenance ID given - cannot update maintenance')
                return HttpResponseRedirect('/admin')

    # Not a POST
    else:

        # Obtain the id
        if 'id' in request.GET:
            if re.match(r'^\d+$', request.GET['id']):
                id = request.GET['id']
            else:
                messages.add_message(
                    request, messages.ERROR,
                    'Improperly formatted maintenance ID - cannot update maintenance'
                )
                return HttpResponseRedirect('/admin')
        else:
            messages.add_message(
                request, messages.ERROR,
                'No maintenance ID given - cannot update maintenance')
            return HttpResponseRedirect('/admin')

        # In the case of a GET, we can acquire the proper services from the DB
        affected_svcs_tmp = Event.objects.filter(
            id=id).values('event_service__service_id')
        affected_svcs = []
        for service_id in affected_svcs_tmp:
            affected_svcs.append(service_id['event_service__service_id'])
        affected_svcs = list(affected_svcs)

        # Create a blank form
        form = UpdateMaintenanceForm()

    # Obtain the details
    # Obain the maintenance detail
    details = Event.objects.filter(id=id).values(
        'start', 'end', 'status__status', 'description',
        'event_impact__impact', 'event_coordinator__coordinator',
        'event_email__email__id', 'user__first_name', 'user__last_name')
    # If nothing was returned, send back to the home page
    if not details:
        messages.add_message(request, messages.ERROR,
                             'Invalid request: no such maintenance id.')
        return HttpResponseRedirect('/')

    # Obtain all current email addresses
    emails = Email.objects.values('id', 'email')

    # Obtain all services
    services = Service.objects.values('id',
                                      'service_name').order_by('service_name')

    start = details[0]['start']
    end = details[0]['end']

    # Set the timezone
    start = start.astimezone(pytz.timezone(request.timezone))
    end = end.astimezone(pytz.timezone(request.timezone))

    # Format the start/end date/time
    s_date = start.strftime("%Y-%m-%d")
    s_time = start.strftime("%H:%M")
    e_date = end.strftime("%Y-%m-%d")
    e_time = end.strftime("%H:%M")

    # Obtain any updates
    updates = Event_Update.objects.filter(event_id=id).values(
        'id', 'date', 'update').order_by('id')

    # Print the page
    return render_to_response('maintenance/m_update.html', {
        'title':
        'System Status Dashboard | Scheduled Maintenance Update',
        'details':
        details,
        'affected_svcs':
        affected_svcs,
        'services':
        services,
        'id':
        id,
        'form':
        form,
        's_date':
        s_date,
        's_time':
        s_time,
        'e_date':
        e_date,
        'e_time':
        e_time,
        'emails':
        emails,
        'email_enabled':
        Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]
                                    ['id']).values('enabled')[0]['enabled'],
        'updates':
        updates,
        'nav_section':
        'event',
        'nav_sub':
        'm_update'
    },
                              context_instance=RequestContext(request))
Example #7
0
def ireport(request):
    """Report View

    Accept a report from a user of an incident

    """

    logger.debug('%s view being executed.' % 'ireport.ireport')

    # If this functionality is disabled in the admin, let the user know
    enable_ireport = cache.get('enable_ireport')
    if enable_ireport == None:
        enable_ireport = Config_Ireport.objects.filter(
            id=Config_Ireport.objects.values('id')[0]['id']).values(
                'enabled')[0]['enabled']
        cache.set('enable_ireport', enable_ireport)
    if enable_ireport == 0:
        # Incident reports are disabled, send them to the homepage with an error message
        messages.add_message(
            request, messages.ERROR,
            'Your system administrator has disabled incident reports')
        return HttpResponseRedirect('/')

    # See if file uploads are anabled
    enable_uploads = Config_Ireport.objects.filter(
        id=Config_Ireport.objects.values('id')[0]['id']).values(
            'upload_enabled')[0]['upload_enabled']

    # If this is a POST, then check the input params and perform the
    # action, otherwise print the index page
    if request.method == 'POST':
        # Check the form elements
        form = ReportIncidentForm(request.POST, request.FILES)
        logger.debug('Form submit (POST): %s, with result: %s' %
                     ('ReportIncidentForm', form))

        if form.is_valid():
            # Obtain the cleaned data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            detail = form.cleaned_data['detail']
            extra = form.cleaned_data['extra']

            # Create a datetime object for right now
            report_time = datetime.datetime.now()

            # Add the server's timezone (whatever DJango is set to)
            report_time = pytz.timezone(
                settings.TIME_ZONE).localize(report_time)

            # Save the data
            # If file uploads are disabled but the user included them somehow, ignore them
            if enable_uploads == 1:
                if 'screenshot1' in request.FILES:
                    screenshot1 = request.FILES['screenshot1']
                else:
                    screenshot1 = ''

                if 'screenshot2' in request.FILES:
                    screenshot2 = request.FILES['screenshot2']
                else:
                    screenshot2 = ''

            # Screenshots are disabled
            else:
                screenshot1 = ''
                screenshot2 = ''

            # Save the data (if the admin has not setup the upload directory, it'll fail)
            try:
                Ireport(
                    date=report_time,
                    name=name,
                    email=email,
                    detail=detail,
                    extra=extra,
                    screenshot1=screenshot1,
                    screenshot2=screenshot2,
                ).save()
            except Exception as e:
                messages.add_message(request, messages.ERROR, e)
                return HttpResponseRedirect('/')

            # If email is enabled and report notifications are turned on, send an email to the pager address
            if Config_Email.objects.filter(id=Config_Email.objects.values(
                    'id')[0]['id']).values('enabled')[0]['enabled'] == 1:
                if Config_Ireport.objects.filter(
                        id=Config_Ireport.objects.values('id')[0]
                    ['id']).values('email_enabled')[0]['email_enabled'] == 1:
                    pager = notify.email()
                    pager.page(detail)

            # Give the user a thank you and let them know what to expect
            message = Config_Ireport.objects.filter(
                id=Config_Ireport.objects.values('id')[0]['id']).values(
                    'submit_message')[0]['submit_message']
            messages.add_message(request, messages.SUCCESS, message)
            return HttpResponseRedirect('/')

        # Invalid form
        else:
            messages.add_message(
                request, messages.ERROR,
                'Invalid data entered, please correct the errors below:')

    # Ok, its a GET or an invalid form so create a blank form
    else:
        form = ReportIncidentForm()

    # Print the page
    return render_to_response('ireport/ireport.html', {
        'title':
        'System Status Dashboard | Report Incident',
        'form':
        form,
        'enable_uploads':
        enable_uploads,
        'instructions':
        Config_Ireport.objects.filter(id=Config_Ireport.objects.values(
            'id')[0]['id']).values('instructions')[0]['instructions']
    },
                              context_instance=RequestContext(request))
def ireport(request):
    """Report View

    Accept a report from a user of an incident

    """

    logger.debug('%s view being executed.' % 'ireport.ireport')

    # If this functionality is disabled in the admin, let the user know
    enable_ireport = cache.get('enable_ireport')
    if enable_ireport == None:
        enable_ireport = Config_Ireport.objects.filter(id=Config_Ireport.objects.values('id')[0]['id']).values('enabled')[0]['enabled']
        cache.set('enable_ireport', enable_ireport)
    if enable_ireport == 0:
        # Incident reports are disabled, send them to the homepage with an error message
        messages.add_message(request, messages.ERROR, 'Your system administrator has disabled incident reports')
        return HttpResponseRedirect('/')

    # See if file uploads are anabled
    enable_uploads = Config_Ireport.objects.filter(id=Config_Ireport.objects.values('id')[0]['id']).values('upload_enabled')[0]['upload_enabled']

    # If this is a POST, then check the input params and perform the
    # action, otherwise print the index page
    if request.method == 'POST':
        # Check the form elements
        form = ReportIncidentForm(request.POST, request.FILES)
        logger.debug('Form submit (POST): %s, with result: %s' % ('ReportIncidentForm',form))

        if form.is_valid():
            # Obtain the cleaned data
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            detail = form.cleaned_data['detail']
            extra = form.cleaned_data['extra']

            # Create a datetime object for right now
            report_time = datetime.datetime.now()

            # Add the server's timezone (whatever DJango is set to)
            report_time = pytz.timezone(settings.TIME_ZONE).localize(report_time)

            # Save the data
            # If file uploads are disabled but the user included them somehow, ignore them
            if enable_uploads == 1:
                if 'screenshot1' in request.FILES:
                    screenshot1 = request.FILES['screenshot1']
                else:
                    screenshot1 = ''

                if 'screenshot2' in request.FILES:
                    screenshot2 = request.FILES['screenshot2']
                else:
                    screenshot2 = ''

            # Screenshots are disabled
            else:
                screenshot1 = ''
                screenshot2 = ''
            
            # Save the data (if the admin has not setup the upload directory, it'll fail)
            try:
                Ireport(date=report_time,
                        name=name,
                        email=email,
                        detail=detail,
                        extra=extra,
                        screenshot1=screenshot1,
                        screenshot2=screenshot2,
                       ).save()
            except Exception as e:
                messages.add_message(request, messages.ERROR, e)
                return HttpResponseRedirect('/')

            # If email is enabled and report notifications are turned on, send an email to the pager address
            if Config_Email.objects.filter(id=Config_Email.objects.values('id')[0]['id']).values('enabled')[0]['enabled'] == 1:
                if Config_Ireport.objects.filter(id=Config_Ireport.objects.values('id')[0]['id']).values('email_enabled')[0]['email_enabled'] == 1:
                    pager = notify.email()
                    pager.page(detail)

            # Give the user a thank you and let them know what to expect
            message = Config_Ireport.objects.filter(id=Config_Ireport.objects.values('id')[0]['id']).values('submit_message')[0]['submit_message']
            messages.add_message(request, messages.SUCCESS, message)
            return HttpResponseRedirect('/')
        
        # Invalid form
        else:
            messages.add_message(request, messages.ERROR, 'Invalid data entered, please correct the errors below:')

    # Ok, its a GET or an invalid form so create a blank form
    else:
        form = ReportIncidentForm()

    # Print the page
    return render_to_response(
       'ireport/ireport.html',
       {
          'title':'System Status Dashboard | Report Incident',
          'form':form,
          'enable_uploads':enable_uploads,
          'instructions':Config_Ireport.objects.filter(id=Config_Ireport.objects.values('id')[0]['id']).values('instructions')[0]['instructions']
       },
       context_instance=RequestContext(request)
    )