public function main()
    {
        $count_reports = reports::count();
        $count_reports_preview = reports_preview::count();
        ?>
		<div id="main" class="ui segment square-corners">
			<h4 class="ui header dividing">Общая информация</h4>

			<p>Всего планов в базе: <b><?php 
        echo $count_reports + $count_reports_preview;
        ?>
</b> (<b><?php 
        echo $count_reports;
        ?>
</b> полноценных и <b><?php 
        echo $count_reports_preview;
        ?>
</b> промежуточных).
		</div>
		<?php 
    }
 /**
  * Tests reports::fetch_incidents()
  * @test
  *
  * This tests compares the output SQL of fetch_incidents against a pre-defined SQL
  * statement based on dummy values. The objective of this test is to check whether
  * reports::fetch_incidents processes the parameters property
  */
 public function testFetchIncidents()
 {
     // Get random location and fetch the latitude and longitude
     $location = ORM::factory('location', testutils::get_random_id('location'));
     $longitude = $location->longitude;
     $latitude = $location->latitude;
     // Build the list of HTTP_GET parameters
     $filter_params = array('c' => array(3, 4, 5), 'start_loc' => $latitude . "," . $longitude, 'radius' => '20', 'mode' => array(1, 2), 'm' => array(1), 'from' => '07/07/2011', 'to' => '07/21/2011', 'v' => 1);
     // Add the report filter params to the list of HTTP_GET parameters
     $_GET = array_merge($_GET, $filter_params);
     // Get the incidents
     $incidents = reports::fetch_incidents();
     // Get the table prefix
     $table_prefix = Kohana::config('database.default.table_prefix');
     // Expected SQL statement; based on the $filter_params above
     $expected_sql = "SELECT DISTINCT i.id incident_id, i.incident_title, i.incident_description, i.incident_date, " . "i.incident_mode, i.incident_active, i.incident_verified, i.location_id, l.country_id, l.location_name, l.latitude, l.longitude " . ", ((ACOS(SIN(" . $latitude . " * PI() / 180) * SIN(l.`latitude` * PI() / 180) + COS(" . $latitude . " * PI() / 180) * " . "\tCOS(l.`latitude` * PI() / 180) * COS((" . $longitude . " - l.`longitude`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance " . "FROM " . $table_prefix . "incident i " . "INNER JOIN " . $table_prefix . "location l ON (i.location_id = l.id) " . "INNER JOIN " . $table_prefix . "incident_category ic ON (ic.incident_id = i.id) " . "INNER JOIN " . $table_prefix . "category c ON (ic.category_id = c.id) " . "WHERE i.incident_active = 1 " . "AND (c.id IN (" . implode(",", $filter_params['c']) . ") OR c.parent_id IN (" . implode(",", $filter_params['c']) . ")) " . "AND c.category_visible = 1 " . "AND i.incident_mode IN (" . implode(",", $filter_params['mode']) . ") " . "AND i.incident_date >= \"2011-07-07\" " . "AND i.incident_date <= \"2011-07-21\" " . "AND i.id IN (SELECT DISTINCT incident_id FROM " . $table_prefix . "media WHERE media_type IN (" . implode(",", $filter_params['m']) . ")) " . "AND i.incident_verified IN (" . $filter_params['v'] . ") " . "HAVING distance <= " . $filter_params['radius'] . " " . "ORDER BY i.incident_date DESC ";
     // Test the expected SQL against the returned
     $this->assertEquals($expected_sql, $incidents->sql());
     // Garbage collection
     unset($location, $latitude, $longitude, $incidents, $filter_params);
 }
Example #3
0
 /**
  * Tests reports::fetch_incidents()
  * @test
  *
  * This tests compares the output SQL of fetch_incidents against a pre-defined SQL
  * statement based on dummy values. The objective of this test is to check whether
  * reports::fetch_incidents processes the parameters property
  */
 public function testFetchIncidents()
 {
     // Get random location and fetch the latitude and longitude
     $location = ORM::factory('location', testutils::get_random_id('location'));
     $longitude = $location->longitude;
     $latitude = $location->latitude;
     // Build the list of HTTP_GET parameters
     $filter_params = array('c' => array(3, 4, 5), 'start_loc' => $latitude . "," . $longitude, 'radius' => '20', 'mode' => array(1, 2), 'm' => array(1), 'from' => '07/07/2011', 'to' => '07/21/2011', 'v' => 1);
     // Add the report filter params to the list of HTTP_GET parameters
     $_GET = array_merge($_GET, $filter_params);
     // Get the incidents
     $incidents = reports::fetch_incidents();
     // Get the table prefix
     $table_prefix = Kohana::config('database.default.table_prefix');
     // Expected SQL statement; based on the $filter_params above
     // Distance calculation deets:
     // 60 = nautical miles per degree of latitude, 1.1515 miles in every nautical mile, 1.609344 km = 1 km
     // more details about the math here: http://sgowtham.net/ramblings/2009/08/04/php-calculating-distance-between-two-locations-given-their-gps-coordinates/
     $expected_sql = "SELECT DISTINCT i.id incident_id, i.incident_title, i.incident_description, i.incident_date, " . "i.incident_mode, i.incident_active, i.incident_verified, i.location_id, l.country_id, l.location_name, l.latitude, l.longitude " . ", ((ACOS(SIN(" . $latitude . " * PI() / 180) * SIN(l.`latitude` * PI() / 180) + COS(" . $latitude . " * PI() / 180) * " . "\tCOS(l.`latitude` * PI() / 180) * COS((" . $longitude . " - l.`longitude`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515 * 1.609344) AS distance " . "FROM " . $table_prefix . "incident i " . "LEFT JOIN " . $table_prefix . "location l ON (i.location_id = l.id) " . "LEFT JOIN " . $table_prefix . "incident_category ic ON (ic.incident_id = i.id) " . "LEFT JOIN " . $table_prefix . "category c ON (ic.category_id = c.id) " . "WHERE i.incident_active = 1 " . "AND (c.id IN (" . implode(",", $filter_params['c']) . ") OR c.parent_id IN (" . implode(",", $filter_params['c']) . ")) " . "AND c.category_visible = 1 " . "AND i.incident_mode IN (" . implode(",", $filter_params['mode']) . ") " . "AND i.incident_date >= \"2011-07-07 00:00:00\" " . "AND i.incident_date <= \"2011-07-21 23:59:59\" " . "AND i.id IN (SELECT DISTINCT incident_id FROM " . $table_prefix . "media WHERE media_type IN (" . implode(",", $filter_params['m']) . ")) " . "AND i.incident_verified IN (" . $filter_params['v'] . ") " . "HAVING distance <= " . $filter_params['radius'] . " " . "ORDER BY i.incident_date DESC ";
     // Test the expected SQL against the returned
     $this->assertEquals($expected_sql, $incidents->sql());
     // Garbage collection
     unset($location, $latitude, $longitude, $incidents, $filter_params);
 }
 /**
  * This function updates the categories associated
  * with this well
  * @param $incident_id the id of the report for this well
  * @param $ivr_data the data we just got from the IVR
  * @return none
  */
 private function update_categories($incident_id, $ivr_data)
 {
     //find the two categories that apply to wells and IVR data
     $functioning_category = ORM::factory('category')->where('category_title', api_ivr::$wellstatus['functioning'])->find();
     if (!$functioning_category->loaded) {
         $this->response['status'] = 'Error';
         $this->response['message'][] = "Could not find well functioning category: " . api_ivr::$wellstatus['functioning'];
         $this->errors_found = TRUE;
         return;
     }
     $malfunctioning_category = ORM::factory('category')->where('category_title', api_ivr::$wellstatus['malfunctioning'])->find();
     if (!$malfunctioning_category->loaded) {
         $this->response['status'] = 'Error';
         $this->response['message'][] = "Could not find well malfunctioning category: " . api_ivr::$wellstatus['malfunctioning'];
         $this->errors_found = TRUE;
         return;
     }
     //so there are easier ways to do this, but we've done things in this way so we can be compatible with the
     //Version Categories plugin. We try to simulate a report being updated via a Post command
     //now add the correct category
     $chosen_cat_id = $malfunctioning_category->id;
     $remove_cat_id = $functioning_category->id;
     if ($ivr_data->well_working) {
         $chosen_cat_id = $functioning_category->id;
         $remove_cat_id = $malfunctioning_category->id;
     }
     //get the current cats for this incident
     $new_cats = array();
     $current_cats = ORM::factory('incident_category')->where('incident_id', $incident_id)->find_all();
     foreach ($current_cats as $c) {
         if ($c->category_id != $remove_cat_id) {
             $new_cats[$c->category_id] = $c->category_id;
         }
     }
     $new_cats[$chosen_cat_id] = $chosen_cat_id;
     $post = new dummy_post($new_cats);
     $incident = ORM::factory('incident')->where('id', $incident_id)->find();
     reports::save_category($post, $incident);
     /*
     // Event so the category change plugin can record the date and time
     // that categories are changed and what they were changed to
     $event_data = array('id'=>$incident_id, 'new_categories'=>$new_cats);
     Event::run('ushahidi_action.report_categories_changing', $event_data);
     
     /*
     
     //now remove any current category associates between these two categories and our well
     ORM::factory('incident_category')
     	->where(array('category_id'=> $remove_cat_id, 'incident_id'=>$incident_id))
     	->delete_all();
     				
     //now add in the right category
     $cat = ORM::factory('incident_category');
     $cat->incident_id = $incident_id;
     $cat->category_id = $chosen_cat_id;
     $cat->save();
     */
 }
Example #5
0
 /**
  * Create a report and assign it to one or more categories and set verification
  */
 public function __response_create_report($vars)
 {
     $categories = array();
     if (isset($vars['add_category'])) {
         $categories = $vars['add_category'];
     }
     $verify = 0;
     if (isset($vars['verify'])) {
         $verify = (int) $vars['verify'];
     }
     $approve = 0;
     if (isset($vars['approve'])) {
         $approve = (int) $vars['approve'];
     }
     // Grab the location_id or create one if we can
     $location_id = 0;
     if (isset($this->data->location_id)) {
         $location_id = $this->data->location_id;
     } elseif (isset($this->data->latitude) and isset($this->data->longitude)) {
         $location_name = map::reverse_geocode($this->data->latitude, $this->data->longitude);
         // In case our location name is too long, chop off the end
         $location_name = substr_replace($location_name, '', 250);
         $location_data = (object) array('location_name' => $location_name, 'latitude' => $this->data->latitude, 'longitude' => $this->data->longitude);
         $location = new Location_Model();
         reports::save_location($location_data, $location);
         $location_id = $location->id;
     }
     // We can only create reports if we have location.
     if ($location_id == FALSE or $location_id == 0) {
         return false;
     }
     // Build title
     // Build title & description
     // If this is a message
     if (isset($this->data->message)) {
         $incident_title = $this->data->message;
         $incident_description = $this->data->message;
         $incident_date = $this->data->message_date;
         // If we're got more message detail, make that the description
         if (!empty($message->message_detail)) {
             $incident_description = $this->data->message_detail;
         }
     } elseif (isset($this->data->item_title)) {
         $incident_title = html::strip_tags(html_entity_decode(html_entity_decode($this->data->item_title, ENT_QUOTES)));
         $incident_description = html::clean(html_entity_decode($this->data->item_description, ENT_QUOTES));
         $incident_date = $this->data->item_date;
     }
     // Override title from action options
     if (!empty($vars['report_title'])) {
         $incident_title = $vars['report_title'];
     }
     // Save Incident
     $incident = new Incident_Model();
     $incident->location_id = $location_id;
     $incident->incident_title = $incident_title;
     $incident->incident_description = $incident_description;
     $incident->incident_date = $incident_date;
     $incident->incident_active = $approve;
     $incident->incident_verified = $verify;
     $incident->incident_dateadd = date("Y-m-d H:i:s", time());
     $incident->save();
     // Conflicted.. do I run report add here? Potential to create a mess with action triggers?
     //Event::run('ushahidi_action.report_add', $incident);
     // Save media
     if (isset($this->data->item_title)) {
         $news = new Media_Model();
         $news->location_id = $incident->location_id;
         $news->incident_id = $incident->id;
         $news->media_type = 4;
         // News
         $news->media_link = $this->data->item_link;
         $news->media_date = $this->data->item_date;
         $news->save();
     }
     $incident_id = $incident->id;
     foreach ($categories as $category_id) {
         // Assign Category
         Incident_Category_Model::assign_category_to_incident($incident_id, $category_id);
     }
     // Link message with incident?
     if (isset($this->data->message) and isset($this->data->id)) {
         $message = new Message_Model($this->data->id);
         $message->incident_id = $incident_id;
         $message->save();
     } elseif (isset($this->data->item_title) and isset($this->data->id)) {
         $item = new Feed_Item_Model($this->data->id);
         $item->incident_id = $incident_id;
         $item->save();
     }
     return TRUE;
 }
Example #6
0
 /**
  * Submits a new report.
  */
 public function submit($id = FALSE, $saved = FALSE)
 {
     $db = new Database();
     // First, are we allowed to submit new reports?
     if (!Kohana::config('settings.allow_reports')) {
         url::redirect(url::site() . 'main');
     }
     $this->template->header->this_page = 'reports_submit';
     $this->template->content = new View('reports_submit');
     // Setup and initialize form field names
     $form = array('incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'geometry' => array(), 'location_name' => '', 'country_id' => '', 'incident_category' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '', 'form_id' => '', 'custom_field' => array());
     //	copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = $saved == 'saved';
     // Initialize Default Values
     $form['incident_date'] = date("m/d/Y", time());
     $form['incident_hour'] = date('g');
     $form['incident_minute'] = date('i');
     $form['incident_ampm'] = date('a');
     // initialize custom field array
     $form['custom_field'] = customforms::get_custom_form_fields($id, '', true);
     //GET custom forms
     $forms = array();
     foreach (customforms::get_custom_forms() as $custom_forms) {
         $forms[$custom_forms->id] = $custom_forms->form_title;
     }
     $this->template->content->forms = $forms;
     // check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite $_POST fields with our own things
         $post = array_merge($_POST, $_FILES);
         // Test to see if things passed the rule checks
         if (reports::validate($post)) {
             // STEP 1: SAVE LOCATION
             $location = new Location_Model();
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model();
             reports::save_report($post, $incident, $location->id);
             // STEP 2b: SAVE INCIDENT GEOMETRIES
             reports::save_report_geometry($post, $incident);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE CUSTOM FORM FIELDS
             reports::save_custom_fields($post, $incident);
             // STEP 6: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // Action::report_add/report_submit - Added a New Report
             //++ Do we need two events for this? Or will one suffice?
             Event::run('ushahidi_action.report_add', $incident);
             Event::run('ushahidi_action.report_submit', $post);
             url::redirect('reports/thanks');
         } else {
             // Repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // Populate the error fields, if any
             $errors = arr::overwrite($errors, $post->errors('report'));
             $form_error = TRUE;
         }
     }
     // Retrieve Country Cities
     $default_country = Kohana::config('settings.default_country');
     $this->template->content->cities = $this->_get_cities($default_country);
     $this->template->content->multi_country = Kohana::config('settings.multi_country');
     $this->template->content->id = $id;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $categories = $this->get_categories($form['incident_category']);
     $this->template->content->categories = $categories;
     // Pass timezone
     $this->template->content->site_timezone = Kohana::config('settings.site_timezone');
     // Pass the submit report message
     $this->template->content->site_submit_report_message = Kohana::config('settings.site_submit_report_message');
     // Retrieve Custom Form Fields Structure
     $this->template->content->custom_forms = new View('reports_submit_custom_forms');
     $disp_custom_fields = customforms::get_custom_form_fields($id, $form['form_id'], FALSE);
     $this->template->content->disp_custom_fields = $disp_custom_fields;
     $this->template->content->stroke_width_array = $this->_stroke_width_array();
     $this->template->content->custom_forms->disp_custom_fields = $disp_custom_fields;
     $this->template->content->custom_forms->form = $form;
     // Javascript Header
     $this->themes->map_enabled = TRUE;
     $this->themes->datepicker_enabled = TRUE;
     $this->themes->treeview_enabled = TRUE;
     $this->themes->colorpicker_enabled = TRUE;
     $this->themes->js = new View('reports_submit_js');
     $this->themes->js->default_map = Kohana::config('settings.default_map');
     $this->themes->js->default_zoom = Kohana::config('settings.default_zoom');
     if (!$form['latitude'] or !$form['latitude']) {
         $this->themes->js->latitude = Kohana::config('settings.default_lat');
         $this->themes->js->longitude = Kohana::config('settings.default_lon');
     } else {
         $this->themes->js->latitude = $form['latitude'];
         $this->themes->js->longitude = $form['longitude'];
     }
     $this->themes->js->geometries = $form['geometry'];
     // Rebuild Header Block
     $this->template->header->header_block = $this->themes->header_block();
 }
Example #7
0
<!--
Developer : chintan khatri
Date : 01-10-2016
-->
<!DOCTYPE html>
<?php 
include_once './class.php';
$db = new reports();
?>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
        <title>Alpha</title>

        <!-- CSS  -->
        <?php 
include_once './theme-part/top_head.php';
?>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <style type="text/css">
            html, body {
                height:100%;
            }
            #box {
                height:80%;
                background:#331266;
            }
            #container {
                position:relative;
                height:100%;
Example #8
0
/*
 * Plugin name: Reports
 * Description: View various reports, e.g. HTTP request staistics from GoAccess
 * Version: 1.0
 */
namespace WPPalvelu;

if (!class_exists('Reports')) {
    class reports
    {
        public static function load()
        {
            add_action('wp_ajax_seravo_reports', function () {
                require_once dirname(__FILE__) . '/../lib/reports-ajax.php';
                wp_die();
            });
            add_action('admin_menu', array(__CLASS__, 'register_reports_page'));
            // TODO: check if this hook actually ever fires for mu-plugins
            register_activation_hook(__FILE__, array(__CLASS__, 'register_view_reports_capability'));
        }
        public static function register_reports_page()
        {
            add_submenu_page('tools.php', 'Reports', 'Reports', 'manage_options', 'reports_page', array(__CLASS__, 'load_reports_page'));
        }
        public static function load_reports_page()
        {
            require_once dirname(__FILE__) . '/../lib/reports-page.php';
        }
    }
    reports::load();
}
Example #9
0
 /**
  * Edit a report
  * @param bool|int $id The id no. of the report
  * @param bool|string $saved
  */
 public function edit($id = FALSE, $saved = FALSE)
 {
     $db = new Database();
     // If user doesn't have access, redirect to dashboard
     if (!$this->auth->has_permission("reports_edit")) {
         url::redirect('admin/dashboard');
     }
     $this->template->content = new View('admin/reports/edit');
     $this->template->content->title = Kohana::lang('ui_admin.create_report');
     // Setup and initialize form field names
     $form = array('location_id' => '', 'form_id' => '', 'locale' => '', 'incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'geometry' => array(), 'location_name' => '', 'country_id' => '', 'country_name' => '', 'incident_category' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '', 'custom_field' => array(), 'incident_active' => '', 'incident_verified' => '', 'incident_zoom' => '');
     // Copy the form as errors, so the errors will be stored with keys
     // corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = $saved == 'saved';
     // Initialize Default Values
     $form['locale'] = Kohana::config('locale.language');
     //$form['latitude'] = Kohana::config('settings.default_lat');
     //$form['longitude'] = Kohana::config('settings.default_lon');
     $form['incident_date'] = date("m/d/Y", time());
     $form['incident_hour'] = date('h');
     $form['incident_minute'] = date('i');
     $form['incident_ampm'] = date('a');
     $form['country_id'] = Kohana::config('settings.default_country');
     // get the form ID if relevant, kind of a hack
     // to just hit the database like this for one
     // tiny bit of info then throw away the DB model object,
     // but seems to be what everyone else does, so
     // why should I care. Just know that when your Ush system crashes
     // because you have 1000 concurrent users you'll need to do this
     // correctly. Etherton.
     $form['form_id'] = 1;
     $form_id = $form['form_id'];
     if ($id and Incident_Model::is_valid_incident($id, FALSE)) {
         $form_id = ORM::factory('incident', $id)->form_id;
     }
     // Initialize custom field array
     $form['custom_field'] = customforms::get_custom_form_fields($id, $form_id, TRUE);
     // Locale (Language) Array
     $this->template->content->locale_array = Kohana::config('locale.all_languages');
     // Create Categories
     $this->template->content->new_categories_form = $this->_new_categories_form_arr();
     // Time formatting
     $this->template->content->hour_array = $this->_hour_array();
     $this->template->content->minute_array = $this->_minute_array();
     $this->template->content->ampm_array = $this->_ampm_array();
     $this->template->content->stroke_width_array = $this->_stroke_width_array();
     // Get Countries
     $countries = array();
     foreach (ORM::factory('country')->orderby('country')->find_all() as $country) {
         // Create a list of all countries
         $this_country = $country->country;
         if (strlen($this_country) > 35) {
             $this_country = substr($this_country, 0, 35) . "...";
         }
         $countries[$country->id] = $this_country;
     }
     // Initialize Default Value for Hidden Field Country Name,
     // just incase Reverse Geo coding yields no result
     $form['country_name'] = $countries[$form['country_id']];
     $this->template->content->countries = $countries;
     // GET custom forms
     $forms = array();
     foreach (customforms::get_custom_forms(FALSE) as $custom_forms) {
         $forms[$custom_forms->id] = $custom_forms->form_title;
     }
     $this->template->content->forms = $forms;
     // Get the incident media
     $incident_media = Incident_Model::is_valid_incident($id, FALSE) ? ORM::factory('incident', $id)->media : FALSE;
     $this->template->content->incident_media = $incident_media;
     // Are we creating this report from SMS/Email/Twitter?
     // If so retrieve message
     if (isset($_GET['mid']) and intval($_GET['mid']) > 0) {
         $message_id = intval($_GET['mid']);
         $service_id = "";
         $message = ORM::factory('message', $message_id);
         if ($message->loaded and $message->message_type == 1) {
             $service_id = $message->reporter->service_id;
             // Has a report already been created for this Message?
             if ($message->incident_id != 0) {
                 // Redirect to report
                 url::redirect('admin/reports/edit/' . $message->incident_id);
             }
             $this->template->content->show_messages = TRUE;
             $incident_description = $message->message;
             if (!empty($message->message_detail)) {
                 $form['incident_title'] = $message->message;
                 $incident_description = $message->message_detail;
             }
             $form['incident_description'] = $incident_description;
             $form['incident_date'] = date('m/d/Y', strtotime($message->message_date));
             $form['incident_hour'] = date('h', strtotime($message->message_date));
             $form['incident_minute'] = date('i', strtotime($message->message_date));
             $form['incident_ampm'] = date('a', strtotime($message->message_date));
             $form['person_first'] = $message->reporter->reporter_first;
             $form['person_last'] = $message->reporter->reporter_last;
             // Does the message itself have a location?
             if ($message->latitude != NULL and $message->longitude != NULL) {
                 $form['latitude'] = $message->latitude;
                 $form['longitude'] = $message->longitude;
             } elseif ($message->reporter->location->loaded) {
                 $form['location_id'] = $message->reporter->location->id;
                 $form['latitude'] = $message->reporter->location->latitude;
                 $form['longitude'] = $message->reporter->location->longitude;
                 $form['location_name'] = $message->reporter->location->location_name;
             }
             // Events to manipulate an already known location
             Event::run('ushahidi_action.location_from', $message_from = $message->message_from);
             // Filter location name
             Event::run('ushahidi_filter.location_name', $form['location_name']);
             // Filter //location find
             Event::run('ushahidi_filter.location_find', $form['location_find']);
             // Retrieve Last 5 Messages From this account
             $this->template->content->all_messages = ORM::factory('message')->where('reporter_id', $message->reporter_id)->orderby('message_date', 'desc')->limit(5)->find_all();
         } else {
             $message_id = "";
             $this->template->content->show_messages = FALSE;
         }
     } else {
         $this->template->content->show_messages = FALSE;
     }
     // Are we creating this report from a Newsfeed?
     if (isset($_GET['fid']) and intval($_GET['fid']) > 0) {
         $feed_item_id = intval($_GET['fid']);
         $feed_item = ORM::factory('feed_item', $feed_item_id);
         if ($feed_item->loaded) {
             // Has a report already been created for this Feed item?
             if ($feed_item->incident_id != 0) {
                 // Redirect to report
                 url::redirect('admin/reports/edit/' . $feed_item->incident_id);
             }
             $form['incident_title'] = $feed_item->item_title;
             $form['incident_description'] = $feed_item->item_description;
             $form['incident_date'] = date('m/d/Y', strtotime($feed_item->item_date));
             $form['incident_hour'] = date('h', strtotime($feed_item->item_date));
             $form['incident_minute'] = date('i', strtotime($feed_item->item_date));
             $form['incident_ampm'] = date('a', strtotime($feed_item->item_date));
             // News Link
             $form['incident_news'][0] = $feed_item->item_link;
             // Does this newsfeed have a geolocation?
             if ($feed_item->location_id) {
                 $form['location_id'] = $feed_item->location_id;
                 $form['latitude'] = $feed_item->location->latitude;
                 $form['longitude'] = $feed_item->location->longitude;
                 $form['location_name'] = $feed_item->location->location_name;
             }
             // HT: new code
             $feed_item_categories = ORM::factory('feed_item_category')->where('feed_item_id', $feed_item->id)->select_list('id', 'category_id');
             if ($feed_item_categories) {
                 foreach ($feed_item_categories as $feed_item_category) {
                     $form['incident_category'][] = $feed_item_category;
                 }
             }
             // HT: end of new code
         } else {
             $feed_item_id = "";
         }
     }
     // Check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite
         // $_POST fields with our own things
         $post = array_merge($_POST, $_FILES);
         // Check if the service id exists
         if (isset($service_id) and intval($service_id) > 0) {
             $post = array_merge($post, array('service_id' => $service_id));
         }
         // Check if the incident id is valid an add it to the post data
         if (Incident_Model::is_valid_incident($id, FALSE)) {
             $post = array_merge($post, array('incident_id' => $id));
         }
         /**
          * NOTES - E.Kala July 27, 2011
          *
          * Previously, the $post parameter for this event was a Validation
          * object. Now it's an array (i.e. the raw data without any validation rules applied to them).
          * As such, all plugins making use of this event shall have to be updated
          */
         // Action::report_submit_admin - Report Posted
         Event::run('ushahidi_action.report_submit_admin', $post);
         // Validate
         if (reports::validate($post)) {
             // Yes! everything is valid
             $location_id = $post->location_id;
             // STEP 1: SAVE LOCATION
             $location = new Location_Model($location_id);
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model($id);
             reports::save_report($post, $incident, $location->id);
             // STEP 2b: Record Approval/Verification Action
             reports::verify_approve($incident);
             // STEP 2c: SAVE INCIDENT GEOMETRIES
             reports::save_report_geometry($post, $incident);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // STEP 6a: SAVE LINK TO REPORTER MESSAGE
             // We're creating a report from a message with this option
             if (isset($message_id) and intval($message_id) > 0) {
                 $savemessage = ORM::factory('message', $message_id);
                 if ($savemessage->loaded) {
                     $savemessage->incident_id = $incident->id;
                     $savemessage->save();
                     // Does Message Have Attachments?
                     // Add Attachments
                     $attachments = ORM::factory("media")->where("message_id", $savemessage->id)->find_all();
                     foreach ($attachments as $attachment) {
                         $attachment->incident_id = $incident->id;
                         $attachment->save();
                     }
                 }
             }
             // STEP 6b: SAVE LINK TO NEWS FEED
             // We're creating a report from a newsfeed with this option
             if (isset($feed_item_id) and intval($feed_item_id) > 0) {
                 $savefeed = ORM::factory('feed_item', $feed_item_id);
                 if ($savefeed->loaded) {
                     $savefeed->incident_id = $incident->id;
                     $savefeed->location_id = $location->id;
                     $savefeed->save();
                 }
             }
             // STEP 7: SAVE CUSTOM FORM FIELDS
             reports::save_custom_fields($post, $incident);
             // Action::report_edit - Edited a Report
             Event::run('ushahidi_action.report_edit', $incident);
             // SAVE AND CLOSE?
             switch ($post->save) {
                 case 1:
                 case 'dontclose':
                     // Save but don't close
                     url::redirect('admin/reports/edit/' . $incident->id . '/saved');
                     break;
                 case 'addnew':
                     // Save and add new
                     url::redirect('admin/reports/edit/0/saved');
                     break;
                 default:
                     // Save and close
                     url::redirect('admin/reports/');
             }
         } else {
             // Repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // Populate the error fields, if any
             $errors = arr::merge($errors, $post->errors('report'));
             $form_error = TRUE;
         }
     } else {
         if (Incident_Model::is_valid_incident($id, FALSE)) {
             // Retrieve Current Incident
             $incident = ORM::factory('incident', $id);
             if ($incident->loaded == TRUE) {
                 // Retrieve Categories
                 $incident_category = array();
                 foreach ($incident->incident_category as $category) {
                     $incident_category[] = $category->category_id;
                 }
                 // Retrieve Media
                 $incident_news = array();
                 $incident_video = array();
                 $incident_photo = array();
                 foreach ($incident->media as $media) {
                     if ($media->media_type == 4) {
                         $incident_news[] = $media->media_link;
                     } elseif ($media->media_type == 2) {
                         $incident_video[] = $media->media_link;
                     } elseif ($media->media_type == 1) {
                         $incident_photo[] = $media->media_link;
                     }
                 }
                 // Get Geometries via SQL query as ORM can't handle Spatial Data
                 $sql = "SELECT AsText(geometry) as geometry, geometry_label,\n\t\t\t\t\t\tgeometry_comment, geometry_color, geometry_strokewidth\n\t\t\t\t\t\tFROM " . Kohana::config('database.default.table_prefix') . "geometry\n\t\t\t\t\t\tWHERE incident_id = ?";
                 $query = $db->query($sql, $id);
                 foreach ($query as $item) {
                     $geometry = array("geometry" => $item->geometry, "label" => $item->geometry_label, "comment" => $item->geometry_comment, "color" => $item->geometry_color, "strokewidth" => $item->geometry_strokewidth);
                     $form['geometry'][] = json_encode($geometry);
                 }
                 // Combine Everything
                 $incident_arr = array('location_id' => $incident->location->id, 'form_id' => $incident->form_id, 'locale' => $incident->locale, 'incident_title' => $incident->incident_title, 'incident_description' => $incident->incident_description, 'incident_date' => date('m/d/Y', strtotime($incident->incident_date)), 'incident_hour' => date('h', strtotime($incident->incident_date)), 'incident_minute' => date('i', strtotime($incident->incident_date)), 'incident_ampm' => date('a', strtotime($incident->incident_date)), 'latitude' => $incident->location->latitude, 'longitude' => $incident->location->longitude, 'location_name' => $incident->location->location_name, 'country_id' => $incident->location->country_id, 'incident_category' => $incident_category, 'incident_news' => $incident_news, 'incident_video' => $incident_video, 'incident_photo' => $incident_photo, 'person_first' => $incident->incident_person->person_first, 'person_last' => $incident->incident_person->person_last, 'person_email' => $incident->incident_person->person_email, 'custom_field' => customforms::get_custom_form_fields($id, $incident->form_id, TRUE, 'submit'), 'incident_active' => $incident->incident_active, 'incident_verified' => $incident->incident_verified, 'incident_zoom' => $incident->incident_zoom);
                 // Merge To Form Array For Display
                 $form = arr::overwrite($form, $incident_arr);
             } else {
                 // Redirect
                 url::redirect('admin/reports/');
             }
         }
     }
     $this->template->content->id = $id;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     // Retrieve Custom Form Fields Structure
     $this->template->content->custom_forms = new View('reports/submit_custom_forms');
     $disp_custom_fields = customforms::get_custom_form_fields($id, $form['form_id'], FALSE, "view");
     $custom_field_mismatch = customforms::get_edit_mismatch($form['form_id']);
     // Quick hack to make sure view-only fields have data set
     foreach ($custom_field_mismatch as $id => $field) {
         $form['custom_field'][$id] = $disp_custom_fields[$id]['field_response'];
     }
     $this->template->content->custom_forms->disp_custom_fields = $disp_custom_fields;
     $this->template->content->custom_forms->custom_field_mismatch = $custom_field_mismatch;
     $this->template->content->custom_forms->form = $form;
     // Retrieve Previous & Next Records
     $previous = ORM::factory('incident')->where('id < ', $id)->orderby('id', 'desc')->find();
     $previous_url = $previous->loaded ? url::site('admin/reports/edit/' . $previous->id) : url::site('admin/reports/');
     $next = ORM::factory('incident')->where('id > ', $id)->orderby('id', 'desc')->find();
     $next_url = $next->loaded ? url::site('admin/reports/edit/' . $next->id) : url::site('admin/reports/');
     $this->template->content->previous_url = $previous_url;
     $this->template->content->next_url = $next_url;
     // Javascript Header
     $this->themes->map_enabled = TRUE;
     $this->themes->colorpicker_enabled = TRUE;
     $this->themes->treeview_enabled = TRUE;
     $this->themes->json2_enabled = TRUE;
     $this->themes->js = new View('reports/submit_edit_js');
     $this->themes->js->edit_mode = TRUE;
     $this->themes->js->default_map = Kohana::config('settings.default_map');
     $this->themes->js->default_zoom = Kohana::config('settings.default_zoom');
     if (!$form['latitude'] or !$form['latitude']) {
         $this->themes->js->latitude = Kohana::config('settings.default_lat');
         $this->themes->js->longitude = Kohana::config('settings.default_lon');
     } else {
         $this->themes->js->latitude = $form['latitude'];
         $this->themes->js->longitude = $form['longitude'];
     }
     $this->themes->js->incident_zoom = $form['incident_zoom'];
     $this->themes->js->geometries = $form['geometry'];
     // Inline Javascript
     $this->template->content->date_picker_js = $this->_date_picker_js();
     $this->template->content->color_picker_js = $this->_color_picker_js();
     $this->template->content->new_category_toggle_js = $this->_new_category_toggle_js();
     // Pack Javascript
     $myPacker = new javascriptpacker($this->themes->js, 'Normal', FALSE, FALSE);
     $this->themes->js = $myPacker->pack();
 }
 /**
  * The actual reporting -
  *
  * @return int
  */
 private function _submit_report()
 {
     // setup and initialize form field names
     $form = array('location_id' => '', 'incident_id' => '', 'incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'location_name' => '', 'country_id' => '', 'incident_category' => '', 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '', 'incident_active ' => '', 'incident_verified' => '');
     $errors = $form;
     // check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite
         // $_POST fields with our own things
         $post = array_merge($_POST, $_FILES);
         $post['incident_category'] = explode(',', $post['incident_category']);
         // Action::report_submit_admin - Report Posted
         Event::run('ushahidi_action.report_submit_admin', $post);
         // Test to see if things passed the rule checks
         if (reports::validate($post, TRUE)) {
             // Yes! everything is valid
             $location_id = $post->location_id;
             // STEP 1: SAVE LOCATION
             $location = new Location_Model($location_id);
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident_id = $post->incident_id;
             $incident = new Incident_Model($incident_id);
             reports::save_report($post, $incident, $location->id);
             // STEP 2b: Record Approval/Verification Action
             $verify = new Verify_Model();
             reports::verify_approve($post, $verify, $incident);
             // STEP 2c: SAVE INCIDENT GEOMETRIES
             reports::save_report_geometry($post, $incident);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // Action::report_edit - Edited a Report
             Event::run('ushahidi_action.report_edit', $incident);
             // Success
             return $this->response(0);
         } else {
             // populate the error fields, if any
             $errors = arr::overwrite($errors, $post->errors('report'));
             foreach ($errors as $error_item => $error_description) {
                 if (!is_array($error_description)) {
                     $this->error_messages .= $error_description;
                     if ($error_description != end($errors)) {
                         $this->error_messages .= " - ";
                     }
                 }
             }
             //FAILED!!! //validation error
             return $this->response(1, $this->error_messages);
         }
     } else {
         // Not sent by post method.
         return $this->response(3);
     }
 }
Example #11
0
 /**
  * Edit a report
  * @param bool|int $id The id no. of the report
  * @param bool|string $saved
  */
 function edit($id = false, $saved = false)
 {
     $db = new Database();
     $this->template->content = new View('members/reports_edit');
     $this->template->content->title = Kohana::lang('ui_admin.create_report');
     // setup and initialize form field names
     $form = array('location_id' => '', 'form_id' => '', 'locale' => '', 'incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'geometry' => array(), 'location_name' => '', 'country_id' => '', 'incident_category' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '', 'custom_field' => array(), 'incident_source' => '', 'incident_information' => '', 'incident_zoom' => '');
     //	copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     if ($saved == 'saved') {
         $form_saved = TRUE;
     } else {
         $form_saved = FALSE;
     }
     // Initialize Default Values
     $form['locale'] = Kohana::config('locale.language');
     //$form['latitude'] = Kohana::config('settings.default_lat');
     //$form['longitude'] = Kohana::config('settings.default_lon');
     $form['country_id'] = Kohana::config('settings.default_country');
     $form['incident_date'] = date("m/d/Y", time());
     $form['incident_hour'] = date('h');
     $form['incident_minute'] = date('i');
     $form['incident_ampm'] = date('a');
     // initialize custom field array
     $form['custom_field'] = $this->_get_custom_form_fields($id, '', true);
     // Locale (Language) Array
     $this->template->content->locale_array = Kohana::config('locale.all_languages');
     // Create Categories
     $this->template->content->categories = $this->_get_categories();
     // Time formatting
     $this->template->content->hour_array = $this->_hour_array();
     $this->template->content->minute_array = $this->_minute_array();
     $this->template->content->ampm_array = $this->_ampm_array();
     $this->template->content->stroke_width_array = $this->_stroke_width_array();
     // Get Countries
     $countries = array();
     foreach (ORM::factory('country')->orderby('country')->find_all() as $country) {
         // Create a list of all categories
         $this_country = $country->country;
         if (strlen($this_country) > 35) {
             $this_country = substr($this_country, 0, 35) . "...";
         }
         $countries[$country->id] = $this_country;
     }
     $this->template->content->countries = $countries;
     //GET custom forms
     $forms = array();
     foreach (ORM::factory('form')->where('form_active', 1)->find_all() as $custom_forms) {
         $forms[$custom_forms->id] = $custom_forms->form_title;
     }
     $this->template->content->forms = $forms;
     // Retrieve thumbnail photos (if edit);
     //XXX: fix _get_thumbnails
     $this->template->content->incident = $this->_get_thumbnails($id);
     // Are we creating this report from a Checkin?
     if (isset($_GET['cid']) && !empty($_GET['cid'])) {
         $checkin_id = (int) $_GET['cid'];
         $checkin = ORM::factory('checkin', $checkin_id);
         if ($checkin->loaded) {
             // Has a report already been created for this Checkin?
             if ((int) $checkin->incident_id > 0) {
                 // Redirect to report
                 url::redirect('members/reports/edit/' . $checkin->incident_id);
             }
             $incident_description = $checkin->checkin_description;
             $incident_title = text::limit_chars(strip_tags($incident_description), 100, "...", true);
             $form['incident_title'] = $incident_title;
             $form['incident_description'] = $incident_description;
             $form['incident_date'] = date('m/d/Y', strtotime($checkin->checkin_date));
             $form['incident_hour'] = date('h', strtotime($checkin->checkin_date));
             $form['incident_minute'] = date('i', strtotime($checkin->checkin_date));
             $form['incident_ampm'] = date('a', strtotime($checkin->checkin_date));
             // Does the sender of this message have a location?
             if ($checkin->location->loaded) {
                 $form['location_id'] = $checkin->location_id;
                 $form['latitude'] = $checkin->location->latitude;
                 $form['longitude'] = $checkin->location->longitude;
                 $form['location_name'] = $checkin->location->location_name;
             }
         }
     }
     // check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite $_POST fields with our own things
         $post = Validation::factory(array_merge($_POST, $_FILES));
         //	 Add some filters
         $post->pre_filter('trim', TRUE);
         // Add some rules, the input field, followed by a list of checks, carried out in order
         // $post->add_rules('locale','required','alpha_dash','length[5]');
         $post->add_rules('location_id', 'numeric');
         $post->add_rules('message_id', 'numeric');
         $post->add_rules('incident_title', 'required', 'length[3,200]');
         $post->add_rules('incident_description', 'required');
         $post->add_rules('incident_date', 'required', 'date_mmddyyyy');
         $post->add_rules('incident_hour', 'required', 'between[1,12]');
         $post->add_rules('incident_minute', 'required', 'between[0,59]');
         if ($_POST['incident_ampm'] != "am" && $_POST['incident_ampm'] != "pm") {
             $post->add_error('incident_ampm', 'values');
         }
         $post->add_rules('latitude', 'required', 'between[-90,90]');
         // Validate for maximum and minimum latitude values
         $post->add_rules('longitude', 'required', 'between[-180,180]');
         // Validate for maximum and minimum longitude values
         $post->add_rules('location_name', 'required', 'length[3,200]');
         //XXX: Hack to validate for no checkboxes checked
         if (!isset($_POST['incident_category'])) {
             $post->incident_category = "";
             $post->add_error('incident_category', 'required');
         } else {
             $post->add_rules('incident_category.*', 'required', 'numeric');
         }
         // Validate only the fields that are filled in
         if (!empty($_POST['incident_news'])) {
             foreach ($_POST['incident_news'] as $key => $url) {
                 if (!empty($url) and !(bool) filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
                     $post->add_error('incident_news', 'url');
                 }
             }
         }
         // Validate only the fields that are filled in
         if (!empty($_POST['incident_video'])) {
             foreach ($_POST['incident_video'] as $key => $url) {
                 if (!empty($url) and !(bool) filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) {
                     $post->add_error('incident_video', 'url');
                 }
             }
         }
         // Validate photo uploads
         $post->add_rules('incident_photo', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[2M]');
         // Validate Personal Information
         if (!empty($_POST['person_first'])) {
             $post->add_rules('person_first', 'length[3,100]');
         }
         if (!empty($_POST['person_last'])) {
             $post->add_rules('person_last', 'length[3,100]');
         }
         if (!empty($_POST['person_email'])) {
             $post->add_rules('person_email', 'email', 'length[3,100]');
         }
         // Validate Custom Fields
         if (isset($post->custom_field) && !$this->_validate_custom_form_fields($post->custom_field)) {
             $post->add_error('custom_field', 'values');
         }
         $post->add_rules('incident_source', 'numeric', 'length[1,1]');
         $post->add_rules('incident_information', 'numeric', 'length[1,1]');
         // Test to see if things passed the rule checks
         if ($post->validate()) {
             // STEP 1: SAVE LOCATION
             $location = new Location_Model();
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model();
             reports::save_report($post, $incident, $location->id);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE CUSTOM FORM FIELDS
             reports::save_custom_fields($post, $incident);
             // STEP 6: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // If creating a report from a checkin
             if (isset($checkin_id) and $checkin_id != "") {
                 $checkin = ORM::factory('checkin', $checkin_id);
                 if ($checkin->loaded) {
                     $checkin->incident_id = $incident->id;
                     $checkin->save();
                     // Attach all the media items in this checkin to the report
                     foreach ($checkin->media as $media) {
                         $media->incident_id = $incident->id;
                         $media->save();
                     }
                 }
             }
             // Action::report_add / report_submit_members - Added a New Report
             //++ Do we need two events for this? Or will one suffice?
             Event::run('ushahidi_action.report_add', $incident);
             Event::run('ushahidi_action.report_submit_members', $post);
             // SAVE AND CLOSE?
             if ($post->save == 1) {
                 url::redirect('members/reports/edit/' . $incident->id . '/saved');
             } else {
                 url::redirect('members/reports/');
             }
         } else {
             // repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // populate the error fields, if any
             $errors = arr::overwrite($errors, $post->errors('report'));
             $form_error = TRUE;
         }
     } else {
         if ($id) {
             // Retrieve Current Incident
             $incident = ORM::factory('incident')->where('user_id', $this->user->id)->find($id);
             if ($incident->loaded == true) {
                 // Retrieve Categories
                 $incident_category = array();
                 foreach ($incident->incident_category as $category) {
                     $incident_category[] = $category->category_id;
                 }
                 // Retrieve Media
                 $incident_news = array();
                 $incident_video = array();
                 $incident_photo = array();
                 foreach ($incident->media as $media) {
                     if ($media->media_type == 4) {
                         $incident_news[] = $media->media_link;
                     } elseif ($media->media_type == 2) {
                         $incident_video[] = $media->media_link;
                     } elseif ($media->media_type == 1) {
                         $incident_photo[] = $media->media_link;
                     }
                 }
                 // Get Geometries via SQL query as ORM can't handle Spatial Data
                 $sql = "SELECT AsText(geometry) as geometry, geometry_label, \n\t\t\t\t\t\tgeometry_comment, geometry_color, geometry_strokewidth \n\t\t\t\t\t\tFROM " . Kohana::config('database.default.table_prefix') . "geometry \n\t\t\t\t\t\tWHERE incident_id=" . $id;
                 $query = $db->query($sql);
                 foreach ($query as $item) {
                     $geometry = array("geometry" => $item->geometry, "label" => $item->geometry_label, "comment" => $item->geometry_comment, "color" => $item->geometry_color, "strokewidth" => $item->geometry_strokewidth);
                     $form['geometry'][] = json_encode($geometry);
                 }
                 // Combine Everything
                 $incident_arr = array('location_id' => $incident->location->id, 'form_id' => $incident->form_id, 'locale' => $incident->locale, 'incident_title' => $incident->incident_title, 'incident_description' => $incident->incident_description, 'incident_date' => date('m/d/Y', strtotime($incident->incident_date)), 'incident_hour' => date('h', strtotime($incident->incident_date)), 'incident_minute' => date('i', strtotime($incident->incident_date)), 'incident_ampm' => date('a', strtotime($incident->incident_date)), 'latitude' => $incident->location->latitude, 'longitude' => $incident->location->longitude, 'location_name' => $incident->location->location_name, 'country_id' => $incident->location->country_id, 'incident_category' => $incident_category, 'incident_news' => $incident_news, 'incident_video' => $incident_video, 'incident_photo' => $incident_photo, 'person_first' => $incident->incident_person->person_first, 'person_last' => $incident->incident_person->person_last, 'person_email' => $incident->incident_person->person_email, 'custom_field' => $this->_get_custom_form_fields($id, $incident->form_id, true), 'incident_source' => $incident->incident_source, 'incident_information' => $incident->incident_information, 'incident_zoom' => $incident->incident_zoom);
                 // Merge To Form Array For Display
                 $form = arr::overwrite($form, $incident_arr);
             } else {
                 // Redirect
                 url::redirect('members/reports/');
             }
         }
     }
     $this->template->content->id = $id;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     // Retrieve Custom Form Fields Structure
     $disp_custom_fields = $this->_get_custom_form_fields($id, $form['form_id'], false);
     $this->template->content->disp_custom_fields = $disp_custom_fields;
     // Retrieve Previous & Next Records
     $previous = ORM::factory('incident')->where('id < ', $id)->orderby('id', 'desc')->find();
     $previous_url = $previous->loaded ? url::base() . 'members/reports/edit/' . $previous->id : url::base() . 'members/reports/';
     $next = ORM::factory('incident')->where('id > ', $id)->orderby('id', 'desc')->find();
     $next_url = $next->loaded ? url::base() . 'members/reports/edit/' . $next->id : url::base() . 'members/reports/';
     $this->template->content->previous_url = $previous_url;
     $this->template->content->next_url = $next_url;
     // Javascript Header
     $this->template->map_enabled = TRUE;
     $this->template->colorpicker_enabled = TRUE;
     $this->template->treeview_enabled = TRUE;
     $this->template->json2_enabled = TRUE;
     $this->template->js = new View('admin/reports_edit_js');
     $this->template->js->default_map = Kohana::config('settings.default_map');
     $this->template->js->default_zoom = Kohana::config('settings.default_zoom');
     if (!$form['latitude'] || !$form['latitude']) {
         $this->template->js->latitude = Kohana::config('settings.default_lat');
         $this->template->js->longitude = Kohana::config('settings.default_lon');
     } else {
         $this->template->js->latitude = $form['latitude'];
         $this->template->js->longitude = $form['longitude'];
     }
     $this->template->js->incident_zoom = $form['incident_zoom'];
     $this->template->js->geometries = $form['geometry'];
     // Inline Javascript
     $this->template->content->date_picker_js = $this->_date_picker_js();
     $this->template->content->color_picker_js = $this->_color_picker_js();
     // Pack Javascript
     $myPacker = new javascriptpacker($this->template->js, 'Normal', false, false);
     $this->template->js = $myPacker->pack();
 }
Example #12
0
	public static function get_reports_count($category_ids, 
		$approved_text, 
		$where_text, 
		$logical_operator,
		$joins = array(),
		$custom_category_to_table_mapping = array())
	{
		$incidents_count = -1;
		
		
		//run a filter just in case someone wants to mess with this:
		$data = array(
					"was_changed_by_plugin" => false,
					"category_ids" => $category_ids, 
					"approved_text" => $approved_text, 
					"where_text" => $where_text, 
					"logical_operator" => $logical_operator,
					"incidents_count" => $incidents_count,
					"custom_category_to_table_mapping" => $custom_category_to_table_mapping
					);
		Event::run('ushahidi_filter.admin_map_get_reports_count', $data);
		//check if someone has changed this and see what we get
		//in case the filter changed the data, make sure it gets passed in
		if($data["was_changed_by_plugin"])
		{
			return $incidents_count = $data["incidents_count"];
		}
		
		//check if we're showing all categories, or if no category info was selected then return everything
		If(count($category_ids) == 0 || $category_ids[0] == '0')
		{
			// Retrieve all markers
			
			$incidents = ORM::factory('incident')
				->select('DISTINCT incident.*')
				->with('location');
				//->join('media', 'incident.id', 'media.incident_id','LEFT');
			//run code to add in extra joins
			foreach($joins as $join)
			{
				if(count($join) < 4)
				{
					$incidents = $incidents->join($join[0], $join[1], $join[2]);
				}
				else
				{
					$incidents = $incidents->join($join[0], $join[1], $join[2], $join[3]);	
				}
					
			}

			//I hate finding the count this way because it forces you to download all 
			//the incidents and not just a number, but if i use count_all() it sometimes gives 
			//erroneous numbers, but doing it this way seems to work. I imagine 
			//it has to do with the way count and distinct work together.
			$incidents_found = $incidents->where($approved_text.$where_text)->find_all();

			$incidents_count = count($incidents_found);
			
			    
			
		}
		else //we are using category IDs, double the fun
		{
			// OR up all the categories we're interested in
			$where_category = reports::or_up_categories($category_ids, $custom_category_to_table_mapping);
			
						
			//if we're using OR
			if($logical_operator == "or")
			{
				$incidents = ORM::factory('incident')
					->select('DISTINCT incident.*, COUNT(DISTINCT '.Kohana::config('database.default.table_prefix').'incident.id) as incidents_found' )
					->with('location')
					->join('incident_category', 'incident.id', 'incident_category.incident_id','LEFT')
					//->join('media', 'incident.id', 'media.incident_id','LEFT')
					->join('category', 'incident_category.category_id', 'category.id', 'LEFT')
					->join('category as parent_cat', 'category.parent_id', 'parent_cat.id', 'LEFT');
				//run code to add in extra joins
				foreach($joins as $join)
				{
					if(count($join) < 4)
					{
						$incidents = $incidents->join($join[0], $join[1], $join[2]);
					}
					else
					{
						$incidents = $incidents->join($join[0], $join[1], $join[2], $join[3]);	
					}
						
				}

				$incidents = $incidents->where($approved_text.' AND ('.$where_category. ')' . $where_text)
					->find();
				$incidents_count = $incidents->incidents_found;
			}
			else //if we're using AND
			{
			
				//based on what's in the custom cat mappings make some fancy selects
				$custom_cat_selects = reports::create_custom_category_selects($category_ids, $custom_category_to_table_mapping);
				
			
			
				// Retrieve incidents by category			
				$incidents = ORM::factory('incident')
					->select('incident.*,  category.category_color as color, category.category_title as category_title, category.id as cat_id, '.
						'parent_cat.category_title as parent_title, parent_cat.category_color as parent_color, parent_cat.id as parent_id'.
						$custom_cat_selects)
					->with('location')
					->join('incident_category', 'incident.id', 'incident_category.incident_id','LEFT')
					->join('category', 'incident_category.category_id', 'category.id')
					//->join('media', 'incident.id', 'media.incident_id','LEFT')
					->join('category as parent_cat', 'category.parent_id', 'parent_cat.id', 'LEFT');
				//run code to add in extra joins
				foreach($joins as $join)
				{
					if(count($join) < 4)
					{
						$incidents = $incidents->join($join[0], $join[1], $join[2]);
					}
					else
					{
						$incidents = $incidents->join($join[0], $join[1], $join[2], $join[3]);	
					}
						
				}

				$incidents = $incidents->where($approved_text.' AND ('.$where_category. ')' . $where_text)
					->find_all();
					
				$incidents = self::post_process_and($category_ids, $incidents);
				
				$incidents_count = count($incidents);
				
			}
			
		}//end else we are using category IDs

		
		return $incidents_count;
		
	}//end method	
Example #13
0
 /**
  * Submits a new report.
  */
 public function submit($id = FALSE, $saved = FALSE)
 {
     $db = new Database();
     // First, are we allowed to submit new reports?
     if (!Kohana::config('settings.allow_reports')) {
         url::redirect(url::site() . 'main');
     }
     $this->template->header->this_page = 'reports_submit';
     $this->template->content = new View('reports/submit');
     $this->template->header->page_title .= Kohana::lang('ui_main.reports_submit_new') . Kohana::config('settings.title_delimiter');
     //Retrieve API URL
     $this->template->api_url = Kohana::config('settings.api_url');
     // Setup and initialize form field names
     // JP: added additional form data for advanced settings
     $form = array('incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'geometry' => array(), 'location_name' => '', 'country_id' => '', 'country_name' => '', 'incident_category' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'incident_zoom' => '', 'person_first' => '', 'person_last' => '', 'person_email' => '', 'form_id' => '', 'custom_field' => array(), 'form_data' => array());
     // Copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = $saved == 'saved';
     // Initialize Default Values
     $form['incident_date'] = date("m/d/Y", time());
     $form['incident_hour'] = date('h');
     $form['incident_minute'] = date('i');
     $form['incident_ampm'] = date('a');
     $form['country_id'] = Kohana::config('settings.default_country');
     // Initialize Default Value for Hidden Field Country Name, just incase Reverse Geo coding yields no result
     $country_name = ORM::factory('country', $form['country_id']);
     $form['country_name'] = $country_name->country;
     // Initialize custom field array
     $form['form_id'] = 1;
     // JP: Removed the $form_id variable since it was being mistakenly used later as the ID of the posted form, resulting in bugs. Changed instances of $form_id to $form['form_id'] (like below) and $post['form_id'], if posted.
     $form['custom_field'] = customforms::get_custom_form_fields($id, $form['form_id'], true);
     // JP: Grab additional form information for advanced settings.
     $form['form_data'] = customforms::get_custom_form($form['form_id']);
     // GET custom forms
     $forms = array();
     foreach (customforms::get_custom_forms() as $custom_forms) {
         $forms[$custom_forms->id] = $custom_forms->form_title;
     }
     $this->template->content->forms = $forms;
     // Check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite $_POST fields with our own things
         $post = array_merge($_POST, $_FILES);
         // JP: Ensure that the advanced settings are correct.
         $form['form_data'] = customforms::get_custom_form($post['form_id']);
         // JP: Add the description_active boolean to our post data so the appropriate validation rules can be added.
         $post['description_active'] = $form['form_data']->description_active;
         // Adding event for endtime plugin to hook into
         Event::run('ushahidi_action.report_posted_frontend', $post);
         // Test to see if things passed the rule checks
         if (reports::validate($post)) {
             // STEP 1: SAVE LOCATION
             $location = new Location_Model();
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model();
             reports::save_report($post, $incident, $location->id);
             // STEP 2b: SAVE INCIDENT GEOMETRIES
             reports::save_report_geometry($post, $incident);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE CUSTOM FORM FIELDS
             reports::save_custom_fields($post, $incident);
             // STEP 6: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // Run events
             Event::run('ushahidi_action.report_submit', $post);
             Event::run('ushahidi_action.report_add', $incident);
             url::redirect('reports/thanks');
         } else {
             // Repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // Populate the error fields, if any
             $errors = arr::merge($errors, $post->errors('report'));
             // JP: Replace default Report Title and Description names with custom names in the error listing.
             if ($errors['incident_title'] and !empty($form['form_data']->report_title_name)) {
                 $errors['incident_title'] = str_replace(Kohana::lang('ui_main.reports_title'), $form['form_data']->report_title_name, $errors['incident_title']);
             }
             if ($errors['incident_description'] and !empty($form['form_data']->description_name)) {
                 $errors['incident_description'] = str_replace(Kohana::lang('ui_main.reports_description'), $form['form_data']->description_name, $errors['incident_description']);
             }
             $form_error = TRUE;
         }
     }
     // Retrieve Country Cities
     $default_country = Kohana::config('settings.default_country');
     $this->template->content->cities = $this->_get_cities($default_country);
     $this->template->content->multi_country = Kohana::config('settings.multi_country');
     $this->template->content->id = $id;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     // Populate this for backwards compat
     $this->template->content->categories = array();
     // Pass timezone
     $this->template->content->site_timezone = Kohana::config('settings.site_timezone');
     // Pass the submit report message
     $this->template->content->site_submit_report_message = Kohana::config('settings.site_submit_report_message');
     // Retrieve Custom Form Fields Structure
     $this->template->content->custom_forms = new View('reports/submit_custom_forms');
     // JP: This needs to be passed $form['form_id'] rather than $form_id so that we use the correct custom fields.
     $disp_custom_fields = customforms::get_custom_form_fields($id, $form['form_id'], FALSE);
     $this->template->content->disp_custom_fields = $disp_custom_fields;
     $this->template->content->stroke_width_array = $this->_stroke_width_array();
     $this->template->content->custom_forms->disp_custom_fields = $disp_custom_fields;
     $this->template->content->custom_forms->form = $form;
     // Javascript Header
     $this->themes->map_enabled = TRUE;
     $this->themes->treeview_enabled = TRUE;
     $this->themes->colorpicker_enabled = TRUE;
     $this->themes->js = new View('reports/submit_edit_js');
     $this->themes->js->edit_mode = FALSE;
     $this->themes->js->incident_zoom = FALSE;
     $this->themes->js->default_map = Kohana::config('settings.default_map');
     $this->themes->js->default_zoom = Kohana::config('settings.default_zoom');
     if (!$form['latitude'] or !$form['latitude']) {
         $this->themes->js->latitude = Kohana::config('settings.default_lat');
         $this->themes->js->longitude = Kohana::config('settings.default_lon');
     } else {
         $this->themes->js->latitude = $form['latitude'];
         $this->themes->js->longitude = $form['longitude'];
     }
     $this->themes->js->geometries = $form['geometry'];
 }
Example #14
0
    /**
    * Lists the reports.
    * @param int $page
    */
    function index($page = 1)
    {

		// Cacheable Controller
		$this->is_cachable = TRUE;
		
		$this->template->header->this_page = 'reports';
		$this->template->content = new View('reports');
		$this->themes->js = new View('reports_js');

		// Get locale
		$l = Kohana::config('locale.language.0');

		$db = new Database;


        if (!empty($_GET['status']))
        {
            $status = $_GET['status'];

            if (strtolower($status) == 'a')
            {
                $filter = 'incident.incident_active = 0';
            }
            elseif (strtolower($status) == 'v')
            {
                $filter = 'incident.incident_verified = 0';
            }
            else
            {
                $status = "0";
                $filter = '1=1';
            }
        }
        else
        {
            $status = "0";
            $filter = "1=1";
        }

       
        // check, has the form been submitted?
        $form_error = FALSE;
        $form_saved = FALSE;
        $form_action = "";
        
        $db = new Database;


	// Category ID
	$category_ids=array();
        if( isset($_GET['c']) AND ! empty($_GET['c']) )
	{
		$category_ids = explode(",", $_GET['c']); //get rid of that trailing ","
	}
	else
	{
		$category_ids = array("0");
	}
	
	// logical operator
	$logical_operator = "or";
        if( isset($_GET['lo']) AND ! empty($_GET['lo']) )
	{
		$logical_operator = $_GET['lo'];
	}

	$approved_text = " incident.incident_active = 1 ";
	
	
	
	$location_where = "";
	// Break apart location variables, if necessary
	$southwest = array();
	if (isset($_GET['sw']))
	{
		$southwest = explode(",",$_GET['sw']);
	}

	$northeast = array();
	if (isset($_GET['ne']))
	{
		$northeast = explode(",",$_GET['ne']);
	}

	if ( count($southwest) == 2 AND count($northeast) == 2 )
	{
		$lon_min = (float) $southwest[0];
		$lon_max = (float) $northeast[0];
		$lat_min = (float) $southwest[1];
		$lat_max = (float) $northeast[1];

		$location_where = ' AND (location.latitude >='.$lat_min.' AND location.latitude <='.$lat_max.' AND location.longitude >='.$lon_min.' AND location.longitude <='.$lon_max.') ';

	}
	
	
	$reports_count = reports::get_reports_count($category_ids, $approved_text, $location_where. " AND ". $filter, $logical_operator);

	
	// Pagination
	$pagination = new Pagination(array(
			'query_string' => 'page',
			'items_per_page' => (int) Kohana::config('settings.items_per_page'),
			'total_items' => $reports_count
			));

	$incidents = reports::get_reports($category_ids,  $approved_text, $location_where. " AND ". $filter, $logical_operator, 
		"incident.incident_date", "asc",
		(int) Kohana::config('settings.items_per_page'), $pagination->sql_offset );
		
		
	
		//Set default as not showing pagination. Will change below if necessary.
		$this->template->content->pagination = "";

		// Pagination and Total Num of Report Stats
		if ($pagination->total_items == 1)
		{
			$plural = "";
		}
		else
		{
			$plural = "s";
		}

		if ($pagination->total_items > 0)
		{
			$current_page = ($pagination->sql_offset/ (int) Kohana::config('settings.items_per_page')) + 1;
			$total_pages = ceil($pagination->total_items/ (int) Kohana::config('settings.items_per_page'));

			if ($total_pages > 1)
			{ // If we want to show pagination
				$this->template->content->pagination_stats = Kohana::lang('ui_admin.showing_page').' '.$current_page.' '.Kohana::lang('ui_admin.of').' '.$total_pages.' '.Kohana::lang('ui_admin.pages');

				$this->template->content->pagination = $pagination;
			}
			else
			{ // If we don't want to show pagination
				$this->template->content->pagination_stats = $pagination->total_items.' '.Kohana::lang('ui_admin.reports');
			}
		}
		else
		{
			$this->template->content->pagination_stats = '('.$pagination->total_items.' report'.$plural.')';
		}


		//locations
			$location_in = array();
		foreach ($incidents as $incident)
		{
			$location_in[] = $incident->location_id;
		}

		//check if location_in is not empty
		if( count($location_in ) > 0 )
		{
			    // Get location names
			    $query = 'SELECT id, location_name FROM '.$this->table_prefix.'location WHERE id IN ('.implode(',',$location_in).')';
			    $locations_query = $db->query($query);

			    $locations = array();
			    foreach ($locations_query as $loc)
			    {
				    $locations[$loc->id] = $loc->location_name;
			    }
		}
		else
		{
		    $locations = array();
		}
		
		$this->template->content->locations = $locations;

		
		//categories
		$localized_categories = array();
		foreach ($incidents as $incident)
		{
			foreach ($incident->category AS $category)
			{
				$ct = (string)$category->category_title;
				if( ! isset($localized_categories[$ct]))
				{
					$translated_title = Category_Lang_Model::category_title($category->id,$l);
					$localized_categories[$ct] = $category->category_title;
					if($translated_title)
					{
						$localized_categories[$ct] = $translated_title;
					}
				}
			}
		}

		$this->template->content->localized_categories = $localized_categories;



	// Category Title, if Category ID available
	$category_title = "All Categories";
	$count = 0;
	foreach($category_ids as $cat_id)
	{
		$category = ORM::factory('category')
			->find($cat_id);
		if($category->loaded)
		{
			$count++;
			if($count > 1)
			{
				$category_title = $category_title . " ". strtoupper($logical_operator). " ";
			}
			$category_title = $category_title . $category->category_title;
		}
	}
	$this->template->content->category_title = $category_title . ": ";



        //GET countries
        $countries = array();
        foreach (ORM::factory('country')->orderby('country')->find_all() as $country)
        {
            // Create a list of all categories
            $this_country = $country->country;
            if (strlen($this_country) > 35)
            {
                $this_country = substr($this_country, 0, 35) . "...";
            }
            $countries[$country->id] = $this_country;
        }

        $this->template->content->countries = $countries;
        $this->template->content->incidents = $incidents;
        $this->template->content->pagination = $pagination;
        $this->template->content->form_error = $form_error;
        $this->template->content->form_saved = $form_saved;
        $this->template->content->form_action = $form_action;

        // Total Reports
        $this->template->content->total_items = $pagination->total_items;

        // Status Tab
        $this->template->content->status = $status;

	$this->template->header->header_block = $this->themes->header_block();
    }//end of index()
 /**
  * The actual reporting -
  *
  * @return int
  */
 private function _submit()
 {
     // Setup and initialize form field names
     $form = array('incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'location_name' => '', 'country_id' => '', 'incident_category' => '', 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '');
     $this->messages = $form;
     // Check for HTTP POST, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite
         // $_POST fields with our own things
         $post = array_merge($_POST, $_FILES);
         $post['incident_category'] = explode(',', $post['incident_category']);
         //
         // EK <*****@*****.**> - 17/05/2012
         // Commenting out this event ('ushahidi_action.report_submit_api') because
         // of the following:
         // The 'ushahidi_action.report_submit' and 'ushahidi_action.report_add'
         // events should suffice for all plugins that wish to run extra
         // operations once a report has been submitted and saved - avoid
         // superfluous events
         //
         // In case there's a plugin that would like to know about
         // this new incident, I mean report
         // Event::run('ushahidi_action.report_submit_api', $post);
         if (reports::validate($post)) {
             // STEP 1: SAVE LOCATION
             $location = new Location_Model();
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model();
             reports::save_report($post, $incident, $location->id);
             // STEP 2b: SAVE INCIDENT GEOMETRIES
             reports::save_report_geometry($post, $incident);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE CUSTOM FORM FIELDS
             reports::save_custom_fields($post, $incident);
             // STEP 6: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // Run events
             Event::run('ushahidi_action.report_submit', $post);
             Event::run('ushahidi_action.report_add', $incident);
             // Action::report_edit_api - Edited a Report
             Event::run('ushahidi_action.report_edit_api', $incident);
             // Success
             return 0;
         } else {
             // Populate the error fields, if any
             $this->messages = arr::overwrite($this->messages, $post->errors('report'));
             foreach ($this->messages as $error_item => $error_description) {
                 if (!is_array($error_description)) {
                     $this->error_string .= $error_description;
                     if ($error_description != end($this->messages)) {
                         $this->error_string .= " - ";
                     }
                 }
             }
             //FAILED!!!
             return 1;
             //validation error
         }
     } else {
         return 3;
         // Not sent by post method.
     }
 }
Example #16
0
<!--
Developer : chintan khatri
Date : 01-10-2016
-->
<!DOCTYPE html>
<?php 
include_once './class.php';
$db = new reports();
?>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
        <title>Alpha</title>

        <!-- CSS  -->
        <?php 
include_once './theme-part/top_head.php';
?>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <style type="text/css">
            html, body {
                height:100%;
            }
            #box {
                height:80%;
                background:#331266;
            }
            #container {
                position:relative;
                height:100%;
<?php

include_once './class.php';
$db = new reports();
?>
<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>aLpha</title>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <style type="text/css">
            html, body {
                height:100%;
            }
            #box {
                height:80%;
                background:#331266;
            }
            #container {
                position:relative;
                height:100%;
            }
            tspan{
                font-size: 100% !important;
            }
        </style>
        <script type="text/javascript">
            var chart1;
            $(function () {
    /**
    * Lists the reports.
    * @param int $page
    */
    function index($page = 1)
    {
        // If user doesn't have access, redirect to dashboard
        if ( ! admin::permissions($this->user, "reports_view"))
        {
            url::redirect(url::site().'admin/dashboard');
        }

        $this->template->content = new View('adminmap/adminmap_reports');
        $this->template->content->title = Kohana::lang('ui_admin.reports');


        if (!empty($_GET['status']))
        {
            $status = $_GET['status'];

            if (strtolower($status) == 'a')
            {
                $filter = 'incident.incident_active = 0';
            }
            elseif (strtolower($status) == 'v')
            {
                $filter = 'incident.incident_verified = 0';
            }
            else
            {
                $status = "0";
                $filter = '1=1';
            }
        }
        else
        {
            $status = "0";
            $filter = "1=1";
        }

       
        // check, has the form been submitted?
        $form_error = FALSE;
        $form_saved = FALSE;
        $form_action = "";
        
        if ($_POST)
        {
            $post = Validation::factory($_POST);

             //  Add some filters
            $post->pre_filter('trim', TRUE);

            // Add some rules, the input field, followed by a list of checks, carried out in order
            $post->add_rules('action','required', 'alpha', 'length[1,1]');
            $post->add_rules('incident_id.*','required','numeric');

            if ($post->validate())
            {
                if ($post->action == 'a')       // Approve Action
                {
                    foreach($post->incident_id as $item)
                    {
                        $update = new Incident_Model($item);
                        if ($update->loaded == true) 
                        {
                            if( $update->incident_active == 0 ) 
                            {
                                $update->incident_active = '1';
                            } 
                            else {
                                $update->incident_active = '0';
                            }

                            // Tag this as a report that needs to be sent out as an alert
                            if ($update->incident_alert_status != '2')
                            { // 2 = report that has had an alert sent
                                $update->incident_alert_status = '1';
                            }

                            $update->save();

                            $verify = new Verify_Model();
                            $verify->incident_id = $item;
                            $verify->verified_status = '1';
                            $verify->user_id = $_SESSION['auth_user']->id;          // Record 'Verified By' Action
                            $verify->verified_date = date("Y-m-d H:i:s",time());
                            $verify->save();

                            // Action::report_approve - Approve a Report
                            Event::run('ushahidi_action.report_approve', $update);
                        }
                    }
                    $form_action = strtoupper(Kohana::lang('ui_admin.approved'));
                }
                elseif ($post->action == 'u')   // Unapprove Action
                {
                    foreach($post->incident_id as $item)
                    {
                        $update = new Incident_Model($item);
                        if ($update->loaded == true) {
                            $update->incident_active = '0';

                            // If Alert hasn't been sent yet, disable it
                            if ($update->incident_alert_status == '1')
                            {
                                $update->incident_alert_status = '0';
                            }

                            $update->save();

                            $verify = new Verify_Model();
                            $verify->incident_id = $item;
                            $verify->verified_status = '0';
                            $verify->user_id = $_SESSION['auth_user']->id;          // Record 'Verified By' Action
                            $verify->verified_date = date("Y-m-d H:i:s",time());
                            $verify->save();

                            // Action::report_unapprove - Unapprove a Report
                            Event::run('ushahidi_action.report_unapprove', $update);
                        }
                    }
                    $form_action = strtoupper(Kohana::lang('ui_admin.unapproved'));
                }
                elseif ($post->action == 'v')   // Verify Action
                {
                    foreach($post->incident_id as $item)
                    {
                        $update = new Incident_Model($item);
                        $verify = new Verify_Model();
                        if ($update->loaded == true) {
                            if ($update->incident_verified == '1')
                            {
                                $update->incident_verified = '0';
                                $verify->verified_status = '0';
                            }
                            else {
                                $update->incident_verified = '1';
                                $verify->verified_status = '2';
                            }
                            $update->save();

                            $verify->incident_id = $item;
                            $verify->user_id = $_SESSION['auth_user']->id;          // Record 'Verified By' Action
                            $verify->verified_date = date("Y-m-d H:i:s",time());
                            $verify->save();
                        }
                    }
                    $form_action = "VERIFIED";
                }
                elseif ($post->action == 'd')   //Delete Action
                {
                    foreach($post->incident_id as $item)
                    {
                        $update = new Incident_Model($item);
                        if ($update->loaded == true)
                        {
                            $incident_id = $update->id;
                            $location_id = $update->location_id;
                            $update->delete();

                            // Delete Location
                            ORM::factory('location')->where('id',$location_id)->delete_all();

                            // Delete Categories
                            ORM::factory('incident_category')->where('incident_id',$incident_id)->delete_all();

                            // Delete Translations
                            ORM::factory('incident_lang')->where('incident_id',$incident_id)->delete_all();

                            // Delete Photos From Directory
                            foreach (ORM::factory('media')->where('incident_id',$incident_id)->where('media_type', 1) as $photo) {
                                deletePhoto($photo->id);
                            }

                            // Delete Media
                            ORM::factory('media')->where('incident_id',$incident_id)->delete_all();

                            // Delete Sender
                            ORM::factory('incident_person')->where('incident_id',$incident_id)->delete_all();

                            // Delete relationship to SMS message
                            $updatemessage = ORM::factory('message')->where('incident_id',$incident_id)->find();
                            if ($updatemessage->loaded == true) {
                                $updatemessage->incident_id = 0;
                                $updatemessage->save();
                            }

                            // Delete Comments
                            ORM::factory('comment')->where('incident_id',$incident_id)->delete_all();

                            // Action::report_delete - Deleted a Report
                            Event::run('ushahidi_action.report_delete', $update);
                        }
                    }
                    $form_action = strtoupper(Kohana::lang('ui_admin.deleted'));
                }
                $form_saved = TRUE;
            }
            else
            {
                $form_error = TRUE;
            }

        }

        
	$db = new Database;


	// Category ID
	$category_ids=array();
        if( isset($_GET['c']) AND ! empty($_GET['c']) )
	{
		$category_ids = explode(",", $_GET['c']); //get rid of that trailing ","
	}
	else
	{
		$category_ids = array("0");
	}
	
	// logical operator
	$logical_operator = "or";
        if( isset($_GET['lo']) AND ! empty($_GET['lo']) )
	{
		$logical_operator = $_GET['lo'];
	}

	$show_unapproved="3"; //1 show only approved, 2 show only unapproved, 3 show all
	//figure out if we're showing unapproved stuff or what.
        if (isset($_GET['u']) AND !empty($_GET['u']))
        {
            $show_unapproved = (int) $_GET['u'];
        }
	$approved_text = "";
	if($show_unapproved == 1)
	{
		$approved_text = "incident.incident_active = 1 ";
	}
	else if ($show_unapproved == 2)
	{
		$approved_text = "incident.incident_active = 0 ";
	}
	else if ($show_unapproved == 3)
	{
		$approved_text = " (incident.incident_active = 0 OR incident.incident_active = 1) ";
	}
	
	
	
	$location_where = "";
	// Break apart location variables, if necessary
	$southwest = array();
	if (isset($_GET['sw']))
	{
		$southwest = explode(",",$_GET['sw']);
	}

	$northeast = array();
	if (isset($_GET['ne']))
	{
		$northeast = explode(",",$_GET['ne']);
	}

	if ( count($southwest) == 2 AND count($northeast) == 2 )
	{
		$lon_min = (float) $southwest[0];
		$lon_max = (float) $northeast[0];
		$lat_min = (float) $southwest[1];
		$lat_max = (float) $northeast[1];

		$location_where = ' AND (location.latitude >='.$lat_min.' AND location.latitude <='.$lat_max.' AND location.longitude >='.$lon_min.' AND location.longitude <='.$lon_max.') ';

	}
	
	
	$reports_count = reports::get_reports_count($category_ids, $approved_text, $location_where. " AND ". $filter, $logical_operator);

	
	// Pagination
	$pagination = new Pagination(array(
			'query_string' => 'page',
			'items_per_page' => (int) Kohana::config('settings.items_per_page'),
			'total_items' => $reports_count
			));

	$incidents = reports::get_reports($category_ids,  $approved_text, $location_where. " AND ". $filter, $logical_operator, 
		"incident.incident_date", "asc",
		(int) Kohana::config('settings.items_per_page_admin'), $pagination->sql_offset );



        //GET countries
        $countries = array();
        foreach (ORM::factory('country')->orderby('country')->find_all() as $country)
        {
            // Create a list of all categories
            $this_country = $country->country;
            if (strlen($this_country) > 35)
            {
                $this_country = substr($this_country, 0, 35) . "...";
            }
            $countries[$country->id] = $this_country;
        }

        $this->template->content->countries = $countries;
        $this->template->content->incidents = $incidents;
        $this->template->content->pagination = $pagination;
        $this->template->content->form_error = $form_error;
        $this->template->content->form_saved = $form_saved;
        $this->template->content->form_action = $form_action;

        // Total Reports
        $this->template->content->total_items = $pagination->total_items;

        // Status Tab
        $this->template->content->status = $status;

        // Javascript Header
        $this->template->js = new View('admin/reports_js');
    }//end of index()
Example #19
0
 private function get_counts()
 {
     //loop through each of the geometries and see how many reports fall under both the geometry category and
     //the dependent
     $geometries = ORM::factory("densitymap_geometry")->find_all();
     $geometries_and_counts = array();
     foreach ($geometries as $geometry) {
         $_GET['dm'] = $geometry->category_id;
         $reports = reports::fetch_incidents();
         $geometries_and_counts[$geometry->id] = count($reports);
     }
     //end foreach loop over all the geometries
     return $geometries_and_counts;
 }
Example #20
0
<?php

$this->a('reports.php');
$back_names[] = "cl_call";
$back_names[] = "cl_call2";
$back_names[] = "cl_call3";
$back_names[] = "cl_call4";
$back_names[] = "cl_call5";
$back_names[] = "cl_call6";
$reports = new reports();
$reports->mysqli = $this->mysqli;
$reports->user = $this->user;
$reports->request = $this->request;
$js_functions[] = $reports->show_js();
$string_out .= $reports->div_selectors();
// detect calling
if ($this->request['type'] == 2) {
    $string_out .= "<div id='post_form' class='post_form'></div>\n<div class='bigblock' id='bigblock'>\n<div id='main_div' class='content'>\n" . $reports->seller_report($this->user['id'], null, null) . "\n<div id ='report_data'></div>\n</div>\n</div>";
} elseif ($this->request['type'] == 3) {
    $string_out .= "<div id='post_form' class='post_form'></div>\n<div class='bigblock' id='bigblock'>\n<div id='main_div' class='content'>\n" . $reports->supplier_report($this->request['supplier'], null, null) . "\n<div id ='report_data'></div>\n</div>\n</div>";
} elseif ($this->request['type'] == 4) {
    $string_out .= "<div id='post_form' class='post_form'></div>\n<div class='bigblock' id='bigblock'>\n<div id='main_div' class='content'>\n" . $reports->brands_report($this->request['supplier'], null, null) . "\n<div id ='report_data'></div>\n</div>\n</div>";
} else {
    if (isset($this->request['product']) and $this->request['product'] != '') {
        $string_out .= "<div id='post_form' class='post_form'></div>\n<div class='bigblock' id='bigblock'>\n<div id='main_div' class='content'>\n" . $reports->prod_report($this->request['product']) . "\n<div id ='report_data'></div>\n</div>\n</div>";
    } else {
        $string_out .= "<div id='post_form' class='post_form'></div>\n<div class='bigblock' id='bigblock'>\n<div id='main_div' class='content'>\n" . $reports->sellings() . "\n<div id ='report_data'></div>\n</div>\n</div>";
    }
}
$string_out .= "<div id='action_buttons' class='divactionbuttons'>" . $reports->reports_buttons() . "</div>";
?>
Example #21
0
 /**
  * Generate JSON in CLUSTER mode
  */
 public function cluster()
 {
     // Database
     $db = new Database();
     $json = "";
     $json_item = "";
     $json_array = array();
     $geometry_array = array();
     $color = Kohana::config('settings.default_map_all');
     $icon = "";
     // Get Zoom Level
     $zoomLevel = (isset($_GET['z']) and !empty($_GET['z'])) ? (int) $_GET['z'] : 8;
     //$distance = 60;
     $distance = (10000000 >> $zoomLevel) / 100000;
     // Fetch the incidents using the specified parameters
     $incidents = reports::fetch_incidents();
     // Category ID
     $category_id = (isset($_GET['c']) and intval($_GET['c']) > 0) ? intval($_GET['c']) : 0;
     // Start date
     $start_date = (isset($_GET['s']) and intval($_GET['s']) > 0) ? intval($_GET['s']) : NULL;
     // End date
     $end_date = (isset($_GET['e']) and intval($_GET['e']) > 0) ? intval($_GET['e']) : NULL;
     if (Category_Model::is_valid_category($category_id)) {
         // Get the color
         $color = ORM::factory('category', $category_id)->category_color;
     }
     // Create markers by marrying the locations and incidents
     $markers = array();
     foreach ($incidents as $incident) {
         $markers[] = array('id' => $incident->incident_id, 'incident_title' => $incident->incident_title, 'latitude' => $incident->latitude, 'longitude' => $incident->longitude, 'thumb' => '');
     }
     $clusters = array();
     // Clustered
     $singles = array();
     // Non Clustered
     // Loop until all markers have been compared
     while (count($markers)) {
         $marker = array_pop($markers);
         $cluster = array();
         // Compare marker against all remaining markers.
         foreach ($markers as $key => $target) {
             // This function returns the distance between two markers, at a defined zoom level.
             // $pixels = $this->_pixelDistance($marker['latitude'], $marker['longitude'],
             // $target['latitude'], $target['longitude'], $zoomLevel);
             $pixels = abs($marker['longitude'] - $target['longitude']) + abs($marker['latitude'] - $target['latitude']);
             // If two markers are closer than defined distance, remove compareMarker from array and add to cluster.
             if ($pixels < $distance) {
                 unset($markers[$key]);
                 $target['distance'] = $pixels;
                 $cluster[] = $target;
             }
         }
         // If a marker was added to cluster, also add the marker we were comparing to.
         if (count($cluster) > 0) {
             $cluster[] = $marker;
             $clusters[] = $cluster;
         } else {
             $singles[] = $marker;
         }
     }
     // Create Json
     foreach ($clusters as $cluster) {
         // Calculate cluster center
         $bounds = $this->_calculateCenter($cluster);
         $cluster_center = $bounds['center'];
         $southwest = $bounds['sw'];
         $northeast = $bounds['ne'];
         // Number of Items in Cluster
         $cluster_count = count($cluster);
         // Get the time filter
         $time_filter = (!empty($start_date) and !empty($end_date)) ? "&s=" . $start_date . "&e=" . $end_date : "";
         // Build out the JSON string
         $json_item = "{";
         $json_item .= "\"type\":\"Feature\",";
         $json_item .= "\"properties\": {";
         $json_item .= "\"name\":\"" . str_replace(chr(10), ' ', str_replace(chr(13), ' ', "<a href=" . url::base() . "reports/index/?c=" . $category_id . "&sw=" . $southwest . "&ne=" . $northeast . $time_filter . ">" . $cluster_count . " Reports</a>")) . "\",";
         $json_item .= "\"link\": \"" . url::base() . "reports/index/?c=" . $category_id . "&sw=" . $southwest . "&ne=" . $northeast . $time_filter . "\", ";
         $json_item .= "\"category\":[0], ";
         $json_item .= "\"color\": \"" . $color . "\", ";
         $json_item .= "\"icon\": \"" . $icon . "\", ";
         $json_item .= "\"thumb\": \"\", ";
         $json_item .= "\"timestamp\": \"0\", ";
         $json_item .= "\"count\": \"" . $cluster_count . "\"";
         $json_item .= "},";
         $json_item .= "\"geometry\": {";
         $json_item .= "\"type\":\"Point\", ";
         $json_item .= "\"coordinates\":[" . $cluster_center . "]";
         $json_item .= "}";
         $json_item .= "}";
         array_push($json_array, $json_item);
     }
     foreach ($singles as $single) {
         $json_item = "{";
         $json_item .= "\"type\":\"Feature\",";
         $json_item .= "\"properties\": {";
         $json_item .= "\"name\":\"" . str_replace(chr(10), ' ', str_replace(chr(13), ' ', "<a href=" . url::base() . "reports/view/" . $single['id'] . "/>" . str_replace('"', '\\"', $single['incident_title']) . "</a>")) . "\",";
         $json_item .= "\"link\": \"" . url::base() . "reports/view/" . $single['id'] . "\", ";
         $json_item .= "\"category\":[0], ";
         $json_item .= "\"color\": \"" . $color . "\", ";
         $json_item .= "\"icon\": \"" . $icon . "\", ";
         // $json_item .= "\"thumb\": \"".$single['thumb']."\", ";
         $json_item .= "\"timestamp\": \"0\", ";
         $json_item .= "\"count\": \"" . 1 . "\"";
         $json_item .= "},";
         $json_item .= "\"geometry\": {";
         $json_item .= "\"type\":\"Point\", ";
         $json_item .= "\"coordinates\":[" . $single['longitude'] . ", " . $single['latitude'] . "]";
         $json_item .= "}";
         $json_item .= "}";
         array_push($json_array, $json_item);
     }
     $json = implode(",", $json_array);
     //
     // E.Kala July 27, 2011
     // @todo Parking this geometry business for review
     //
     // if (count($geometry_array))
     // {
     // 	$json = implode(",", $geometry_array).",".$json;
     // }
     header('Content-type: application/json; charset=utf-8');
     $this->template->json = $json;
 }
Example #22
0
 function __construct()
 {
     $this->tr = new trace('html');
     /*
      * check for show stoppers:
      * 1) presence of settings file
      * 2) correct authentication
      * 3) mandatory configuration constants
      */
     if (!defined("PATH_TO_SETTINGS")) {
         die("<p>Constant PATH_TO_SETTINGS is undefined.");
     }
     $close_gate = '';
     if (file_exists(PATH_TO_SETTINGS)) {
         require_once PATH_TO_SETTINGS;
         //TODO: TRACE_LEVEL and EXTJS_UI_ENABLED are available after call of proofreadOptionalSettings
         //move proofreadOptionalSettings up here
         $this->debug = defined('TRACE_LEVEL') && constant('TRACE_LEVEL') < 4 ? false : true;
         $this->use_extjs = defined('EXTJS_UI_ENABLED') ? constant('EXTJS_UI_ENABLED') : false;
         $this->authentication_enabled = defined('YAPHOBIA_WEB_INTERFACE_PASSWORD') && constant('YAPHOBIA_WEB_INTERFACE_PASSWORD') != "";
         if ($this->authentication_enabled) {
             $close_gate = $this->authenticate();
         }
         $sv = new settingsValidator();
         $sermon = $sv->proofreadMandatorySettings();
         if ($sermon != "") {
             $close_gate = '<div class="welcome" style="text-align: left;">' . $sermon . '</div>';
         }
     } else {
         $close_gate = '<div class="welcome"><p>ERROR: There is no configuration file <b>settings.php</b>!<br/>Please copy <b>settings.defaults.php</b> to <b>settings.php</b> and change the options within the file according to your needs.</p></div>';
         $this->authentication_enabled = true;
         //this should prevent category menu from being displayed
     }
     $this->importRequestVars();
     // needed for correct rendering of categorie_menu
     if ($this->xmldata == 0) {
         $this->htmlHeader();
         //render yaphobia header if not in printview
         if ($this->printview === false) {
             print '<div class="yaph_header"><h1>Yaphobia</h1>';
             if ($close_gate == '' && $this->cat != self::CATEGORY_LOGOUT || !$this->authentication_enabled) {
                 $this->render_categorie_menu();
             }
             print "</div><br/>";
         }
         //stop here if a showstopper has occured above
         if ($close_gate != '') {
             print $close_gate . "<br/>";
         } else {
             parent::__construct();
             //connect to database
             $this->installHelperChecks();
             $this->actions();
         }
         $this->htmlFooter();
     } else {
         header("Content-type: text/xml");
         if ($close_gate != '') {
             print $close_gate . "<br/>";
         } else {
             parent::__construct();
             //connect to database
             //$this->installHelperChecks();
             $this->xmlActions();
         }
     }
 }
 public static function json_timeline($controller, $category_ids, $on_the_back_end = true, $extra_where_text = "", $joins = array(), $custom_category_to_table_mapping = array())
 {
     $category_ids = explode(",", $category_ids, -1);
     //get rid of that trailing ","
     //a little flag to alert us to the presence of the "ALL CATEGORIES" category
     $is_all_categories = false;
     if (count($category_ids) == 0 || $category_ids[0] == '0') {
         $is_all_categories = true;
     }
     $controller->auto_render = FALSE;
     $db = new Database();
     $show_unapproved = "3";
     //1 show only approved, 2 show only unapproved, 3 show all
     $approved_text = " (1=1) ";
     if ($on_the_back_end) {
         //figure out if we're showing unapproved stuff or what.
         if (isset($_GET['u']) and !empty($_GET['u'])) {
             $show_unapproved = (int) $_GET['u'];
         }
         $approved_text = "";
         if ($show_unapproved == 1) {
             $approved_text = "incident.incident_active = 1 ";
         } else {
             if ($show_unapproved == 2) {
                 $approved_text = "incident.incident_active = 0 ";
             } else {
                 if ($show_unapproved == 3) {
                     $approved_text = " (incident.incident_active = 0 OR incident.incident_active = 1) ";
                 }
             }
         }
     } else {
         $approved_text = "incident.incident_active = 1 ";
     }
     $logical_operator = "or";
     if (isset($_GET['lo']) and !empty($_GET['lo'])) {
         $logical_operator = $_GET['lo'];
     }
     $interval = (isset($_GET["i"]) and !empty($_GET["i"])) ? $_GET["i"] : "month";
     // Get the Counts
     $select_date_text = "DATE_FORMAT(incident_date, '%Y-%m-01')";
     $groupby_date_text = "DATE_FORMAT(incident_date, '%Y%m')";
     if ($interval == 'day') {
         $select_date_text = "DATE_FORMAT(incident_date, '%Y-%m-%d')";
         $groupby_date_text = "DATE_FORMAT(incident_date, '%Y%m%d')";
     } elseif ($interval == 'hour') {
         $select_date_text = "DATE_FORMAT(incident_date, '%Y-%m-%d %H:%M')";
         $groupby_date_text = "DATE_FORMAT(incident_date, '%Y%m%d%H')";
     } elseif ($interval == 'week') {
         $select_date_text = "STR_TO_DATE(CONCAT(CAST(YEARWEEK(incident_date) AS CHAR), ' Sunday'), '%X%V %W')";
         $groupby_date_text = "YEARWEEK(incident_date)";
     }
     $graph_data = array();
     $graph_data[0] = array();
     $graph_data[0]['label'] = "Category Title";
     //is this used for anything?
     $graph_data[0]['color'] = '#' . self::merge_colors($category_ids, $custom_category_to_table_mapping);
     $graph_data[0]['data'] = array();
     $incidents = reports::get_reports($category_ids, $approved_text, " " . $extra_where_text, $logical_operator, "incident.incident_date", "asc", -1, -1, $joins, $custom_category_to_table_mapping);
     $approved_IDs_str = "('-1')";
     if (count($incidents) > 0) {
         $i = 0;
         $approved_IDs_str = "(";
         foreach ($incidents as $incident) {
             $i++;
             $approved_IDs_str = $i > 1 ? $approved_IDs_str . ', ' : $approved_IDs_str;
             $approved_IDs_str = $approved_IDs_str . "'" . $incident->id . "'";
         }
         $approved_IDs_str = $approved_IDs_str . ") ";
     }
     $query = 'SELECT UNIX_TIMESTAMP(' . $select_date_text . ') AS time, COUNT(id) AS number FROM ' . adminmap_helper::$table_prefix . 'incident WHERE incident.id in' . $approved_IDs_str . ' GROUP BY ' . $groupby_date_text;
     $query = $db->query($query);
     foreach ($query as $items) {
         array_push($graph_data[0]['data'], array($items->time * 1000, $items->number));
     }
     echo json_encode($graph_data);
 }
Example #24
0
 /**
  * Generate JSON in CLUSTER mode
  */
 public function cluster()
 {
     // Database
     $db = new Database();
     $json = '';
     $json_item = array();
     $json_features = array();
     $geometry_array = array();
     $color = Kohana::config('settings.default_map_all');
     $icon = "";
     if (Kohana::config('settings.default_map_all_icon_id')) {
         $icon_object = ORM::factory('media')->find(Kohana::config('settings.default_map_all_icon_id'));
         $icon = url::convert_uploaded_to_abs($icon_object->media_medium);
     }
     // Get Zoom Level
     $zoomLevel = (isset($_GET['z']) and !empty($_GET['z'])) ? (int) $_GET['z'] : 8;
     //$distance = 60;
     $distance = (10000000 >> $zoomLevel) / 100000;
     // Fetch the incidents using the specified parameters
     $incidents = reports::fetch_incidents();
     // Category ID
     $category_id = (isset($_GET['c']) and intval($_GET['c']) > 0) ? intval($_GET['c']) : 0;
     // Start date
     $start_date = (isset($_GET['s']) and intval($_GET['s']) > 0) ? intval($_GET['s']) : NULL;
     // End date
     $end_date = (isset($_GET['e']) and intval($_GET['e']) > 0) ? intval($_GET['e']) : NULL;
     if (Category_Model::is_valid_category($category_id)) {
         // Get the color & icon
         $cat = ORM::factory('category', $category_id);
         $color = $cat->category_color;
         if ($cat->category_image) {
             $icon = url::convert_uploaded_to_abs($cat->category_image);
         }
     }
     // Create markers by marrying the locations and incidents
     $markers = array();
     foreach ($incidents as $incident) {
         $markers[] = array('id' => $incident->incident_id, 'incident_title' => $incident->incident_title, 'latitude' => $incident->latitude, 'longitude' => $incident->longitude, 'thumb' => '');
     }
     $clusters = array();
     // Clustered
     $singles = array();
     // Non Clustered
     // Loop until all markers have been compared
     while (count($markers)) {
         $marker = array_pop($markers);
         $cluster = array();
         // Compare marker against all remaining markers.
         foreach ($markers as $key => $target) {
             // This function returns the distance between two markers, at a defined zoom level.
             // $pixels = $this->_pixelDistance($marker['latitude'], $marker['longitude'],
             // $target['latitude'], $target['longitude'], $zoomLevel);
             $pixels = abs($marker['longitude'] - $target['longitude']) + abs($marker['latitude'] - $target['latitude']);
             // If two markers are closer than defined distance, remove compareMarker from array and add to cluster.
             if ($pixels < $distance) {
                 unset($markers[$key]);
                 $target['distance'] = $pixels;
                 $cluster[] = $target;
             }
         }
         // If a marker was added to cluster, also add the marker we were comparing to.
         if (count($cluster) > 0) {
             $cluster[] = $marker;
             $clusters[] = $cluster;
         } else {
             $singles[] = $marker;
         }
     }
     // Create Json
     foreach ($clusters as $cluster) {
         // Calculate cluster center
         $bounds = $this->calculate_center($cluster);
         $cluster_center = array_values($bounds['center']);
         $southwest = $bounds['sw']['longitude'] . ',' . $bounds['sw']['latitude'];
         $northeast = $bounds['ne']['longitude'] . ',' . $bounds['ne']['latitude'];
         // Number of Items in Cluster
         $cluster_count = count($cluster);
         // Get the time filter
         $time_filter = (!empty($start_date) and !empty($end_date)) ? "&s=" . $start_date . "&e=" . $end_date : "";
         // Build out the JSON string
         $link = url::base() . "reports/index/?c=" . $category_id . "&sw=" . $southwest . "&ne=" . $northeast . $time_filter;
         $item_name = $this->get_title(Kohana::lang('ui_main.reports_count', $cluster_count), $link);
         $json_item = array();
         $json_item['type'] = 'Feature';
         $json_item['properties'] = array('name' => $item_name, 'link' => $link, 'category' => array($category_id), 'color' => $color, 'icon' => $icon, 'thumb' => '', 'timestamp' => 0, 'count' => $cluster_count);
         $json_item['geometry'] = array('type' => 'Point', 'coordinates' => $cluster_center);
         array_push($json_features, $json_item);
     }
     foreach ($singles as $single) {
         $link = url::base() . "reports/view/" . $single['id'];
         $item_name = $this->get_title($single['incident_title'], $link);
         $json_item = array();
         $json_item['type'] = 'Feature';
         $json_item['properties'] = array('name' => $item_name, 'link' => $link, 'category' => array($category_id), 'color' => $color, 'icon' => $icon, 'thumb' => '', 'timestamp' => 0, 'count' => 1);
         $json_item['geometry'] = array('type' => 'Point', 'coordinates' => array($single['longitude'], $single['latitude']));
         array_push($json_features, $json_item);
     }
     //
     // E.Kala July 27, 2011
     // @todo Parking this geometry business for review
     //
     // if (count($geometry_array))
     // {
     // 	$json = implode(",", $geometry_array).",".$json;
     // }
     Event::run('ushahidi_filter.json_cluster_features', $json_features);
     $json = json_encode(array("type" => "FeatureCollection", "features" => $json_features));
     header('Content-type: application/json; charset=utf-8');
     echo $json;
 }
Example #25
0
 /**
  * Generate geojson
  * 
  * @param string $type type of geojson to generate. Valid options are: 'clusters' and 'markers'
  **/
 protected function geojson($type)
 {
     $color = Kohana::config('settings.default_map_all');
     $icon = "";
     $markers = FALSE;
     if (Kohana::config('settings.default_map_all_icon_id')) {
         $icon_object = ORM::factory('media')->find(Kohana::config('settings.default_map_all_icon_id'));
         $icon = url::convert_uploaded_to_abs($icon_object->media_medium);
     }
     // Category ID
     $category_id = (isset($_GET['c']) and intval($_GET['c']) > 0) ? intval($_GET['c']) : 0;
     // Get the category colour
     if (Category_Model::is_valid_category($category_id)) {
         // Get the color & icon
         $cat = ORM::factory('category', $category_id);
         $color = $cat->category_color;
         $icon = "";
         if ($cat->category_image) {
             $icon = url::convert_uploaded_to_abs($cat->category_image);
         }
     }
     $params = array('color' => $color, 'icon' => $icon);
     Event::run('ushahidi_filter.json_alter_params', $params);
     $color = $params['color'];
     $icon = $params['icon'];
     // Run event ushahidi_filter.json_replace_markers
     // This allows a plugin to completely replace $markers
     // If markers are added at this point we don't bother fetching incidents at all
     Event::run('ushahidi_filter.json_replace_markers', $markers);
     // Fetch the incidents
     if (!$markers) {
         $markers = (isset($_GET['page']) and intval($_GET['page']) > 0) ? reports::fetch_incidents(TRUE) : reports::fetch_incidents();
     }
     // Run event ushahidi_filter.json_alter_markers
     // This allows a plugin to alter $markers
     // Plugins can add or remove markers as needed
     Event::run('ushahidi_filter.json_alter_markers', $markers);
     // Get geojson features array
     $function = "{$type}_geojson";
     $json_features = $this->{$function}($markers, $category_id, $color, $icon);
     $this->render_geojson($json_features);
 }
 /**
  * Function: json_timeline
  *
  * Description: Creates the json of incidents that goes on the timeline
  *
  * @param obj $controller - The controller that's calling this function
  * @param bool $on_the_back_end - True if this json is going to a client on the backend
  * @param string $extra_where_text - If you want to add some extra where text to the SQL
  * @param array $joins - Array of joins you'd like to add. Great if you're looking to select things based on non-standard tables
  * @param array $custom_category_to_table_mapping - Maps what the joins are on.
  * 
  * Views:
  *
  * Results:  Json is sent to the client
  */
 public static function json_timeline($controller, $on_the_back_end = true, $extra_where_text = "", $joins = array(), $custom_category_to_table_mapping = array())
 {
     $category_ids = array('0');
     //get the coloring mode
     $color_mode = ORM::factory('enhancedmap_settings')->where('key', 'color_mode')->find()->value;
     if (isset($_GET['c']) and is_array($_GET['c'])) {
         $category_ids = array();
         //make sure we only hanlde numeric cat ids
         foreach ($_GET['c'] as $cat) {
             if (is_numeric($cat)) {
                 $category_ids[] = $cat;
             }
         }
     }
     $is_all_categories = false;
     if (count($category_ids) == 0 || $category_ids[0] == '0') {
         $is_all_categories = true;
     }
     $controller->auto_render = FALSE;
     $db = new Database();
     $interval = (isset($_GET["i"]) and !empty($_GET["i"])) ? $_GET["i"] : "month";
     // Get the Counts
     $select_date_text = "DATE_FORMAT(incident_date, '%Y-%m-01')";
     $groupby_date_text = "DATE_FORMAT(incident_date, '%Y%m')";
     if ($interval == 'day') {
         $select_date_text = "DATE_FORMAT(incident_date, '%Y-%m-%d')";
         $groupby_date_text = "DATE_FORMAT(incident_date, '%Y%m%d')";
     } elseif ($interval == 'hour') {
         $select_date_text = "DATE_FORMAT(incident_date, '%Y-%m-%d %H:%M')";
         $groupby_date_text = "DATE_FORMAT(incident_date, '%Y%m%d%H')";
     } elseif ($interval == 'week') {
         $select_date_text = "STR_TO_DATE(CONCAT(CAST(YEARWEEK(incident_date) AS CHAR), ' Sunday'), '%X%V %W')";
         $groupby_date_text = "YEARWEEK(incident_date)";
     }
     //more than one color
     $color = Kohana::config('settings.default_map_all');
     if ($is_all_categories) {
     } else {
         if ($color_mode == 'merge_all') {
             //more than one color
             $colors = array();
             foreach ($category_ids as $cat) {
                 $colors[] = ORM::factory('category', $cat)->category_color;
             }
             $color = self::merge_colors($colors);
         } else {
             if ($color_mode == 'highest_first') {
                 $highest_color = null;
                 foreach ($category_ids as $cat) {
                     $c = ORM::factory('category', $cat);
                     if ($highest_color == null or $highest_color->category_position > $c->category_position) {
                         $highest_color = $c;
                     }
                 }
                 $color = $highest_color->category_color;
             }
         }
     }
     $graph_data = array();
     $graph_data[0] = array();
     $graph_data[0]['label'] = "Category Title";
     //is this used for anything?
     $graph_data[0]['color'] = '#' . $color;
     $graph_data[0]['data'] = array();
     $incidents = reports::fetch_incidents();
     $approved_IDs_str = "('-1')";
     if (count($incidents) > 0) {
         $i = 0;
         $approved_IDs_str = "(";
         foreach ($incidents as $incident) {
             $i++;
             $approved_IDs_str = $i > 1 ? $approved_IDs_str . ', ' : $approved_IDs_str;
             $approved_IDs_str = $approved_IDs_str . "'" . $incident->incident_id . "'";
         }
         $approved_IDs_str = $approved_IDs_str . ") ";
     }
     $table_prefix = Kohana::config('database.default.table_prefix');
     $query = 'SELECT UNIX_TIMESTAMP(' . $select_date_text . ') AS time, COUNT(id) AS number FROM ' . $table_prefix . 'incident WHERE incident.id in' . $approved_IDs_str . ' GROUP BY ' . $groupby_date_text;
     $query = $db->query($query);
     foreach ($query as $items) {
         array_push($graph_data[0]['data'], array($items->time * 1000, $items->number));
     }
     header('Content-type: application/json; charset=utf-8');
     echo json_encode($graph_data);
 }
 /**
  * Edit a report
  * @param bool|int $id The id no. of the report
  * @param bool|string $saved
  */
 public function edit($id = FALSE, $saved = FALSE)
 {
     $db = new Database();
     $this->template->content = new View('members/reports_edit');
     $this->template->content->title = Kohana::lang('ui_admin.create_report');
     // Setup and initialize form field names
     $form = array('location_id' => '', 'form_id' => '1', 'locale' => '', 'incident_title' => '', 'incident_description' => '', 'incident_date' => '', 'incident_hour' => '', 'incident_minute' => '', 'incident_ampm' => '', 'latitude' => '', 'longitude' => '', 'geometry' => array(), 'location_name' => '', 'country_id' => '', 'country_name' => '', 'incident_category' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '', 'custom_field' => array(), 'incident_zoom' => '', 'incident_source' => '', 'incident_information' => '');
     // Copy the form as errors, so the errors will be stored with keys
     // corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = $saved == 'saved';
     // Initialize Default Values
     $form['locale'] = Kohana::config('locale.language');
     $form['latitude'] = Kohana::config('settings.default_lat');
     $form['longitude'] = Kohana::config('settings.default_lon');
     $form['country_id'] = Kohana::config('settings.default_country');
     $form['incident_date'] = date("m/d/Y", time());
     $form['incident_hour'] = date('h');
     $form['incident_minute'] = date('i');
     $form['incident_ampm'] = date('a');
     // Initialize custom field array
     $form_id = $form['form_id'];
     $form['custom_field'] = customforms::get_custom_form_fields($id, $form_id, TRUE);
     // Locale (Language) Array
     $this->template->content->locale_array = Kohana::config('locale.all_languages');
     // Time formatting
     $this->template->content->hour_array = $this->_hour_array();
     $this->template->content->minute_array = $this->_minute_array();
     $this->template->content->ampm_array = $this->_ampm_array();
     $this->template->content->stroke_width_array = $this->_stroke_width_array();
     // Get Countries
     $countries = array();
     foreach (ORM::factory('country')->orderby('country')->find_all() as $country) {
         // Create a list of all categories
         $this_country = $country->country;
         if (strlen($this_country) > 35) {
             $this_country = substr($this_country, 0, 35) . "...";
         }
         $countries[$country->id] = $this_country;
     }
     $this->template->content->countries = $countries;
     // Initialize Default Value for Hidden Field Country Name, just incase Reverse Geo coding yields no result
     $form['country_name'] = $countries[$form['country_id']];
     //GET custom forms
     $forms = array();
     foreach (ORM::factory('form')->where('form_active', 1)->find_all() as $custom_forms) {
         $forms[$custom_forms->id] = $custom_forms->form_title;
     }
     $this->template->content->forms = $forms;
     // Retrieve thumbnail photos (if edit);
     //XXX: fix _get_thumbnails
     $this->template->content->incident = $this->_get_thumbnails($id);
     // Check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite $_POST fields with our own things
         $post = array_merge($_POST, $_FILES);
         if (reports::validate($post)) {
             // STEP 1: SAVE LOCATION
             $location = new Location_Model();
             reports::save_location($post, $location);
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model($id);
             reports::save_report($post, $incident, $location->id);
             // STEP 2b: SAVE INCIDENT GEOMETRIES
             reports::save_report_geometry($post, $incident);
             // STEP 3: SAVE CATEGORIES
             reports::save_category($post, $incident);
             // STEP 4: SAVE MEDIA
             reports::save_media($post, $incident);
             // STEP 5: SAVE CUSTOM FORM FIELDS
             reports::save_custom_fields($post, $incident);
             // STEP 6: SAVE PERSONAL INFORMATION
             reports::save_personal_info($post, $incident);
             // Action::report_add / report_submit_members - Added a New Report
             Event::run('ushahidi_action.report_submit_members', $post);
             Event::run('ushahidi_action.report_edit', $incident);
             // SAVE AND CLOSE?
             if ($post->save == 1) {
                 // Save but don't close
                 url::redirect('members/reports/edit/' . $incident->id . '/saved');
             } else {
                 // Save and close
                 url::redirect('members/reports/');
             }
         } else {
             // Repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // Populate the error fields, if any
             $errors = arr::overwrite($errors, $post->errors('report'));
             $form_error = TRUE;
         }
     } else {
         if ($id) {
             // Retrieve Current Incident
             $incident = ORM::factory('incident')->where('user_id', $this->user->id)->find($id);
             if ($incident->loaded == true) {
                 // Retrieve Categories
                 $incident_category = array();
                 foreach ($incident->incident_category as $category) {
                     $incident_category[] = $category->category_id;
                 }
                 // Retrieve Media
                 $incident_news = array();
                 $incident_video = array();
                 $incident_photo = array();
                 foreach ($incident->media as $media) {
                     if ($media->media_type == 4) {
                         $incident_news[] = $media->media_link;
                     } elseif ($media->media_type == 2) {
                         $incident_video[] = $media->media_link;
                     } elseif ($media->media_type == 1) {
                         $incident_photo[] = $media->media_link;
                     }
                 }
                 // Get Geometries via SQL query as ORM can't handle Spatial Data
                 $sql = "SELECT AsText(geometry) as geometry, geometry_label, \n\t\t\t\t\t\tgeometry_comment, geometry_color, geometry_strokewidth \n\t\t\t\t\t\tFROM " . Kohana::config('database.default.table_prefix') . "geometry \n\t\t\t\t\t\tWHERE incident_id = ?";
                 $query = $db->query($sql, $id);
                 foreach ($query as $item) {
                     $geometry = array("geometry" => $item->geometry, "label" => $item->geometry_label, "comment" => $item->geometry_comment, "color" => $item->geometry_color, "strokewidth" => $item->geometry_strokewidth);
                     $form['geometry'][] = json_encode($geometry);
                 }
                 // Combine Everything
                 $incident_arr = array('location_id' => $incident->location->id, 'form_id' => $incident->form_id, 'locale' => $incident->locale, 'incident_title' => $incident->incident_title, 'incident_description' => $incident->incident_description, 'incident_date' => date('m/d/Y', strtotime($incident->incident_date)), 'incident_hour' => date('h', strtotime($incident->incident_date)), 'incident_minute' => date('i', strtotime($incident->incident_date)), 'incident_ampm' => date('a', strtotime($incident->incident_date)), 'latitude' => $incident->location->latitude, 'longitude' => $incident->location->longitude, 'location_name' => $incident->location->location_name, 'country_id' => $incident->location->country_id, 'incident_category' => $incident_category, 'incident_news' => $incident_news, 'incident_video' => $incident_video, 'incident_photo' => $incident_photo, 'person_first' => $incident->incident_person->person_first, 'person_last' => $incident->incident_person->person_last, 'person_email' => $incident->incident_person->person_email, 'incident_source' => '', 'incident_information' => '', 'custom_field' => customforms::get_custom_form_fields($id, $incident->form_id, TRUE), 'incident_zoom' => $incident->incident_zoom);
                 // Merge To Form Array For Display
                 $form = arr::overwrite($form, $incident_arr);
             } else {
                 // Redirect
                 url::redirect('members/reports/');
             }
         }
     }
     $this->template->content->id = $id;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     // Retrieve Custom Form Fields Structure
     $this->template->content->custom_forms = new View('reports/submit_custom_forms');
     $disp_custom_fields = customforms::get_custom_form_fields($id, $form['form_id'], FALSE, "view");
     $custom_field_mismatch = customforms::get_edit_mismatch($form['form_id']);
     // Quick hack to make sure view-only fields have data set
     foreach ($custom_field_mismatch as $id => $field) {
         $form['custom_field'][$id] = $disp_custom_fields[$id]['field_response'];
     }
     $this->template->content->custom_forms->disp_custom_fields = $disp_custom_fields;
     $this->template->content->custom_forms->custom_field_mismatch = $custom_field_mismatch;
     $this->template->content->custom_forms->form = $form;
     // Retrieve Previous & Next Records
     $previous = ORM::factory('incident')->where('id < ', $id)->orderby('id', 'desc')->find();
     $previous_url = $previous->loaded ? url::site('members/reports/edit/' . $previous->id) : url::site() . 'members/reports/';
     $next = ORM::factory('incident')->where('id > ', $id)->orderby('id', 'desc')->find();
     $next_url = $next->loaded ? url::site('members/reports/edit/' . $next->id) : url::site('members/reports/');
     $this->template->content->previous_url = $previous_url;
     $this->template->content->next_url = $next_url;
     // Javascript Header
     $this->themes->map_enabled = TRUE;
     $this->themes->colorpicker_enabled = TRUE;
     $this->themes->treeview_enabled = TRUE;
     $this->themes->json2_enabled = TRUE;
     $this->themes->js = new View('reports/submit_edit_js');
     $this->themes->js->edit_mode = FALSE;
     $this->themes->js->default_map = Kohana::config('settings.default_map');
     $this->themes->js->default_zoom = Kohana::config('settings.default_zoom');
     if (!$form['latitude'] or !$form['longitude']) {
         $this->themes->js->latitude = Kohana::config('settings.default_lat');
         $this->themes->js->longitude = Kohana::config('settings.default_lon');
     } else {
         $this->themes->js->latitude = $form['latitude'];
         $this->themes->js->longitude = $form['longitude'];
     }
     $this->themes->js->incident_zoom = $form['incident_zoom'];
     $this->themes->js->geometries = $form['geometry'];
     // Inline Javascript
     $this->template->content->date_picker_js = $this->_date_picker_js();
     $this->template->content->color_picker_js = $this->_color_picker_js();
     // Pack Javascript
     $myPacker = new javascriptpacker($this->themes->js, 'Normal', FALSE, FALSE);
     $this->themes->js = $myPacker->pack();
 }
Example #28
0
 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      |
 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   |
 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT        |
 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,   |
 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY   |
 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT     |
 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   |
 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.    |
 |                                                                         |
 +-------------------------------------------------------------------------+
*/
include "../../include/session.php";
include "include/tables.php";
include "include/fields.php";
include "include/reports.php";
$thetable = new reports($db, "tbld:d595ef42-db9d-2233-1b9b-11dfd0db9cbb");
$therecord = $thetable->processAddEditPage();
if ($therecord["id"]) {
    $reportSettings = new reportSettings($db, $therecord["uuid"]);
    $reportSettings->get();
}
//endif
if (isset($therecord["phpbmsStatus"])) {
    $statusmessage = $therecord["phpbmsStatus"];
}
$pageTitle = "Report";
$phpbms->cssIncludes[] = "pages/base/reports.css";
$phpbms->jsIncludes[] = "modules/base/javascript/reports.js";
//Form Elements
//==============================================================
$theform = new phpbmsForm(NULL, "post", "record", NULL);
                $path = $common->path;
                $xtemplate = $path . "templates/career/reports_compliance_self.html";
                $file = $common->return_file_content($db_object, $xtemplate);
                preg_match($pattern, $file, $match);
                $match = $match[0];
                for ($a = 0; $a < count($result1); $a++) {
                    $userid = $result1[$a][user_id];
                    $name = $common->name_display($db_object, $userid);
                    $date = $result1[$a][date];
                    $email = $result1[$a][email];
                    $rating = $result1[$a][test_type];
                    $str .= preg_replace("/<{(.*?)}>/e", "\$\$1", $match);
                }
                $file = preg_replace($pattern, $str, $file);
                $file = $common->direct_replace($db_object, $file, $xArray);
                echo $file;
            } else {
                echo $error_msg['cNoPending'];
                include_once "footer.php";
                exit;
            }
        } else {
            echo $error_msg['cNoReports'];
            include_once "footer.php";
            exit;
        }
    }
}
$obj = new reports();
$obj->reports_compliance($db_object, $common, $user_id, $error_msg);
include_once "footer.php";
Example #30
0
 /**
  * Create a report and assign it to one or more categories and set verification
  */
 public function __response_create_report($vars)
 {
     $categories = array();
     if (isset($vars['add_category'])) {
         $categories = $vars['add_category'];
     }
     $verify = 0;
     if (isset($vars['verify'])) {
         $verify = (int) $vars['verify'];
     }
     $approve = 0;
     if (isset($vars['approve'])) {
         $approve = (int) $vars['approve'];
     }
     // Grab the location_id or create one if we can
     $location_id = 0;
     if (isset($this->data->location_id)) {
         $location_id = $this->data->location_id;
     } elseif (isset($this->data->latitude) and isset($this->data->longitude)) {
         $location_name = map::reverse_geocode($this->data->latitude, $this->data->longitude);
         // In case our location name is too long, chop off the end
         $location_name = substr_replace($location_name, '', 250);
         $location_data = (object) array('location_name' => $location_name, 'latitude' => $this->data->latitude, 'longitude' => $this->data->longitude);
         $location = new Location_Model();
         reports::save_location($location_data, $location);
         $location_id = $location->id;
     }
     // We can only create reports if we have location.
     if ($location_id == FALSE or $location_id == 0) {
         return false;
     }
     // Save Incident
     $incident = new Incident_Model();
     $incident->location_id = $location_id;
     $incident->incident_title = $vars['report_title'];
     $incident->incident_description = $this->data->message;
     $incident->incident_date = $this->data->message_date;
     $incident->incident_active = $approve;
     $incident->incident_verified = $verify;
     $incident->incident_dateadd = date("Y-m-d H:i:s", time());
     $incident->save();
     // Conflicted.. do I run report add here? Potential to create a mess with action triggers?
     //Event::run('ushahidi_action.report_add', $incident);
     $incident_id = $incident->id;
     foreach ($categories as $category_id) {
         // Assign Category
         Incident_Category_Model::assign_category_to_incident($incident_id, $category_id);
     }
     // Link message with incident?
     if (isset($this->data->message) and isset($this->data->id)) {
         $message = new Message_Model($this->data->id);
         $message->incident_id = $incident_id;
         $message->save();
     }
     return TRUE;
 }