/**
  * Adds reports in JSON format to the database
  * @param string $data - CF JSON results
  */
 private function add_reports($data)
 {
     $reports = json_decode($data, false);
     foreach ($reports as $report) {
         //Save the Report location
         $location = new Location_Model();
         $location->longitude = $report->{'longitude'};
         $location->latitude = $report->{'latitude'};
         $location->location_name = $report->{'location_city'};
         $location->save();
         // Save CF result as Report
         $incident = new Incident_Model();
         $incident->location_id = $location->id;
         // $incident->id = $report->{'id'};
         $incident->incident_title = date("Y-m-d H:i:s", time());
         $incident->incident_description = $report->{'sms_text'};
         $incident->incident_date = date("Y-m-d H:i:s", time());
         $incident->incident_dateadd = date("Y-m-d H:i:s", time());
         $incident->incident_active = 1;
         $incident->incident_verified = 1;
         $incident->save();
         // Save Incident Category
         $categories = explode(",", $report->{'categories'});
         foreach ($categories as $category) {
             $report_category_id = ORM::factory("category")->where("category_title", $category)->find();
             if ($report_category_id->loaded) {
                 $incident_category = new Incident_Category_Model();
                 $incident_category->incident_id = $incident->id;
                 $incident_category->category_id = $report_category_id->id;
                 $incident_category->save();
             }
         }
     }
 }
Example #2
0
 function index()
 {
     $this->template->content = new View('admin/dashboard');
     $this->template->content->title = Kohana::lang('ui_admin.dashboard');
     $this->template->this_page = 'dashboard';
     // Retrieve Dashboard Count...
     // Total Reports
     $this->template->content->reports_total = ORM::factory('incident')->count_all();
     // Total Unapproved Reports
     $this->template->content->reports_unapproved = ORM::factory('incident')->where('incident_active', '0')->count_all();
     // Total Unverified Reports
     $this->template->content->reports_unverified = ORM::factory('incident')->where('incident_verified', '0')->count_all();
     // Total Categories
     $this->template->content->categories = ORM::factory('category')->count_all();
     // Total Locations
     $this->template->content->locations = ORM::factory('location')->count_all();
     // Total Incoming Media
     $this->template->content->incoming_media = ORM::factory('feed_item')->count_all();
     // Messages By Service
     $total_message_count = 0;
     $message_services = array();
     $services = ORM::factory('service')->find_all();
     foreach ($services as $service) {
         $message_count = ORM::factory('message')->join('reporter', 'message.reporter_id', 'reporter.id')->where('service_id', $service->id)->where('message_type', '1')->count_all();
         $message_services[] = array('id' => $service->id, 'name' => $service->service_name, 'count' => $message_count);
         $total_message_count += $message_count;
     }
     $this->template->content->message_services = $message_services;
     // Total Messages
     $this->template->content->message_count = $total_message_count;
     // Get reports for display
     $incidents = ORM::factory('incident')->limit(5)->orderby('incident_dateadd', 'desc')->find_all();
     $this->template->content->incidents = $incidents;
     // Get Incoming Media (We'll Use NewsFeeds for now)
     $this->template->content->feeds = ORM::factory('feed_item')->limit('3')->orderby('item_date', 'desc')->find_all();
     /*
     // Javascript Header
     $this->template->flot_enabled = TRUE;
     $this->template->js = new View('admin/dashboard_js');
     // Graph
     $this->template->js->all_graphs = Incident_Model::get_incidents_by_interval('ALL',NULL,NULL,'all');
     $this->template->js->current_date = date('Y') . '/' . date('m') . '/01';
     */
     // Javascript Header
     $this->template->protochart_enabled = TRUE;
     $this->template->js = new View('admin/stats_js');
     $this->template->content->failure = '';
     // Build dashboard chart
     // Set the date range (how many days in the past from today?)
     //    default to one year
     $range = isset($_GET['range']) ? $_GET['range'] : 365;
     if (isset($_GET['range']) and $_GET['range'] == 0) {
         $range = NULL;
     }
     $this->template->content->range = $range;
     $incident_data = Incident_Model::get_number_reports_by_date($range);
     $data = array('Reports' => $incident_data);
     $options = array('xaxis' => array('mode' => '"time"'));
     $this->template->content->report_chart = protochart::chart('report_chart', $data, $options, array('Reports' => 'CC0000'), 410, 310);
 }
Example #3
0
 function index()
 {
     $this->template->content = new View('members/dashboard');
     $this->template->content->title = Kohana::lang('ui_admin.dashboard');
     $this->template->this_page = 'dashboard';
     // User
     $this->template->content->user = $this->user;
     // User Reputation Score
     $this->template->content->reputation = reputation::calculate($this->user->id);
     // Get Badges
     $this->template->content->badges = Badge_Model::users_badges($this->user->id);
     // Retrieve Dashboard Counts...
     // Total Reports
     $this->template->content->reports_total = ORM::factory('incident')->where("user_id", $this->user->id)->count_all();
     // Total Unapproved Reports
     $this->template->content->reports_unapproved = ORM::factory('incident')->where('incident_active', '0')->where("user_id", $this->user->id)->count_all();
     // Total Checkins
     $this->template->content->checkins = ORM::factory('checkin')->where("user_id", $this->user->id)->count_all();
     // Total Alerts
     $this->template->content->alerts = ORM::factory('alert')->where("user_id", $this->user->id)->count_all();
     // Total Votes
     $this->template->content->votes = ORM::factory('rating')->where("user_id", $this->user->id)->count_all();
     // Total Votes Positive
     $this->template->content->votes_up = ORM::factory('rating')->where("user_id", $this->user->id)->where("rating", "1")->count_all();
     // Total Votes Negative
     $this->template->content->votes_down = ORM::factory('rating')->where("user_id", $this->user->id)->where("rating", "-1")->count_all();
     // Get reports for display
     $this->template->content->incidents = ORM::factory('incident')->where("user_id", $this->user->id)->limit(5)->orderby('incident_dateadd', 'desc')->find_all();
     // To support the "welcome" or "not enough info on user" form
     if ($this->user->public_profile == 1) {
         $this->template->content->profile_public = TRUE;
         $this->template->content->profile_private = FALSE;
     } else {
         $this->template->content->profile_public = FALSE;
         $this->template->content->profile_private = TRUE;
     }
     $this->template->content->hidden_welcome_fields = array('email' => $this->user->email, 'notify' => $this->user->notify, 'color' => $this->user->color, 'password' => '', 'needinfo' => 0);
     /*
     // Javascript Header
     $this->template->flot_enabled = TRUE;
     $this->template->js = new View('admin/dashboard_js');
     // Graph
     $this->template->js->all_graphs = Incident_Model::get_incidents_by_interval('ALL',NULL,NULL,'all');
     $this->template->js->current_date = date('Y') . '/' . date('m') . '/01';
     */
     // Javascript Header
     $this->template->protochart_enabled = TRUE;
     $this->template->js = new View('admin/stats_js');
     $this->template->content->failure = '';
     // Build dashboard chart
     // Set the date range (how many days in the past from today?)
     // Default to one year if invalid or not set
     $range = (isset($_GET['range']) and preg_match('/^\\d+$/', $_GET['range']) > 0) ? (int) $_GET['range'] : 365;
     // Phase 3 - Invoke Kohana's XSS cleaning mechanism just incase an outlier wasn't caught
     $range = $this->input->xss_clean($range);
     $incident_data = Incident_Model::get_number_reports_by_date($range, $this->user->id);
     $data = array('Reports' => $incident_data);
     $options = array('xaxis' => array('mode' => '"time"'));
     $this->template->content->report_chart = protochart::chart('report_chart', $data, $options, array('Reports' => 'CC0000'), 410, 310);
 }
 /**
  * Tests Incident_Model::is_valid_incident
  * @test
  */
 public function testIsValidIncident()
 {
     // Get any incident
     $random_incident = testutils::get_random_id('incident');
     $inactive_incident = testutils::get_random_id('incident', 'WHERE incident_active = 0');
     $active_incident = testutils::get_random_id('incident', 'WHERE incident_active = 1');
     //Test to see if there are data in the incident table to test with.
     if (empty($random_incident)) {
         $this->markTestSkipped('The incident table is empty.');
     } elseif (empty($inactive_incident)) {
         $this->markTestSkipped('No inactive incidents in incident table.');
     } elseif (empty($active_incident)) {
         $this->markTestSkipped('No active incidents in incident table.');
     } else {
         $this->assertEquals(TRUE, Incident_Model::is_valid_incident($random_incident, FALSE));
         // Get inactive incident
         $inactive_incident = testutils::get_random_id('incident', 'WHERE incident_active = 0');
         // Check fails with default args and explicitly limit to active only
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident($inactive_incident));
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident($inactive_incident, TRUE));
         // Check success when including inactive incidents
         $this->assertEquals(TRUE, Incident_Model::is_valid_incident($inactive_incident, FALSE));
         // Get active incident
         $active_incident = testutils::get_random_id('incident', 'WHERE incident_active = 1');
         // Check success with default args and explicitly limit to active only
         $this->assertEquals(TRUE, Incident_Model::is_valid_incident($active_incident));
         $this->assertEquals(TRUE, Incident_Model::is_valid_incident($active_incident, TRUE));
         // Null incident value
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident(NULL));
         // Non numeric incident value
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident('0.999'));
     }
 }
 /**
  * Tests fetching of incidents when the limit parameter is specified
  * @test
  */
 public function testGetIncidentsByLimit()
 {
     // Randomly generate the record limit
     $limit = rand(1, Incident_Model::get_incidents()->count());
     // HTTP GET data
     $_GET = array('task' => 'incidents', 'limit' => $limit);
     ob_start();
     $this->api_controller->index();
     $contents = json_decode(ob_get_clean());
     $this->assertEquals("0", $contents->error->code);
     $this->assertEquals($limit, count($contents->payload->incidents));
 }
Example #6
0
 function index()
 {
     $this->template->content = new View('admin/dashboard');
     $this->template->content->title = 'Dashboard';
     $this->template->this_page = 'dashboard';
     //		$this->template->header  = new View('header');
     // Retrieve Dashboard Count...
     // Total Reports
     $this->template->content->reports_total = ORM::factory('incident')->count_all();
     // Total Unapproved Reports
     $this->template->content->reports_unapproved = ORM::factory('incident')->where('incident_active', '0')->count_all();
     // Total Unverified Reports
     $this->template->content->reports_unverified = ORM::factory('incident')->where('incident_verified', '0')->count_all();
     // Total Categories
     $this->template->content->categories = ORM::factory('category')->count_all();
     // Total Locations
     $this->template->content->locations = ORM::factory('location')->count_all();
     // Total Incoming Media
     $this->template->content->incoming_media = ORM::factory('feed_item')->count_all();
     // Messages By Service
     $total_message_count = 0;
     $message_services = array();
     $services = ORM::factory('service')->find_all();
     foreach ($services as $service) {
         $message_count = ORM::factory('message')->join('reporter', 'message.reporter_id', 'reporter.id')->where('service_id', $service->id)->where('message_type', '1')->count_all();
         $message_services[] = array('id' => $service->id, 'name' => $service->service_name, 'count' => $message_count);
         $total_message_count += $message_count;
     }
     $this->template->content->message_services = $message_services;
     // Total Messages
     $this->template->content->message_count = $total_message_count;
     // Get reports for display
     $incidents = ORM::factory('incident')->limit(5)->orderby('incident_dateadd', 'desc')->find_all();
     $this->template->content->incidents = $incidents;
     // Get Incoming Media (We'll Use NewsFeeds for now)
     $this->template->content->feeds = ORM::factory('feed_item')->limit('3')->orderby('item_date', 'desc')->find_all();
     // Javascript Header
     $this->template->flot_enabled = TRUE;
     $this->template->js = new View('admin/dashboard_js');
     // Graph
     $this->template->js->all_graphs = Incident_Model::get_incidents_by_interval('ALL', NULL, NULL, 'all');
     $this->template->js->current_date = date('Y') . '/' . date('m') . '/01';
 }
 /**
  * Tests Incident_Model::is_valid_incident
  * @test
  */
 public function testIsValidIncident()
 {
     // Get any incident
     $random_incident = testutils::get_random_id('incident');
     //Test to see if there are data in the incident table to test with.
     if (empty($random_incident)) {
         $this->markTestSkipped('The incident table is empty.');
     } else {
         $this->assertEquals(TRUE, Incident_Model::is_valid_incident($random_incident));
         // Get inactive incident
         $inactive_incident = testutils::get_random_id('incident', 'WHERE incident_active = 0');
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident($inactive_incident, TRUE));
         // Get active incident
         $active_incident = testutils::get_random_id('incident', 'WHERE incident_active = 1');
         $this->assertEquals(TRUE, Incident_Model::is_valid_incident($active_incident, TRUE));
         // Null incident value
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident(NULL));
         // Non numeric incident value
         $this->assertEquals(FALSE, Incident_Model::is_valid_incident('0.999'));
     }
 }
Example #8
0
 /**
  * Retrieve Custom Form Fields
  * @param bool|int $incident_id The unique incident_id of the original report
  * @param int $form_id The unique form_id. Uses default form (1), if none selected
  * @param bool $field_names_only Whether or not to include just fields names, or field names + data
  * @param bool $data_only Whether or not to include just data
  * @param string $action If this is being used to grab fields for submit or view of data
  */
 public static function get_custom_form_fields($incident_id = FALSE, $form_id = 1, $data_only = FALSE, $action = "submit")
 {
     $fields_array = array();
     if (!$form_id) {
         $form_id = 1;
     }
     // Validation
     if (!Form_Model::is_valid_form($form_id)) {
         return $fields_array;
     }
     // Database table prefix
     $table_prefix = Kohana::config('database.default.table_prefix');
     //NOTE will probably need to add a user_level variable for non-web based requests
     $user_level = self::get_user_max_auth();
     // Get the predicates for the public state
     $public_state = $action == "view" ? '<=' . $user_level : ' <= ' . $user_level;
     // Query to fetch the form fields and their responses
     $sql = "SELECT ff.*, '' AS form_response FROM " . $table_prefix . "form_field ff WHERE 1=1 ";
     // Check if the provided incident exists
     if (Incident_Model::is_valid_incident($incident_id)) {
         // Overwrite the previous query
         $sql = "SELECT ff.*, fr.form_response " . "FROM " . $table_prefix . "form_field ff " . "RIGHT JOIN " . $table_prefix . "form_response fr ON (fr.form_field_id = ff.id) " . "WHERE fr.incident_id = " . $incident_id . " ";
     }
     $sql .= "AND ff.form_id = " . $form_id . " " . "AND ff.field_ispublic_visible " . $public_state . " " . "ORDER BY ff.field_position ASC";
     // Execute the SQL to fetch the custom form fields
     $form_fields = Database::instance()->query($sql);
     foreach ($form_fields as $custom_formfield) {
         if ($data_only) {
             // Return Data Only
             $fields_array[$custom_formfield->id] = $custom_formfield->form_response;
         } else {
             // Return Field Structure
             $fields_array[$custom_formfield->id] = array('field_id' => $custom_formfield->id, 'field_name' => $custom_formfield->field_name, 'field_type' => $custom_formfield->field_type, 'field_default' => $custom_formfield->field_default, 'field_required' => $custom_formfield->field_required, 'field_maxlength' => $custom_formfield->field_maxlength, 'field_height' => $custom_formfield->field_height, 'field_width' => $custom_formfield->field_width, 'field_isdate' => $custom_formfield->field_isdate, 'field_ispublic_visible' => $custom_formfield->field_ispublic_visible, 'field_ispublic_submit' => $custom_formfield->field_ispublic_submit, 'field_response' => $custom_formfield->form_response);
         }
     }
     // Garbage collection
     unset($form_fields);
     // Return
     return $fields_array;
 }
Example #9
0
 /**
  * Retrieve Custom Form Fields
  * @param bool|int $incident_id The unique incident_id of the original report
  * @param int $form_id The unique form_id. If none selected, retrieve custom form fields from ALL custom forms
  * @param bool $data_only Whether or not to include just data
  * @param string $action If this is being used to grab fields for submit or view of data
  */
 public static function get_custom_form_fields($incident_id = FALSE, $form_id = NULL, $data_only = FALSE, $action = "submit")
 {
     $fields_array = array();
     // If we have a form id but its invalid, return empty
     if (!empty($form_id) and !Form_Model::is_valid_form($form_id)) {
         return $fields_array;
     }
     // Database table prefix
     $table_prefix = Kohana::config('database.default.table_prefix');
     // Get field we'll check permissions against
     $ispublic_field = $action == "view" ? 'field_ispublic_visible' : 'field_ispublic_submit';
     // NOTE will probably need to add a user_level variable for non-web based requests
     $user_level = self::get_user_max_auth();
     // Check if incident is valid
     // Have to do this early since we can't build 2 ORM queries at once.
     $valid_incident = Incident_Model::is_valid_incident($incident_id, FALSE);
     // Check if the provided incident exists, then fill in the data
     if ($valid_incident) {
         $sql = "SELECT ff.*, fr.form_response\n\t\t\tFROM `{$table_prefix}form_field` ff\n\t\t\tLEFT JOIN `{$table_prefix}roles` r ON (r.id = {$ispublic_field})\n\t\t\tLEFT JOIN\n\t\t\t\t`{$table_prefix}form_response` fr ON (\n\t\t\t\t\tfr.form_field_id = ff.id AND\n\t\t\t\t\tfr.incident_id = :incident_id\n\t\t\t\t)\n\t\t\tWHERE (access_level <= :user_level OR access_level IS NULL) " . (!empty($form_id) ? "AND form_id = :form_id " : '') . "ORDER BY field_position ASC";
     } else {
         $sql = "SELECT ff.*\n\t\t\tFROM `{$table_prefix}form_field` ff\n\t\t\tLEFT JOIN `{$table_prefix}roles` r ON (r.id = {$ispublic_field})\n\t\t\tWHERE (access_level <= :user_level OR access_level IS NULL) " . (!empty($form_id) ? "AND form_id = :form_id " : '') . "ORDER BY field_position ASC";
     }
     $form_fields = Database::instance()->query($sql, array(':form_id' => $form_id, ':user_level' => $user_level, ':incident_id' => $incident_id));
     foreach ($form_fields as $custom_formfield) {
         if ($data_only) {
             // Return Data Only
             $fields_array[$custom_formfield->id] = isset($custom_formfield->form_response) ? $custom_formfield->form_response : '';
         } else {
             // Return Field Structure
             // JP: added field description
             $fields_array[$custom_formfield->id] = array('field_id' => $custom_formfield->id, 'form_id' => $custom_formfield->form_id, 'field_name' => $custom_formfield->field_name, 'field_description' => $custom_formfield->field_description, 'field_type' => $custom_formfield->field_type, 'field_default' => $custom_formfield->field_default, 'field_required' => $custom_formfield->field_required, 'field_maxlength' => $custom_formfield->field_maxlength, 'field_height' => $custom_formfield->field_height, 'field_width' => $custom_formfield->field_width, 'field_isdate' => $custom_formfield->field_isdate, 'field_ispublic_visible' => $custom_formfield->field_ispublic_visible, 'field_ispublic_submit' => $custom_formfield->field_ispublic_submit, 'field_response' => isset($custom_formfield->form_response) ? $custom_formfield->form_response : '');
         }
     }
     // Garbage collection
     unset($form_fields);
     // Return
     return $fields_array;
 }
Example #10
0
 function index()
 {
     $this->template->content = new View('admin/dashboard');
     $this->template->content->title = 'Dashboard';
     $this->template->this_page = 'dashboard';
     //		$this->template->header  = new View('header');
     // Retrieve Dashboard Count...
     // Total Reports
     $this->template->content->reports_total = ORM::factory('incident')->count_all();
     // Total Unapproved Reports
     $this->template->content->reports_unapproved = ORM::factory('incident')->where('incident_active', '0')->count_all();
     // Total Unverified Reports
     $this->template->content->reports_unverified = ORM::factory('incident')->where('incident_verified', '0')->count_all();
     // Total Categories
     $this->template->content->categories = ORM::factory('category')->count_all();
     // Total Locations
     $this->template->content->locations = ORM::factory('location')->count_all();
     // Total Incoming Media
     $this->template->content->incoming_media = ORM::factory('feed_item')->count_all();
     // Total SMS Messages
     $this->template->content->message_sms_count = ORM::factory('message')->count_all();
     // Total Twitter Messages
     $this->template->content->message_twitter_count = ORM::factory('twitter')->where('hide', 0)->count_all();
     // Total Message Count
     $this->template->content->message_count = $this->template->content->message_twitter_count + $this->template->content->message_sms_count;
     // Get reports for display
     $incidents = ORM::factory('incident')->limit(3)->orderby('incident_dateadd', 'desc')->find_all();
     $this->template->content->incidents = $incidents;
     // Get Incoming Media (We'll Use NewsFeeds for now)
     $this->template->content->feeds = ORM::factory('feed_item')->limit('3')->orderby('item_date', 'desc')->find_all();
     // Javascript Header
     $this->template->flot_enabled = TRUE;
     $this->template->js = new View('admin/dashboard_js');
     // Graph
     $this->template->js->all_graphs = Incident_Model::get_incidents_by_interval('ALL', NULL, NULL, 'all');
     $this->template->js->current_date = date('Y') . '/' . date('m') . '/01';
 }
Example #11
0
 /**
  * Adds hash tweets in JSON format to the database and saves the sender as a new
  * Reporter if they don't already exist
  * @param string $data - Twitter JSON results
  */
 private function add_hash_tweets($data)
 {
     if ($this->_lock()) {
         return false;
     }
     $services = new Service_Model();
     $service = $services->where('service_name', 'Twitter')->find();
     if (!$service) {
         $this->_unlock();
         return false;
     }
     $tweets = json_decode($data, false);
     if (!$tweets) {
         $this->_unlock();
         return false;
     }
     if (isset($tweets->{'error'})) {
         $this->_unlock();
         return false;
     }
     $tweet_results = $tweets->{'results'};
     foreach ($tweet_results as $tweet) {
         $reporter = ORM::factory('reporter')->where('service_id', $service->id)->where('service_account', $tweet->{'from_user'})->find();
         if (!$reporter->loaded) {
             // get default reporter level (Untrusted)
             $level = ORM::factory('level')->where('level_weight', 0)->find();
             $reporter->service_id = $service->id;
             $reporter->level_id = $level->id;
             $reporter->service_account = $tweet->{'from_user'};
             $reporter->reporter_first = null;
             $reporter->reporter_last = null;
             $reporter->reporter_email = null;
             $reporter->reporter_phone = null;
             $reporter->reporter_ip = null;
             $reporter->reporter_date = date('Y-m-d');
             $reporter->save();
         }
         if ($reporter->level_id > 1 && count(ORM::factory("message")->where("service_messageid = '" . $tweet->{'id_str'} . "'")->find_all()) == 0) {
             // Grab geo data if it exists from the tweet
             $tweet_lat = null;
             $tweet_lon = null;
             if ($tweet->{'geo'} != null) {
                 $tweet_lat = $tweet->{'geo'}->coordinates[0];
                 $tweet_lon = $tweet->{'geo'}->coordinates[1];
             }
             // Save Tweet as Message
             $message = new Message_Model();
             $message->parent_id = 0;
             $message->incident_id = 0;
             $message->user_id = 0;
             $message->reporter_id = $reporter->id;
             $message->message_from = $tweet->{'from_user'};
             $message->message_to = null;
             $message->message = $tweet->{'text'};
             $message->message_type = 1;
             // Inbox
             $tweet_date = date("Y-m-d H:i:s", strtotime($tweet->{'created_at'}));
             $message->message_date = $tweet_date;
             $message->service_messageid = $tweet->{'id_str'};
             $message->latitude = $tweet_lat;
             $message->longitude = $tweet_lon;
             $message->save();
             // Action::message_twitter_add - Twitter Message Received!
             Event::run('ushahidi_action.message_twitter_add', $message);
             // Auto-Create A Report if Reporter is Trusted
             $reporter_weight = $reporter->level->level_weight;
             $reporter_location = $reporter->location;
             if ($reporter_weight > 0 and $reporter_location) {
                 $incident_title = text::limit_chars($message->message, 50, "...", false);
                 // Create Incident
                 $incident = new Incident_Model();
                 $incident->location_id = $reporter_location->id;
                 $incident->incident_title = $incident_title;
                 $incident->incident_description = $message->message;
                 $incident->incident_date = $tweet_date;
                 $incident->incident_dateadd = date("Y-m-d H:i:s", time());
                 $incident->incident_active = 1;
                 if ($reporter_weight == 2) {
                     $incident->incident_verified = 1;
                 }
                 $incident->save();
                 // Update Message with Incident ID
                 $message->incident_id = $incident->id;
                 $message->save();
                 // Save Incident Category
                 $trusted_categories = ORM::factory("category")->where("category_trusted", 1)->find();
                 if ($trusted_categories->loaded) {
                     $incident_category = new Incident_Category_Model();
                     $incident_category->incident_id = $incident->id;
                     $incident_category->category_id = $trusted_categories->id;
                     $incident_category->save();
                 }
             }
         }
     }
     $this->_unlock();
     return true;
 }
 function importreport($row, $group)
 {
     if (!strtotime($row['INCIDENT DATE'])) {
         $this->errors[] = 'Could not parse incident date "' . htmlspecialchars($row['INCIDENT DATE']) . '" on line ' . ($this->rownumber + 1);
     }
     if (isset($row["APPROVED"]) and !in_array($row["APPROVED"], array('NO', 'YES'))) {
         $this->errors[] = 'APPROVED must be either YES or NO on line ' . ($this->rownumber + 1);
     }
     if (isset($row["VERIFIED"]) and !in_array($row["VERIFIED"], array('NO', 'YES'))) {
         $this->errors[] = 'VERIFIED must be either YES or NO on line ' . ($this->rownumber + 1);
     }
     if (count($this->errors)) {
         return false;
     }
     // STEP 1: SAVE LOCATION
     if (isset($row['LOCATION'])) {
         $location = new Location_Model();
         $location->location_name = isset($row['LOCATION']) ? $row['LOCATION'] : '';
         $location->latitude = isset($row['LATITUDE']) ? $row['LATITUDE'] : '';
         $location->longitude = isset($row['LONGITUDE']) ? $row['LONGITUDE'] : '';
         $location->location_date = $this->time;
         $location->save();
         $this->locations_added[] = $location->id;
     }
     // STEP 2: SAVE INCIDENT
     $incident = new Incident_Model();
     $incident->location_id = isset($row['LOCATION']) ? $location->id : 0;
     $incident->user_id = 0;
     $incident->incident_title = $row['INCIDENT TITLE'];
     $incident->incident_description = isset($row['DESCRIPTION']) ? $row['DESCRIPTION'] : '';
     $incident->incident_date = date("Y-m-d H:i:s", strtotime($row['INCIDENT DATE']));
     $incident->incident_dateadd = $this->time;
     $incident->incident_active = (isset($row['APPROVED']) and $row['APPROVED'] == 'YES') ? 1 : 0;
     $incident->incident_verified = (isset($row['VERIFIED']) and $row['VERIFIED'] == 'YES') ? 1 : 0;
     $incident->save();
     $this->incidents_added[] = $incident->id;
     //STEP 2.5: SAVE THE GROUP ASSOCIATION
     $group_incident = ORM::factory("simplegroups_groups_incident");
     $group_incident->incident_id = $incident->id;
     $group_incident->simplegroups_groups_id = $group->id;
     $group_incident->save();
     // STEP 3: SAVE CATEGORIES
     if (isset($row['CATEGORY'])) {
         $categorynames = explode(',', trim($row['CATEGORY']));
         foreach ($categorynames as $categoryname) {
             $categoryname = strtoupper(trim($categoryname));
             // There seems to be an uppercase convention for categories... Don't know why.
             if ($categoryname != '') {
                 if (!isset($this->category_ids[$categoryname])) {
                     $this->notices[] = 'There exists no category "' . htmlspecialchars($categoryname) . '" in database yet. This category was skipped.';
                     continue;
                     /*
                     $this->notices[] = 'There exists no category "'.htmlspecialchars($categoryname).'" in database yet. Added to database.';
                     $category = new Category_Model;
                     $category->category_title = $categoryname;
                     $category->category_color = '000000'; // We'll just use black for now. Maybe something random?
                     $category->category_type = 5; // because all current categories are of type '5'
                     $category->category_visible = 1;
                     $category->category_description = $categoryname;
                     $category->save();
                     $this->categories_added[] = $category->id;
                     $this->category_ids[$categoryname] = $category->id; // Now category_id is known: This time, and for the rest of the import.
                     */
                 }
                 $incident_category = new Incident_Category_Model();
                 $incident_category->incident_id = $incident->id;
                 $incident_category->category_id = $this->category_ids[$categoryname];
                 $incident_category->save();
                 $this->incident_categories_added[] = $incident_category->id;
             }
             // empty categoryname not allowed
         }
         // add categories to incident
     }
     // if CATEGORIES column exists
     // STEP 4: SAVE GROUP CATEGORIES
     if (isset($row['GROUP CATEGORY'])) {
         $categorynames = explode(',', trim($row['GROUP CATEGORY']));
         foreach ($categorynames as $categoryname) {
             $categoryname = strtoupper(trim($categoryname));
             // There seems to be an uppercase convention for categories... Don't know why.
             if ($categoryname != '') {
                 if (!isset($this->group_category_ids[$categoryname])) {
                     $this->notices[] = 'There exists no category "' . htmlspecialchars($categoryname) . '" in the group categories yet. Added to database.';
                     $category = ORM::factory("simplegroups_category");
                     $category->category_title = $categoryname;
                     $category->category_color = '000000';
                     // We'll just use black for now. Maybe something random?
                     $category->category_type = 5;
                     // because all current categories are of type '5'
                     $category->category_visible = 1;
                     $category->category_description = $categoryname;
                     $category->simplegroups_groups_id = $group->id;
                     $category->applies_to_report = 1;
                     $category->save();
                     $this->categories_added[] = $category->id;
                     $this->group_category_ids[$categoryname] = $category->id;
                     // Now category_id is known: This time, and for the rest of the import.
                 }
                 $incident_category = ORM::factory("simplegroups_incident_category");
                 $incident_category->incident_id = $incident->id;
                 $incident_category->simplegroups_category_id = $this->group_category_ids[$categoryname];
                 $incident_category->save();
                 $this->incident_categories_added[] = $incident_category->id;
             }
             // empty categoryname not allowed
         }
         // add categories to incident
     }
     // if CATEGORIES column exists
     return true;
 }
Example #13
0
 function punchcard()
 {
     $this->template->content = new View('admin/stats/punchcard');
     $this->template->content->title = Kohana::lang('ui_admin.statistics');
     $incident_dates = Incident_Model::get_incident_dates();
     // Initialize the array. Zeroing everything out now to keep us from having to loop it
     $data = array('sun' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0), 'mon' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0), 'tue' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0), 'wed' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0), 'thu' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0), 'fri' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0), 'sat' => array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0, 16 => 0, 17 => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0));
     $highest_value = 0;
     foreach ($incident_dates as $datetime) {
         $t = strtotime($datetime);
         $dow = strtolower(date('D', $t));
         $hour = date('G', $t);
         $data[$dow][$hour] += 1;
         if ($data[$dow][$hour] > $highest_value) {
             $highest_value = $data[$dow][$hour];
         }
     }
     $this->template->content->chart_url = Kohana::config('core.site_protocol') . '://chart.googleapis.com/chart?chs=905x300&chds=-1,24,-1,7,0,' . $highest_value . '&chf=bg,s,efefef&chd=t:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23|0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7|' . implode(',', $data['sun']) . ',' . implode(',', $data['mon']) . ',' . implode(',', $data['tue']) . ',' . implode(',', $data['wed']) . ',' . implode(',', $data['thu']) . ',' . implode(',', $data['fri']) . ',' . implode(',', $data['sat']) . ',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0&chxt=x,y&chm=o,333333,1,1.0,30.0&chxl=0:||12' . Kohana::lang('datetime.am') . '|1|2|3|4|5|6|7|8|9|10|11|12' . Kohana::lang('datetime.pm') . '|1|2|3|4|5|6|7|8|9|10|11||1:||' . Kohana::lang('datetime.sunday.abbv') . '|' . Kohana::lang('datetime.monday.abbv') . '|' . Kohana::lang('datetime.tuesday.abbv') . '|' . Kohana::lang('datetime.wednesday.abbv') . '|' . Kohana::lang('datetime.thursday.abbv') . '|' . Kohana::lang('datetime.friday.abbv') . '|' . Kohana::lang('datetime.saturday.abbv') . '|&cht=s';
 }
Example #14
0
 public function index()
 {
     $this->template->header->this_page = 'home';
     $this->template->content = new View('main');
     // Get all active top level categories
     $parent_categories = array();
     foreach (ORM::factory('category')->where('category_visible', '1')->where('parent_id', '0')->find_all() as $category) {
         // Get The Children
         $children = array();
         foreach ($category->children as $child) {
             $children[$child->id] = array($child->category_title, $child->category_color);
         }
         // Put it all together
         $parent_categories[$category->id] = array($category->category_title, $category->category_color, $children);
     }
     $this->template->content->categories = $parent_categories;
     // Get all active Layers (KMZ/KML)
     $layers = array();
     $config_layers = Kohana::config('map.layers');
     // use config/map layers if set
     if ($config_layers == $layers) {
         foreach (ORM::factory('layer')->where('layer_visible', 1)->find_all() as $layer) {
             $layers[$layer->id] = array($layer->layer_name, $layer->layer_color, $layer->layer_url, $layer->layer_file);
         }
     } else {
         $layers = $config_layers;
     }
     $this->template->content->layers = $layers;
     // Get all active Shares
     $shares = array();
     foreach (ORM::factory('sharing')->where('sharing_active', 1)->where('sharing_type', 1)->find_all() as $share) {
         $shares[$share->id] = array($share->sharing_site_name, $share->sharing_color);
     }
     $this->template->content->shares = $shares;
     // Get Reports
     // XXX: Might need to replace magic no. 8 with a constant
     $this->template->content->total_items = ORM::factory('incident')->where('incident_active', '1')->limit('8')->count_all();
     $this->template->content->incidents = ORM::factory('incident')->where('incident_active', '1')->limit('10')->orderby('incident_date', 'desc')->with('location')->find_all();
     // Get Default Color
     $this->template->content->default_map_all = Kohana::config('settings.default_map_all');
     // Get Twitter Hashtags
     $this->template->content->twitter_hashtag_array = array_filter(array_map('trim', explode(',', Kohana::config('settings.twitter_hashtags'))));
     // Get Report-To-Email
     $this->template->content->report_email = Kohana::config('settings.site_email');
     // Get SMS Numbers
     $phone_array = array();
     $sms_no1 = Kohana::config('settings.sms_no1');
     $sms_no2 = Kohana::config('settings.sms_no2');
     $sms_no3 = Kohana::config('settings.sms_no3');
     if (!empty($sms_no1)) {
         $phone_array[] = $sms_no1;
     }
     if (!empty($sms_no2)) {
         $phone_array[] = $sms_no2;
     }
     if (!empty($sms_no3)) {
         $phone_array[] = $sms_no3;
     }
     $this->template->content->phone_array = $phone_array;
     // Get RSS News Feeds
     $this->template->content->feeds = ORM::factory('feed_item')->limit('10')->orderby('item_date', 'desc')->find_all();
     // Get The START, END and most ACTIVE Incident Dates
     $startDate = "";
     $endDate = "";
     $active_month = 0;
     $active_startDate = 0;
     $active_endDate = 0;
     $db = new Database();
     // First Get The Most Active Month
     $query = $db->query('SELECT incident_date, count(*) AS incident_count FROM ' . $this->table_prefix . 'incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_date, \'%Y-%m\') ORDER BY incident_count DESC LIMIT 1');
     foreach ($query as $query_active) {
         $active_month = date('n', strtotime($query_active->incident_date));
         $active_year = date('Y', strtotime($query_active->incident_date));
         $active_startDate = strtotime($active_year . "-" . $active_month . "-01");
         $active_endDate = strtotime($active_year . "-" . $active_month . "-" . date('t', mktime(0, 0, 0, $active_month, 1)) . " 23:59:59");
     }
     // Next, Get the Range of Years
     $query = $db->query('SELECT DATE_FORMAT(incident_date, \'%Y\') AS incident_date FROM ' . $this->table_prefix . 'incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_date, \'%Y\') ORDER BY incident_date');
     foreach ($query as $slider_date) {
         $years = $slider_date->incident_date;
         $startDate .= "<optgroup label=\"" . $years . "\">";
         for ($i = 1; $i <= 12; $i++) {
             if ($i < 10) {
                 $i = "0" . $i;
             }
             $startDate .= "<option value=\"" . strtotime($years . "-" . $i . "-01") . "\"";
             if ($active_month && (int) $i == $active_month - 1) {
                 $startDate .= " selected=\"selected\" ";
             }
             $startDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $years . "</option>";
         }
         $startDate .= "</optgroup>";
         $endDate .= "<optgroup label=\"" . $years . "\">";
         for ($i = 1; $i <= 12; $i++) {
             if ($i < 10) {
                 $i = "0" . $i;
             }
             $endDate .= "<option value=\"" . strtotime($years . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59") . "\"";
             // Focus on the most active month or set December as month of endDate
             if ($active_month && (int) $i == $active_month + 1 || $i == 12 && preg_match('/selected/', $endDate) == 0) {
                 $endDate .= " selected=\"selected\" ";
             }
             $endDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $years . "</option>";
         }
         $endDate .= "</optgroup>";
     }
     $this->template->content->startDate = $startDate;
     $this->template->content->endDate = $endDate;
     // get graph data
     // could not use DB query builder. It does not support parentheses yet
     $graph_data = array();
     $all_graphs = Incident_Model::get_incidents_by_interval('month');
     $daily_graphs = Incident_Model::get_incidents_by_interval('day');
     $weekly_graphs = Incident_Model::get_incidents_by_interval('week');
     $hourly_graphs = Incident_Model::get_incidents_by_interval('hour');
     $this->template->content->all_graphs = $all_graphs;
     $this->template->content->daily_graphs = $daily_graphs;
     // If we are looking at the standard street map set by user
     if (!isset($_GET['3dmap'])) {
         //echo 'STREET MAP';
         // Javascript Header
         $this->template->header->map_enabled = 'streetmap';
         $this->template->content->map_enabled = 'streetmap';
         $this->template->content->map_container = 'map';
         $this->template->header->main_page = TRUE;
         $this->template->header->validator_enabled = TRUE;
         // Map Settings
         $clustering = Kohana::config('settings.allow_clustering');
         $marker_radius = Kohana::config('map.marker_radius');
         $marker_opacity = Kohana::config('map.marker_opacity');
         $marker_stroke_width = Kohana::config('map.marker_stroke_width');
         $marker_stroke_opacity = Kohana::config('map.marker_stroke_opacity');
         // pdestefanis - allows to restrict the number of zoomlevels available
         $numZoomLevels = Kohana::config('map.numZoomLevels');
         $minZoomLevel = Kohana::config('map.minZoomLevel');
         $maxZoomLevel = Kohana::config('map.maxZoomLevel');
         // pdestefanis - allows to limit the extents of the map
         $lonFrom = Kohana::config('map.lonFrom');
         $latFrom = Kohana::config('map.latFrom');
         $lonTo = Kohana::config('map.lonTo');
         $latTo = Kohana::config('map.latTo');
         $this->template->header->js = $clustering ? new View('main_cluster_js') : new View('main_cluster_js');
         if ($clustering == 1) {
             //$this->template->header->js->cluster = "true"; // not used??
             $this->template->header->js->default_json_url = "json_cluster";
         } else {
             //$this->template->header->js->cluster = "false"; // not used??
             $this->template->header->js->default_json_url = "json";
         }
         $this->template->header->js->marker_radius = $marker_radius >= 1 && $marker_radius <= 10 ? $marker_radius : 5;
         $this->template->header->js->marker_opacity = $marker_opacity >= 1 && $marker_opacity <= 10 ? $marker_opacity * 0.1 : 0.9;
         $this->template->header->js->marker_stroke_width = $marker_stroke_width >= 1 && $marker_stroke_width <= 5 ? $marker_stroke_width : 2;
         $this->template->header->js->marker_stroke_opacity = $marker_stroke_opacity >= 1 && $marker_stroke_opacity <= 10 ? $marker_stroke_opacity * 0.1 : 0.9;
         // pdestefanis - allows to restrict the number of zoomlevels available
         $this->template->header->js->numZoomLevels = $numZoomLevels;
         $this->template->header->js->minZoomLevel = $minZoomLevel;
         $this->template->header->js->maxZoomLevel = $maxZoomLevel;
         // pdestefanis - allows to limit the extents of the map
         $this->template->header->js->lonFrom = $lonFrom;
         $this->template->header->js->latFrom = $latFrom;
         $this->template->header->js->lonTo = $lonTo;
         $this->template->header->js->latTo = $latTo;
         $this->template->header->js->default_map = Kohana::config('settings.default_map');
         $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
         $this->template->header->js->latitude = Kohana::config('settings.default_lat');
         $this->template->header->js->longitude = Kohana::config('settings.default_lon');
         $this->template->header->js->graph_data = $graph_data;
         $this->template->header->js->all_graphs = $all_graphs;
         $this->template->header->js->daily_graphs = $daily_graphs;
         $this->template->header->js->hourly_graphs = $hourly_graphs;
         $this->template->header->js->weekly_graphs = $weekly_graphs;
         $this->template->header->js->default_map_all = Kohana::config('settings.default_map_all');
         //
         $this->template->header->js->active_startDate = $active_startDate;
         $this->template->header->js->active_endDate = $active_endDate;
         // If we are viewing the 3D map
     } else {
         //echo '3D MAP';
         // Javascript Header
         $this->template->header->map_enabled = '3dmap';
         $this->template->content->map_enabled = '3dmap';
         $this->template->content->map_container = 'map3d';
         $this->template->header->main_page = FALSE;
         // Setting to false because we don't want all the external controls that the street map has
         $this->template->header->js = new View('main_3d_js');
         $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
         $this->template->header->js->latitude = Kohana::config('settings.default_lat');
         $this->template->header->js->longitude = Kohana::config('settings.default_lon');
         // Override API URL
         $this->template->header->api_url = '<script src="http://www.google.com/jsapi?key=' . Kohana::config('settings.api_google') . '"> </script>';
     }
     $myPacker = new javascriptpacker($this->template->header->js, 'Normal', false, false);
     $this->template->header->js = $myPacker->pack();
 }
Example #15
0
 /**
  * Edit a report
  * @param bool|int $id The id no. of the report
  * @param bool|string $saved
  */
 function edit($id = false, $saved = false)
 {
     $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' => '', '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_active' => '', 'incident_verified' => '', '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;
     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('g');
     $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();
     $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();
     // 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')->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 SMS/Email/Twitter?
     // If so retrieve message
     if (isset($_GET['mid']) && !empty($_GET['mid'])) {
         $message_id = $_GET['mid'];
         $service_id = "";
         $message = ORM::factory('message', $message_id);
         if ($message->loaded == true && $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)) {
                 $incident_description .= "\n\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n" . $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;
             // 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']) && !empty($_GET['fid'])) {
         $feed_item_id = $_GET['fid'];
         $feed_item = ORM::factory('feed_item', $feed_item_id);
         if ($feed_item->loaded == true) {
             // 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;
             }
         } 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 = 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_active', 'required', 'between[0,1]');
         $post->add_rules('incident_verified', 'required', 'length[0,1]');
         $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()) {
             // Yes! everything is valid
             $location_id = $post->location_id;
             // STEP 1: SAVE LOCATION
             $location = new Location_Model($location_id);
             $location->location_name = $post->location_name;
             $location->latitude = $post->latitude;
             $location->longitude = $post->longitude;
             $location->location_date = date("Y-m-d H:i:s", time());
             $location->save();
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model($id);
             $incident->location_id = $location->id;
             //$incident->locale = $post->locale;
             $incident->form_id = $post->form_id;
             $incident->user_id = $_SESSION['auth_user']->id;
             $incident->incident_title = $post->incident_title;
             $incident->incident_description = $post->incident_description;
             $incident_date = explode("/", $post->incident_date);
             // where the $_POST['date'] is a value posted by form in mm/dd/yyyy format
             $incident_date = $incident_date[2] . "-" . $incident_date[0] . "-" . $incident_date[1];
             $incident_time = $post->incident_hour . ":" . $post->incident_minute . ":00 " . $post->incident_ampm;
             $incident->incident_date = date("Y-m-d H:i:s", strtotime($incident_date . " " . $incident_time));
             // Is this new or edit?
             if ($id) {
                 $incident->incident_datemodify = date("Y-m-d H:i:s", time());
             } else {
                 $incident->incident_dateadd = date("Y-m-d H:i:s", time());
             }
             // Is this an Email, SMS, Twitter submitted report?
             //XXX: We may get rid of incident_mode altogether... ???
             //$_POST
             if (!empty($service_id)) {
                 if ($service_id == 1) {
                     // SMS
                     $incident->incident_mode = 2;
                 } elseif ($service_id == 2) {
                     // Email
                     $incident->incident_mode = 3;
                 } elseif ($service_id == 3) {
                     // Twitter
                     $incident->incident_mode = 4;
                 } elseif ($service_id == 4) {
                     // Laconica
                     $incident->incident_mode = 5;
                 }
             }
             // Incident Evaluation Info
             $incident->incident_active = $post->incident_active;
             $incident->incident_verified = $post->incident_verified;
             $incident->incident_source = $post->incident_source;
             $incident->incident_information = $post->incident_information;
             //Save
             $incident->save();
             // Record Approval/Verification Action
             $verify = new Verify_Model();
             $verify->incident_id = $incident->id;
             $verify->user_id = $_SESSION['auth_user']->id;
             // Record 'Verified By' Action
             $verify->verified_date = date("Y-m-d H:i:s", time());
             if ($post->incident_active == 1) {
                 $verify->verified_status = '1';
             } elseif ($post->incident_verified == 1) {
                 $verify->verified_status = '2';
             } elseif ($post->incident_active == 1 && $post->incident_verified == 1) {
                 $verify->verified_status = '3';
             } else {
                 $verify->verified_status = '0';
             }
             $verify->save();
             // STEP 3: SAVE CATEGORIES
             ORM::factory('Incident_Category')->where('incident_id', $incident->id)->delete_all();
             // Delete Previous Entries
             foreach ($post->incident_category as $item) {
                 $incident_category = new Incident_Category_Model();
                 $incident_category->incident_id = $incident->id;
                 $incident_category->category_id = $item;
                 $incident_category->save();
             }
             // STEP 4: SAVE MEDIA
             ORM::factory('Media')->where('incident_id', $incident->id)->where('media_type <> 1')->delete_all();
             // Delete Previous Entries
             // a. News
             foreach ($post->incident_news as $item) {
                 if (!empty($item)) {
                     $news = new Media_Model();
                     $news->location_id = $location->id;
                     $news->incident_id = $incident->id;
                     $news->media_type = 4;
                     // News
                     $news->media_link = $item;
                     $news->media_date = date("Y-m-d H:i:s", time());
                     $news->save();
                 }
             }
             // b. Video
             foreach ($post->incident_video as $item) {
                 if (!empty($item)) {
                     $video = new Media_Model();
                     $video->location_id = $location->id;
                     $video->incident_id = $incident->id;
                     $video->media_type = 2;
                     // Video
                     $video->media_link = $item;
                     $video->media_date = date("Y-m-d H:i:s", time());
                     $video->save();
                 }
             }
             // c. Photos
             $filenames = upload::save('incident_photo');
             $i = 1;
             foreach ($filenames as $filename) {
                 $new_filename = $incident->id . "_" . $i . "_" . time();
                 // Resize original file... make sure its max 408px wide
                 Image::factory($filename)->resize(408, 248, Image::AUTO)->save(Kohana::config('upload.directory', TRUE) . $new_filename . ".jpg");
                 // Create thumbnail
                 Image::factory($filename)->resize(70, 41, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_t.jpg");
                 // Remove the temporary file
                 unlink($filename);
                 // Save to DB
                 $photo = new Media_Model();
                 $photo->location_id = $location->id;
                 $photo->incident_id = $incident->id;
                 $photo->media_type = 1;
                 // Images
                 $photo->media_link = $new_filename . ".jpg";
                 $photo->media_thumb = $new_filename . "_t.jpg";
                 $photo->media_date = date("Y-m-d H:i:s", time());
                 $photo->save();
                 $i++;
             }
             // STEP 5: SAVE PERSONAL INFORMATION
             ORM::factory('Incident_Person')->where('incident_id', $incident->id)->delete_all();
             // Delete Previous Entries
             $person = new Incident_Person_Model();
             $person->location_id = $location->id;
             $person->incident_id = $incident->id;
             $person->person_first = $post->person_first;
             $person->person_last = $post->person_last;
             $person->person_email = $post->person_email;
             $person->person_date = date("Y-m-d H:i:s", time());
             $person->save();
             // STEP 6a: SAVE LINK TO REPORTER MESSAGE
             // We're creating a report from a message with this option
             if (isset($message_id) && $message_id != "") {
                 $savemessage = ORM::factory('message', $message_id);
                 if ($savemessage->loaded == true) {
                     $savemessage->incident_id = $incident->id;
                     $savemessage->save();
                 }
             }
             // STEP 6b: SAVE LINK TO NEWS FEED
             // We're creating a report from a newsfeed with this option
             if (isset($feed_item_id) && $feed_item_id != "") {
                 $savefeed = ORM::factory('feed_item', $feed_item_id);
                 if ($savefeed->loaded == true) {
                     $savefeed->incident_id = $incident->id;
                     $savefeed->location_id = $location->id;
                     $savefeed->save();
                 }
             }
             // STEP 7: SAVE CUSTOM FORM FIELDS
             if (isset($post->custom_field)) {
                 foreach ($post->custom_field as $key => $value) {
                     $form_response = ORM::factory('form_response')->where('form_field_id', $key)->where('incident_id', $incident->id)->find();
                     if ($form_response->loaded == true) {
                         $form_response->form_field_id = $key;
                         $form_response->form_response = $value;
                         $form_response->save();
                     } else {
                         $form_response = new Form_Response_Model();
                         $form_response->form_field_id = $key;
                         $form_response->incident_id = $incident->id;
                         $form_response->form_response = $value;
                         $form_response->save();
                     }
                 }
             }
             // SAVE AND CLOSE?
             if ($post->save == 1) {
                 url::redirect('admin/reports/edit/' . $incident->id . '/saved');
             } else {
                 url::redirect('admin/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', $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;
                     }
                 }
                 // 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_active' => $incident->incident_active, 'incident_verified' => $incident->incident_verified, 'incident_source' => $incident->incident_source, 'incident_information' => $incident->incident_information);
                 // 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
     $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() . 'admin/reports/edit/' . $previous->id : url::base() . 'admin/reports/';
     $next = ORM::factory('incident')->where('id > ', $id)->orderby('id', 'desc')->find();
     $next_url = $next->loaded ? url::base() . 'admin/reports/edit/' . $next->id : url::base() . 'admin/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->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'];
     }
     // 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();
 }
Example #16
0
					</td>
				</tr>
			</table>
		</div>
		<!-- /Top reportbox section-->
		
		<!-- Report listing -->
		<div class="r_cat_tooltip"><a href="#" class="r-3"></a></div>
		<div class="rb_list-and-map-box">
			<div id="rb_list-view">
			<?php 
foreach ($incidents as $incident) {
    $incident_id = $incident->incident_id;
    $incident_title = strip_tags($incident->incident_title);
    $incident_description = strip_tags($incident->incident_description);
    $incident_url = Incident_Model::get_url($incident_id);
    //$incident_category = $incident->incident_category;
    // Trim to 150 characters without cutting words
    // XXX: Perhaps delcare 150 as constant
    $incident_description = text::limit_chars(strip_tags($incident_description), 140, "...", true);
    $incident_date = date('H:i M d, Y', strtotime($incident->incident_date));
    //$incident_time = date('H:i', strtotime($incident->incident_date));
    $location_id = $incident->location_id;
    $location_name = $incident->location_name;
    $comment_count = ORM::Factory('comment')->where('incident_id', $incident_id)->count_all();
    $incident_thumb = url::file_loc('img') . "media/img/report-thumb-default.jpg";
    $media = ORM::Factory('media')->where('incident_id', $incident_id)->find_all();
    if ($media->count()) {
        foreach ($media as $photo) {
            if ($photo->media_thumb) {
                // Get the first thumb
Example #17
0
 /**
  * Approve a report and assign it to one or more categories
  */
 public function __response_approve_report($vars)
 {
     $incident_id = $this->data->id;
     $categories = array();
     if (isset($vars['add_category'])) {
         $categories = $vars['add_category'];
     }
     $verify = 0;
     if (isset($vars['verify'])) {
         $verify = (int) $vars['verify'];
     }
     foreach ($categories as $category_id) {
         // Assign Category
         Incident_Category_Model::assign_category_to_incident($incident_id, $category_id);
     }
     // Approve Report
     Incident_Model::set_approve($incident_id, 1);
     // Set Verification
     Incident_Model::set_verification($incident_id, $verify);
     return TRUE;
 }
Example #18
0
 /**
  * the actual reporting - ***must find a cleaner way to do this than duplicating code verbatim - modify report***
  */
 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' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '');
     //	copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $this->messages = $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 = 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('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 ($this->_verifyArrayIndex($_POST, 'incident_ampm')) {
             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]');
         $post->add_rules('incident_category', 'required', 'length[3,100]');
         // 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]');
         }
         // Test to see if things passed the rule checks
         if ($post->validate()) {
             // SAVE LOCATION (***IF IT DOES NOT EXIST***)
             $location = new Location_Model();
             $location->location_name = $post->location_name;
             $location->latitude = $post->latitude;
             $location->longitude = $post->longitude;
             $location->location_date = date("Y-m-d H:i:s", time());
             $location->save();
             // SAVE INCIDENT
             $incident = new Incident_Model();
             $incident->location_id = $location->id;
             $incident->user_id = 0;
             $incident->incident_title = $post->incident_title;
             $incident->incident_description = $post->incident_description;
             $incident_date = split("/", $post->incident_date);
             // where the $_POST['date'] is a value posted by form in mm/dd/yyyy format
             $incident_date = $incident_date[2] . "-" . $incident_date[0] . "-" . $incident_date[1];
             $incident_time = $post->incident_hour . ":" . $post->incident_minute . ":00 " . $post->incident_ampm;
             $incident->incident_date = $incident_date . " " . $incident_time;
             $incident->incident_dateadd = date("Y-m-d H:i:s", time());
             $incident->save();
             // SAVE CATEGORIES
             //check if data is array or a serialized data.
             if (is_array($post->incident_category)) {
                 $categories = $post->incident_category;
             } else {
                 $categories = unserialize($post->incident_category);
             }
             if (!empty($categories) && is_array($categories)) {
                 foreach ($categories as $item) {
                     $incident_category = new Incident_Category_Model();
                     $incident_category->incident_id = $incident->id;
                     $incident_category->category_id = $item;
                     $incident_category->save();
                 }
             }
             // STEP 4: SAVE MEDIA
             // a. News
             if (!empty($post->incident_news) && is_array($post->incident_news)) {
                 foreach ($post->incident_news as $item) {
                     if (!empty($item)) {
                         $news = new Media_Model();
                         $news->location_id = $location->id;
                         $news->incident_id = $incident->id;
                         $news->media_type = 4;
                         // News
                         $news->media_link = $item;
                         $news->media_date = date("Y-m-d H:i:s", time());
                         $news->save();
                     }
                 }
             }
             // b. Video
             if (!empty($post->incident_video) && is_array($post->incident_video)) {
                 foreach ($post->incident_video as $item) {
                     if (!empty($item)) {
                         $video = new Media_Model();
                         $video->location_id = $location->id;
                         $video->incident_id = $incident->id;
                         $video->media_type = 2;
                         // Video
                         $video->media_link = $item;
                         $video->media_date = date("Y-m-d H:i:s", time());
                         $video->save();
                     }
                 }
             }
             // c. Photos
             if (!empty($post->incident_photo)) {
                 $filenames = upload::save('incident_photo');
                 $i = 1;
                 foreach ($filenames as $filename) {
                     $new_filename = $incident->id . "_" . $i . "_" . time();
                     // Resize original file... make sure its max 408px wide
                     Image::factory($filename)->resize(408, 248, Image::AUTO)->save(Kohana::config('upload.directory', TRUE) . $new_filename . ".jpg");
                     // Create thumbnail
                     Image::factory($filename)->resize(70, 41, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_t.jpg");
                     // Remove the temporary file
                     unlink($filename);
                     // Save to DB
                     $photo = new Media_Model();
                     $photo->location_id = $location->id;
                     $photo->incident_id = $incident->id;
                     $photo->media_type = 1;
                     // Images
                     $photo->media_link = $new_filename . ".jpg";
                     $photo->media_thumb = $new_filename . "_t.jpg";
                     $photo->media_date = date("Y-m-d H:i:s", time());
                     $photo->save();
                     $i++;
                 }
             }
             // SAVE PERSONAL INFORMATION IF ITS FILLED UP
             if (!empty($post->person_first) || !empty($post->person_last)) {
                 $person = new Incident_Person_Model();
                 $person->location_id = $location->id;
                 $person->incident_id = $incident->id;
                 $person->person_first = $post->person_first;
                 $person->person_last = $post->person_last;
                 $person->person_email = $post->person_email;
                 $person->person_date = date("Y-m-d H:i:s", time());
                 $person->save();
             }
             return 0;
             //success
         } 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_messages .= $error_description;
                     if ($error_description != end($this->messages)) {
                         $this->error_messages .= " - ";
                     }
                 }
             }
             //FAILED!!!
             return 1;
             //validation error
         }
     } else {
         return 2;
         // Not sent by post method.
     }
 }
Example #19
0
 /**
  * Adds email to the database and saves the sender as a new
  * Reporter if they don't already exist
  * @param string $messages
  */
 private function add_email($messages)
 {
     $service = ORM::factory('service')->where('service_name', 'Email')->find();
     if (!$service->loaded) {
         return;
     }
     if (empty($messages) or !is_array($messages)) {
         return;
     }
     foreach ($messages as $message) {
         $reporter = ORM::factory('reporter')->where('service_id', $service->id)->where('service_account', $message['email'])->find();
         if (!$reporter->loaded == true) {
             // Add new reporter
             $names = explode(' ', $message['from'], 2);
             $last_name = '';
             if (count($names) == 2) {
                 $last_name = $names[1];
             }
             // get default reporter level (Untrusted)
             $level = ORM::factory('level')->where('level_weight', 0)->find();
             $reporter->service_id = $service->id;
             $reporter->level_id = $level->id;
             $reporter->service_account = $message['email'];
             $reporter->reporter_first = $names[0];
             $reporter->reporter_last = $last_name;
             $reporter->reporter_email = $message['email'];
             $reporter->reporter_phone = null;
             $reporter->reporter_ip = null;
             $reporter->reporter_date = date('Y-m-d');
             $reporter->save();
         }
         if ($reporter->level_id > 1 && count(ORM::factory('message')->where('service_messageid', $message['message_id'])->find_all()) == 0) {
             // Save Email as Message
             $email = new Message_Model();
             $email->parent_id = 0;
             $email->incident_id = 0;
             $email->user_id = 0;
             $email->reporter_id = $reporter->id;
             $email->message_from = $message['from'];
             $email->message_to = null;
             $email->message = $message['subject'];
             $email->message_detail = $message['body'];
             $email->message_type = 1;
             // Inbox
             $email->message_date = $message['date'];
             $email->service_messageid = $message['message_id'];
             $email->save();
             // Attachments?
             foreach ($message['attachments'] as $attachments) {
                 foreach ($attachments as $attachment) {
                     $media = new Media_Model();
                     $media->location_id = 0;
                     $media->incident_id = 0;
                     $media->message_id = $email->id;
                     $media->media_type = 1;
                     // Images
                     $media->media_link = $attachment[0];
                     $media->media_medium = $attachment[1];
                     $media->media_thumb = $attachment[2];
                     $media->media_date = date("Y-m-d H:i:s", time());
                     $media->save();
                 }
             }
             // Auto-Create A Report if Reporter is Trusted
             $reporter_weight = $reporter->level->level_weight;
             $reporter_location = $reporter->location;
             if ($reporter_weight > 0 and $reporter_location) {
                 // Create Incident
                 $incident = new Incident_Model();
                 $incident->location_id = $reporter_location->id;
                 $incident->incident_title = $message['subject'];
                 $incident->incident_description = $message['body'];
                 $incident->incident_date = $message['date'];
                 $incident->incident_dateadd = date("Y-m-d H:i:s", time());
                 $incident->incident_active = 1;
                 if ($reporter_weight == 2) {
                     $incident->incident_verified = 1;
                 }
                 $incident->save();
                 // Update Message with Incident ID
                 $email->incident_id = $incident->id;
                 $email->save();
                 // Save Incident Category
                 $trusted_categories = ORM::factory("category")->where("category_trusted", 1)->find();
                 if ($trusted_categories->loaded) {
                     $incident_category = new Incident_Category_Model();
                     $incident_category->incident_id = $incident->id;
                     $incident_category->category_id = $trusted_categories->id;
                     $incident_category->save();
                 }
                 // Add Attachments
                 $attachments = ORM::factory("media")->where("message_id", $email->id)->find_all();
                 foreach ($attachments as $attachment) {
                     $attachment->incident_id = $incident->id;
                     $attachment->save();
                 }
             }
             // Notify Admin Of New Email Message
             $send = notifications::notify_admins("[" . Kohana::config('settings.site_name') . "] " . Kohana::lang('notifications.admin_new_email.subject'), Kohana::lang('notifications.admin_new_email.message'));
             // Action::message_email_add - Email Received!
             Event::run('ushahidi_action.message_email_add', $email);
         }
     }
 }
Example #20
0
 public function index()
 {
     $this->template->header->this_page = 'home';
     $this->template->content = new View('main');
     //get images from flickr
     $flickr = new PhpFlickr('7ffd3c4b9d9f3a486b67124d5b530f11');
     $haiti_photos = $flickr->photos_search(array('text' => 'earthquake in haiti', 'per_page' => 12));
     $this->template->content->flickr = $flickr;
     $this->template->content->haiti_photos = $haiti_photos;
     // Get all active top level categories
     $parent_categories = array();
     foreach (ORM::factory('category')->where('category_visible', '1')->where('parent_id', '0')->find_all() as $category) {
         // Get The Children
         $children = array();
         foreach ($category->children as $child) {
             $children[$child->id] = array($child->category_title, $child->category_color, $child->category_image);
         }
         // Put it all together
         $parent_categories[$category->id] = array($category->category_title, $category->category_color, $category->category_image, $children);
     }
     $this->template->content->categories = $parent_categories;
     // Get all active Layers (KMZ/KML)
     $layers = array();
     foreach (ORM::factory('layer')->where('layer_visible', 1)->find_all() as $layer) {
         $layers[$layer->id] = array($layer->layer_name, $layer->layer_color, $layer->layer_url, $layer->layer_file);
     }
     $this->template->content->layers = $layers;
     // Get all active Shares
     $shares = array();
     foreach (ORM::factory('sharing')->where('sharing_active', 1)->where('sharing_type', 1)->find_all() as $share) {
         $shares[$share->id] = array($share->sharing_site_name, $share->sharing_color);
     }
     $this->template->content->shares = $shares;
     // Get Reports
     // XXX: Might need to replace magic no. 8 with a constant
     $this->template->content->total_items = ORM::factory('incident')->where('incident_active', '1')->limit('8')->count_all();
     $this->template->content->incidents = ORM::factory('incident')->where('incident_active', '1')->limit('14')->orderby('incident_date', 'desc')->with('location')->find_all();
     // Get quick stats for "Latest Activity"
     // note: Kohana ORM doesn't support these fancy date search features
     $this->template->content->latest_activity_today = count($this->db->query('SELECT id FROM incident WHERE incident_dateadd >= DATE_SUB(CURDATE(),INTERVAL 0 DAY);'));
     $this->template->content->latest_activity_yesterday = count($this->db->query('SELECT id FROM incident WHERE incident_dateadd >= DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND incident_dateadd < DATE_SUB(CURDATE(),INTERVAL 0 DAY);'));
     $this->template->content->latest_activity_week = count($this->db->query('SELECT id FROM incident WHERE incident_dateadd >= DATE_SUB(CURDATE(),INTERVAL 1 WEEK);'));
     $this->template->content->latest_activity_total_from_sms = Incident_Model::num_incidents_by_sms();
     // End getting of quick stats for "Latest Activity"
     // Get Default Color
     $this->template->content->default_map_all = Kohana::config('settings.default_map_all');
     // Get Twitter Hashtags
     $this->template->content->twitter_hashtag_array = array_filter(array_map('trim', explode(',', Kohana::config('settings.twitter_hashtags'))));
     // Get Report-To-Email
     $this->template->content->report_email = Kohana::config('settings.site_email');
     // Get SMS Numbers
     $phone_array = array();
     $sms_no1 = Kohana::config('settings.sms_no1');
     $sms_no2 = Kohana::config('settings.sms_no2');
     $sms_no3 = Kohana::config('settings.sms_no3');
     if (!empty($sms_no1)) {
         $phone_array[] = $sms_no1;
     }
     if (!empty($sms_no2)) {
         $phone_array[] = $sms_no2;
     }
     if (!empty($sms_no3)) {
         $phone_array[] = $sms_no3;
     }
     $this->template->content->phone_array = $phone_array;
     $this->template->header->phone_array = $phone_array;
     // Because we need some custom language around these numbers,
     // I'm just sending them straight to the template for "hardcoding"
     $this->template->content->sms_no1 = $sms_no1;
     $this->template->content->sms_no2 = $sms_no2;
     $this->template->header->sms_no1 = $sms_no1;
     $this->template->header->sms_no2 = $sms_no2;
     // Get RSS News Feeds but don't include Global Voices (8)
     $this->template->content->feeds = ORM::factory('feed_item')->limit('10')->where('feed_id !=', '8')->orderby('item_date', 'desc')->find_all();
     // Get Global Voices Feed
     $this->template->content->gvfeeds = ORM::factory('feed_item')->limit('10')->where('feed_id', '8')->orderby('item_date', 'desc')->find_all();
     // Get The START, END and most ACTIVE Incident Dates
     $startDate = "";
     $endDate = "";
     $active_month = 0;
     $active_startDate = 0;
     $active_endDate = 0;
     $db = new Database();
     // First Get The Most Active Month
     $query = $db->query('SELECT incident_date, count(*) AS incident_count FROM incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_date, \'%Y-%m\') ORDER BY incident_count DESC LIMIT 1');
     foreach ($query as $query_active) {
         $active_month = date('n', strtotime($query_active->incident_date));
         $active_year = date('Y', strtotime($query_active->incident_date));
         $active_startDate = strtotime($active_year . "-" . $active_month . "-01");
         $active_endDate = strtotime($active_year . "-" . $active_month . "-" . date('t', mktime(0, 0, 0, $active_month, 1)) . " 23:59:59");
     }
     /** HARDCODED SLIDER SET UP **/
     // We'll Hardcode in the Start/End Dates
     $timeframe_start = strtotime("2010-01-12", 0);
     $timeframe_stop = strtotime(date("Y-m-d"), 0);
     $active_startDate = $timeframe_start;
     $active_endDate = $timeframe_stop + 86399;
     $days = floor(($timeframe_stop - $timeframe_start) / 86400);
     $startDate = "<optgroup label=\"2010\">";
     $endDate = "<optgroup label=\"2010\">";
     for ($i = 0; $i <= $days; $i++) {
         $startDate .= "<option value=\"" . $timeframe_start . "\"";
         if ($i == 0) {
             $startDate .= " selected=\"selected\" ";
         }
         $startDate .= ">" . date('M j', $timeframe_start) . " 2010</option>";
         $timeframe_stop = $timeframe_start + 86399;
         $endDate .= "<option value=\"" . $timeframe_stop . "\"";
         if ($i == $days) {
             $endDate .= " selected=\"selected\" ";
         }
         $endDate .= ">" . date('M j', $timeframe_stop) . " 2010</option>";
         $timeframe_start = $timeframe_start + 86400;
     }
     $startDate .= "</optgroup>";
     $endDate .= "</optgroup>";
     /** OLD SLIDER SET UP **/
     // Next, Get the Range of Years
     //        $query = $db->query('SELECT DATE_FORMAT(incident_date, \'%Y\') AS incident_date FROM incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_date, \'%Y\') ORDER BY incident_date');
     $query = array();
     foreach ($query as $slider_date) {
         $years = $slider_date->incident_date;
         $startDate .= "<optgroup label=\"" . $years . "\">";
         for ($i = 1; $i <= 12; $i++) {
             if ($i < 10) {
                 $i = "0" . $i;
             }
             $startDate .= "<option value=\"" . strtotime($years . "-" . $i . "-01") . "\"";
             if ($active_month && (int) $i == $active_month - 1) {
                 $startDate .= " selected=\"selected\" ";
             }
             $startDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $years . "</option>";
         }
         $startDate .= "</optgroup>";
         $endDate .= "<optgroup label=\"" . $years . "\">";
         for ($i = 1; $i <= 12; $i++) {
             if ($i < 10) {
                 $i = "0" . $i;
             }
             $endDate .= "<option value=\"" . strtotime($years . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59") . "\"";
             if ($active_month && (int) $i == $active_month + 1 || $i == 12) {
                 $endDate .= " selected=\"selected\" ";
             }
             $endDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $years . "</option>";
         }
         $endDate .= "</optgroup>";
     }
     $this->template->content->startDate = $startDate;
     $this->template->content->endDate = $endDate;
     //$this->template->content->startDate = '<select name="startDate" id="startDate"><optgroup label="2010"><option value="1262325600">Jan 2010</option></optgroup></select>';
     //$this->template->content->endDate = '<select name="endDate" id="endDate"><optgroup label="2010"><option value="1265003999">Jan 2010</option><option value="1267423199" selected="selected" >Feb 2010</option></optgroup></select>';
     // get graph data
     // could not use DB query builder. It does not support parentheses yet
     $graph_data = array();
     $all_graphs = Incident_Model::get_incidents_by_interval('month');
     $daily_graphs = Incident_Model::get_incidents_by_interval('day');
     $weekly_graphs = Incident_Model::get_incidents_by_interval('week');
     $hourly_graphs = Incident_Model::get_incidents_by_interval('hour');
     $this->template->content->all_graphs = $all_graphs;
     $this->template->content->daily_graphs = $daily_graphs;
     // If we are looking at the standard street map set by user
     if (!isset($_GET['3dmap'])) {
         //echo 'STREET MAP';
         // Javascript Header
         $this->template->header->map_enabled = 'streetmap';
         $this->template->content->map_enabled = 'streetmap';
         $this->template->content->map_container = 'map';
         $this->template->header->main_page = TRUE;
         $this->template->header->validator_enabled = TRUE;
         // Map Settings
         $clustering = Kohana::config('settings.allow_clustering');
         $marker_radius = Kohana::config('map.marker_radius');
         $marker_opacity = Kohana::config('map.marker_opacity');
         $marker_stroke_width = Kohana::config('map.marker_stroke_width');
         $marker_stroke_opacity = Kohana::config('map.marker_stroke_opacity');
         $this->template->header->js = $clustering ? new View('main_cluster_js') : new View('main_js');
         $this->template->header->js->cluster = $clustering == 1 ? "true" : "false";
         $this->template->header->js->marker_radius = $marker_radius >= 1 && $marker_radius <= 10 ? $marker_radius : 5;
         $this->template->header->js->marker_opacity = $marker_opacity >= 1 && $marker_opacity <= 10 ? $marker_opacity * 0.1 : 0.9;
         $this->template->header->js->marker_stroke_width = $marker_stroke_width >= 1 && $marker_stroke_width <= 5 ? $marker_stroke_width : 2;
         $this->template->header->js->marker_stroke_opacity = $marker_stroke_opacity >= 1 && $marker_stroke_opacity <= 10 ? $marker_stroke_opacity * 0.1 : 0.9;
         $this->template->header->js->default_map = Kohana::config('settings.default_map');
         $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
         $this->template->header->js->latitude = Kohana::config('settings.default_lat');
         $this->template->header->js->longitude = Kohana::config('settings.default_lon');
         $this->template->header->js->graph_data = $graph_data;
         $this->template->header->js->all_graphs = $all_graphs;
         $this->template->header->js->daily_graphs = $daily_graphs;
         $this->template->header->js->hourly_graphs = $hourly_graphs;
         $this->template->header->js->weekly_graphs = $weekly_graphs;
         $this->template->header->js->default_map_all = Kohana::config('settings.default_map_all');
         //
         $this->template->header->js->active_startDate = $active_startDate;
         $this->template->header->js->active_endDate = $active_endDate;
         // If we are viewing the 3D map
     } else {
         //echo '3D MAP';
         // Javascript Header
         $this->template->header->map_enabled = '3dmap';
         $this->template->content->map_enabled = '3dmap';
         $this->template->content->map_container = 'map3d';
         $this->template->header->main_page = FALSE;
         // Setting to false because we don't want all the external controls that the street map has
         $this->template->header->js = new View('main_3d_js');
         $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
         $this->template->header->js->latitude = Kohana::config('settings.default_lat');
         $this->template->header->js->longitude = Kohana::config('settings.default_lon');
         // Override API URL
         $this->template->header->api_url = '<script src="http://www.google.com/jsapi?key=' . Kohana::config('settings.api_google') . '"> </script>';
     }
     $footerjs = new View('footer_form_js');
     // Pack the javascript using the javascriptpacker helper
     $this->template->header->js .= $footerjs;
     $myPacker = new javascriptpacker($this->template->header->js, 'Normal', true, false);
     $this->template->header->js = $myPacker->pack();
 }
Example #21
0
	public function submit($saved = false)
	{
		// Cacheable Controller
		$this->is_cachable = FALSE;

		$this->template->header->show_map = TRUE;
		$this->template->content  = new View('keitai/reports_submit');

		// First, are we allowed to submit new reports?
		if ( ! Kohana::config('settings.allow_reports'))
		{
			url::redirect(url::site().'main');
		}

		// setup and initialize form field names
		$form = array
		(
			'incident_title' => '',
			'incident_description' => '',
			'incident_month' => '',
			'incident_day' => '',
			'incident_year' => '',
			'incident_hour' => '',
			'incident_minute' => '',
			'incident_ampm' => '',
			'latitude' => '',
			'longitude' => '',
			'location_name' => '',
			'country_id' => '',
			'incident_category' => 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;

		if ($saved == 'saved')
		{
			$form_saved = TRUE;
		}
		else
		{
			$form_saved = FALSE;
		}


		// Initialize Default Values
		$form['incident_month'] = date('m');
		$form['incident_day'] = date('d');
		$form['incident_year'] = date('Y');
		$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);
		//GET custom forms
		//$forms = array();
		//foreach (ORM::factory('form')->find_all() 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 = 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('incident_title', 'required', 'length[3,200]');
			$post->add_rules('incident_description', 'required');
			$post->add_rules('incident_month', 'required', 'numeric', 'between[1,12]');
			$post->add_rules('incident_day', 'required', 'numeric', 'between[1,31]');
			$post->add_rules('incident_year', 'required', 'numeric', 'length[4,4]');

			if ( ! checkdate($_POST['incident_month'], $_POST['incident_day'], $_POST['incident_year']) )
			{
				$post->add_error('incident_date','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');
			}

			// Validate for maximum and minimum latitude values
			$post->add_rules('latitude', 'between[-90,90]');
			$post->add_rules('longitude', 'between[-180,180]');
			//$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');
			}

			// Geocode Location
			if ( empty($_POST['latitude']) AND empty($_POST['longitude'])
				AND ! empty($_POST['location_name']) )
			{
				$default_country = Kohana::config('settings.default_country');
				$country_name = "";
				if ($default_country)
				{
					$country = ORM::factory('country', $default_country);
					if ($country->loaded)
					{
						$country_name = $country->country;
					}
				}

				$geocode = keitai_geocoder::geocode($_POST['location_name'].", ".$country_name);
				if ($geocode)
				{
					$post->latitude = $geocode['lat'];
					$post->longitude = $geocode['lon'];
				}
				else
				{
					$post->add_error('location_name', 'geocode');
				}
			}

			// Test to see if things passed the rule checks
			if ($post->validate())
			{
				if ($post->latitude AND $post->longitude)
				{
					// STEP 1: SAVE LOCATION
					$location = new Location_Model();
					$location->location_name = $post->location_name;
					$location->latitude = $post->latitude;
					$location->longitude = $post->longitude;
					$location->location_date = date("Y-m-d H:i:s",time());
					$location->save();
				}

				// STEP 2: SAVE INCIDENT
				$incident = new Incident_Model();
				if (isset($location) AND $location->loaded)
				{
					$incident->location_id = $location->id;
				}
				$incident->user_id = 0;
				$incident->incident_title = $post->incident_title;
				$incident->incident_description = $post->incident_description;

				$incident_date = $post->incident_year."-".$post->incident_month."-".$post->incident_day;
				$incident_time = $post->incident_hour
					.":".$post->incident_minute
					.":00 ".$post->incident_ampm;
				$incident->incident_date = date( "Y-m-d H:i:s", strtotime($incident_date . " " . $incident_time) );
				$incident->incident_dateadd = date("Y-m-d H:i:s",time());
				$incident->save();

				// STEP 3: SAVE CATEGORIES
				foreach($post->incident_category as $item)
				{
					$incident_category = new Incident_Category_Model();
					$incident_category->incident_id = $incident->id;
					$incident_category->category_id = $item;
					$incident_category->save();
				}

				url::redirect('keitai/reports/thanks');

			}
			// No! We have validation errors, we need to show the form again, with the errors
			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 {
			$form['latitude'] = (isset($_GET['latitude'])) ? $_GET['latitude'] : "";
			$form['longitude'] = (isset($_GET['longitude'])) ? $_GET['longitude'] : "";
		}

		$this->template->content->form = $form;
		$this->template->content->errors = $errors;
		$this->template->content->form_error = $form_error;
		$this->template->content->categories = $this->_get_categories($form['incident_category']);

		$this->template->content->cities = $this->_get_cities();

		$this->template->header->js = new View('keitai/reports_submit_js');
		if (!$form['latitude'] || !$form['latitude'])
		{
			$this->template->header->js->latitude = Kohana::config('settings.default_lat');
			$this->template->header->js->longitude = Kohana::config('settings.default_lon');
		}else{
			$this->template->header->js->latitude = $form['latitude'];
			$this->template->header->js->longitude = $form['longitude'];
		}
		$this->template->content->device = $this->checkdevice($_SERVER['HTTP_USER_AGENT']);

	}
Example #22
0
 /**
  * Submits a new report.
  */
 public function submit()
 {
     $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' => '', 'location_name' => '', 'country_id' => '', 'incident_category' => array(), 'incident_news' => array(), 'incident_video' => array(), 'incident_photo' => array(), 'person_first' => '', 'person_last' => '', 'person_email' => '');
     //copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     // Initialize Default Values
     $form['incident_date'] = date("m/d/Y", time());
     $form['incident_hour'] = "12";
     $form['incident_minute'] = "00";
     $form['incident_ampm'] = "pm";
     // 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('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');
         }
         // Validate for maximum and minimum latitude values
         $post->add_rules('latitude', 'required', 'between[-90,90]');
         $post->add_rules('longitude', 'required', 'between[-180,180]');
         $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]');
         }
         // Test to see if things passed the rule checks
         if ($post->validate()) {
             // STEP 1: SAVE LOCATION
             $location = new Location_Model();
             $location->location_name = $post->location_name;
             $location->latitude = $post->latitude;
             $location->longitude = $post->longitude;
             $location->location_date = date("Y-m-d H:i:s", time());
             $location->save();
             // STEP 2: SAVE INCIDENT
             $incident = new Incident_Model();
             $incident->location_id = $location->id;
             $incident->user_id = 0;
             $incident->incident_title = $post->incident_title;
             $incident->incident_description = $post->incident_description;
             $incident_date = explode("/", $post->incident_date);
             // The $_POST['date'] is a value posted by form in mm/dd/yyyy format
             $incident_date = $incident_date[2] . "-" . $incident_date[0] . "-" . $incident_date[1];
             $incident_time = $post->incident_hour . ":" . $post->incident_minute . ":00 " . $post->incident_ampm;
             $incident->incident_date = $incident_date . " " . $incident_time;
             $incident->incident_dateadd = date("Y-m-d H:i:s", time());
             $incident->save();
             // STEP 3: SAVE CATEGORIES
             foreach ($post->incident_category as $item) {
                 $incident_category = new Incident_Category_Model();
                 $incident_category->incident_id = $incident->id;
                 $incident_category->category_id = $item;
                 $incident_category->save();
             }
             // STEP 4: SAVE MEDIA
             // a. News
             foreach ($post->incident_news as $item) {
                 if (!empty($item)) {
                     $news = new Media_Model();
                     $news->location_id = $location->id;
                     $news->incident_id = $incident->id;
                     $news->media_type = 4;
                     // News
                     $news->media_link = $item;
                     $news->media_date = date("Y-m-d H:i:s", time());
                     $news->save();
                 }
             }
             // b. Video
             foreach ($post->incident_video as $item) {
                 if (!empty($item)) {
                     $video = new Media_Model();
                     $video->location_id = $location->id;
                     $video->incident_id = $incident->id;
                     $video->media_type = 2;
                     // Video
                     $video->media_link = $item;
                     $video->media_date = date("Y-m-d H:i:s", time());
                     $video->save();
                 }
             }
             // c. Photos
             $filenames = upload::save('incident_photo');
             $i = 1;
             foreach ($filenames as $filename) {
                 $new_filename = $incident->id . "_" . $i . "_" . time();
                 // Resize original file... make sure its max 408px wide
                 Image::factory($filename)->resize(408, 248, Image::AUTO)->save(Kohana::config('upload.directory', TRUE) . $new_filename . ".jpg");
                 // Create thumbnail
                 Image::factory($filename)->resize(70, 41, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_t.jpg");
                 // Remove the temporary file
                 unlink($filename);
                 // Save to DB
                 $photo = new Media_Model();
                 $photo->location_id = $location->id;
                 $photo->incident_id = $incident->id;
                 $photo->media_type = 1;
                 // Images
                 $photo->media_link = $new_filename . ".jpg";
                 $photo->media_thumb = $new_filename . "_t.jpg";
                 $photo->media_date = date("Y-m-d H:i:s", time());
                 $photo->save();
                 $i++;
             }
             // STEP 5: SAVE PERSONAL INFORMATION
             $person = new Incident_Person_Model();
             $person->location_id = $location->id;
             $person->incident_id = $incident->id;
             $person->person_first = $post->person_first;
             $person->person_last = $post->person_last;
             $person->person_email = $post->person_email;
             $person->person_date = date("Y-m-d H:i:s", time());
             $person->save();
             // Notify Admin Of New Report
             $send = notifications::notify_admins("[" . Kohana::config('settings.site_name') . "] " . Kohana::lang('notifications.admin_new_report.subject'), Kohana::lang('notifications.admin_new_report.message') . "\n\n'" . strtoupper($incident->incident_title) . "'" . "\n" . $incident->incident_description);
             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->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->categories = $this->_get_categories($form['incident_category']);
     // Javascript Header
     $this->template->header->map_enabled = TRUE;
     $this->template->header->datepicker_enabled = TRUE;
     $this->template->header->js = new View('reports_submit_js');
     $this->template->header->js->default_map = Kohana::config('settings.default_map');
     $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
     if (!$form['latitude'] || !$form['latitude']) {
         $this->template->header->js->latitude = Kohana::config('settings.default_lat');
         $this->template->header->js->longitude = Kohana::config('settings.default_lon');
     } else {
         $this->template->header->js->latitude = $form['latitude'];
         $this->template->header->js->longitude = $form['longitude'];
     }
 }
Example #23
0
 private function _search_form()
 {
     $search_form = View::factory('admin/reports/search_form');
     // Handling location filter
     $location_filter = isset($_GET['location_filter']);
     if (!$location_filter) {
         if (isset($_GET['start_loc'])) {
             unset($_GET['start_loc']);
         }
         if (isset($_GET['alert_radius'])) {
             unset($_GET['alert_radius']);
         }
     } else {
         $_GET['radius'] = $_GET['alert_radius'];
     }
     $search_form->location_filter = $location_filter;
     $search_form->start_loc = isset($_GET['start_loc']) ? $_GET['start_loc'] : array(0, 0);
     // Get the date of the oldest report
     if (!empty($_GET['from'])) {
         $date_from = strtotime($_GET['from']);
     } else {
         $date_from = Incident_Model::get_oldest_report_timestamp();
     }
     // Get the date of the latest report
     if (!empty($_GET['to'])) {
         $date_to = strtotime($_GET['to']);
     } else {
         $date_to = Incident_Model::get_latest_report_timestamp();
     }
     $search_form->date_from = $date_from;
     $search_form->date_to = $date_to;
     // Categories
     if (!isset($_GET['c']) or !is_array($_GET['c'])) {
         $_GET['c'] = isset($_GET['c']) ? array($_GET['c']) : array();
     }
     $search_form->categories = $_GET['c'];
     // Media
     if (!isset($_GET['m']) or !is_array($_GET['m'])) {
         $_GET['m'] = isset($_GET['m']) ? array($_GET['m']) : array();
     }
     $search_form->media = $_GET['m'];
     // Mode
     if (!isset($_GET['mode']) or !is_array($_GET['mode'])) {
         $_GET['mode'] = isset($_GET['mode']) ? array($_GET['mode']) : array();
     }
     $search_form->mode = $_GET['mode'];
     // Approved
     $search_form->approved = $_GET['a'] = isset($_GET['a']) ? $_GET['a'] : 'all';
     if ($_GET['a'] == 'all') {
         unset($_GET['a']);
     }
     // Verified
     $search_form->verified = $_GET['v'] = isset($_GET['v']) ? $_GET['v'] : 'all';
     if ($_GET['v'] == 'all') {
         unset($_GET['v']);
     }
     // Load the alert radius view
     $alert_radius_view = new View('alerts/radius');
     $alert_radius_view->show_usage_info = FALSE;
     $alert_radius_view->enable_find_location = TRUE;
     $alert_radius_view->css_class = "map_holder_reports";
     $search_form->alert_radius_view = $alert_radius_view;
     return $search_form;
 }
 public function timeline()
 {
     $this->auto_render = FALSE;
     $this->template = new View('json/timeline');
     //$this->template->content = new View('json/timeline');
     $interval = 'day';
     $start_date = NULL;
     $end_date = NULL;
     $active = 'true';
     if (isset($_GET['i'])) {
         $interval = $_GET['i'];
     }
     if (isset($_GET['s'])) {
         $start_date = $_GET['s'];
     }
     if (isset($_GET['e'])) {
         $end_date = $_GET['e'];
     }
     if (isset($_GET['active'])) {
         $active = $_GET['active'];
     }
     // get graph data
     $graph_data = array();
     $all_graphs = Incident_Model::get_incidents_by_interval($interval, $start_date, $end_date, $active);
     echo $all_graphs;
 }
Example #25
0
 public function index()
 {
     $this->template->header->this_page = 'home';
     $this->template->content = new View('main');
     // Get all active categories
     $categories = array();
     foreach (ORM::factory('category')->where('category_visible', '1')->find_all() as $category) {
         // Create a list of all categories
         $categories[$category->id] = array($category->category_title, $category->category_color);
     }
     $this->template->content->categories = $categories;
     // Get Reports
     // XXX: Might need to replace magic no. 8 with a constant
     $this->template->content->total_items = ORM::factory('incident')->where('incident_active', '1')->limit('8')->count_all();
     $this->template->content->incidents = ORM::factory('incident')->where('incident_active', '1')->limit('10')->orderby('incident_dateadd', 'desc')->find_all();
     // Get SMS Numbers
     $phone_array = array();
     $sms_no1 = Kohana::config('settings.sms_no1');
     $sms_no2 = Kohana::config('settings.sms_no2');
     $sms_no3 = Kohana::config('settings.sms_no3');
     if (!empty($sms_no1)) {
         $phone_array[] = $sms_no1;
     }
     if (!empty($sms_no2)) {
         $phone_array[] = $sms_no2;
     }
     if (!empty($sms_no3)) {
         $phone_array[] = $sms_no3;
     }
     $this->template->content->phone_array = $phone_array;
     // Get RSS News Feeds
     $this->template->content->feeds = ORM::factory('feed_item')->limit('10')->orderby('item_date', 'desc')->find_all();
     // Get Slider Dates By Year
     $startDate = "";
     $endDate = "";
     // We need to use the DB builder for a custom query
     $db = new Database();
     $query = $db->query('SELECT DATE_FORMAT(incident_dateadd, \'%Y\') AS incident_dateadd FROM incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_dateadd, \'%Y\') ORDER BY incident_dateadd');
     foreach ($query as $slider_date) {
         $startDate .= "<optgroup label=\"" . $slider_date->incident_dateadd . "\">";
         for ($i = 1; $i <= 12; $i++) {
             if ($i < 10) {
                 $i = "0" . $i;
             }
             $startDate .= "<option value=\"" . strtotime($slider_date->incident_dateadd . "-" . $i . "-01") . "\">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $slider_date->incident_dateadd . "</option>";
         }
         $startDate .= "</optgroup>";
         $endDate .= "<optgroup label=\"" . $slider_date->incident_dateadd . "\">";
         for ($i = 1; $i <= 12; $i++) {
             if ($i < 10) {
                 $i = "0" . $i;
             }
             $endDate .= "<option value=\"" . strtotime($slider_date->incident_dateadd . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1))) . "\"";
             if ($i == 12) {
                 $endDate .= " selected=\"selected\" ";
             }
             $endDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $slider_date->incident_dateadd . "</option>";
         }
         $endDate .= "</optgroup>";
     }
     $this->template->content->startDate = $startDate;
     $this->template->content->endDate = $endDate;
     // get graph data
     // could not use DB query builder. It does not support parentheses yet
     $graph_data = array();
     $all_graphs = Incident_Model::get_incidents_by_interval('month');
     $this->template->content->all_graphs = $all_graphs;
     // Javascript Header
     $this->template->header->map_enabled = TRUE;
     $this->template->header->main_page = TRUE;
     // Cluster Reports on Map?
     $clustering = Kohana::config('settings.allow_clustering');
     if ($clustering == 1) {
         $this->template->header->js = new View('main_cluster_js');
     } else {
         $this->template->header->js = new View('main_js');
     }
     $this->template->header->js->default_map = Kohana::config('settings.default_map');
     $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
     $this->template->header->js->latitude = Kohana::config('settings.default_lat');
     $this->template->header->js->longitude = Kohana::config('settings.default_lon');
     $this->template->header->js->graph_data = $graph_data;
     $this->template->header->js->all_graphs = $all_graphs;
     $this->template->header->js->categories = $categories;
     // Pack the javascript using the javascriptpacker helper
     $myPacker = new javascriptpacker($this->template->header->js, 'Normal', false, false);
     $this->template->header->js = $myPacker->pack();
 }
Example #26
0
 /**
  * Displays a report.
  * @param boolean $id If id is supplied, a report with that id will be
  * retrieved.
  */
 public function view($id = FALSE)
 {
     $this->template->header->this_page = 'reports';
     $this->template->content = new View('reports_view');
     // Load Akismet API Key (Spam Blocker)
     $api_akismet = Kohana::config('settings.api_akismet');
     if (!Incident_Model::is_valid_incident($id, TRUE)) {
         url::redirect('main');
     } else {
         $incident = ORM::factory('incident')->where('id', $id)->where('incident_active', 1)->find();
         if ($incident->id == 0) {
             url::redirect('reports/view/');
         }
         // Comment Post?
         // Setup and initialize form field names
         $form = array('comment_author' => '', 'comment_description' => '', 'comment_email' => '', 'comment_ip' => '', 'captcha' => '');
         $captcha = Captcha::factory();
         $errors = $form;
         $form_error = FALSE;
         // Check, has the form been submitted, if so, setup validation
         if ($_POST and Kohana::config('settings.allow_comments')) {
             // Instantiate Validation, use $post, so we don't overwrite $_POST fields with our own things
             $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
             if (!$this->user) {
                 $post->add_rules('comment_author', 'required', 'length[3,100]');
                 $post->add_rules('comment_email', 'required', 'email', 'length[4,100]');
             }
             $post->add_rules('comment_description', 'required');
             $post->add_rules('captcha', 'required', 'Captcha::valid');
             // Test to see if things passed the rule checks
             if ($post->validate()) {
                 // Yes! everything is valid
                 if ($api_akismet != "") {
                     // Run Akismet Spam Checker
                     $akismet = new Akismet();
                     // Comment data
                     $comment = array('website' => "", 'body' => $post->comment_description, 'user_ip' => $_SERVER['REMOTE_ADDR']);
                     if ($this->user) {
                         $comment['author'] = $this->user->name;
                         $comment['email'] = $this->user->email;
                     } else {
                         $comment['author'] = $post->comment_author;
                         $comment['email'] = $post->comment_email;
                     }
                     $config = array('blog_url' => url::site(), 'api_key' => $api_akismet, 'comment' => $comment);
                     $akismet->init($config);
                     if ($akismet->errors_exist()) {
                         if ($akismet->is_error('AKISMET_INVALID_KEY')) {
                             // throw new Kohana_Exception('akismet.api_key');
                         } elseif ($akismet->is_error('AKISMET_RESPONSE_FAILED')) {
                             // throw new Kohana_Exception('akismet.server_failed');
                         } elseif ($akismet->is_error('AKISMET_SERVER_NOT_FOUND')) {
                             // throw new Kohana_Exception('akismet.server_not_found');
                         }
                         // If the server is down, we have to post
                         // the comment :(
                         // $this->_post_comment($comment);
                         $comment_spam = 0;
                     } else {
                         $comment_spam = $akismet->is_spam() ? 1 : 0;
                     }
                 } else {
                     // No API Key!!
                     $comment_spam = 0;
                 }
                 $comment = new Comment_Model();
                 $comment->incident_id = $id;
                 if ($this->user) {
                     $comment->user_id = $this->user->id;
                     $comment->comment_author = $this->user->name;
                     $comment->comment_email = $this->user->email;
                 } else {
                     $comment->comment_author = strip_tags($post->comment_author);
                     $comment->comment_email = strip_tags($post->comment_email);
                 }
                 $comment->comment_description = strip_tags($post->comment_description);
                 $comment->comment_ip = $_SERVER['REMOTE_ADDR'];
                 $comment->comment_date = date("Y-m-d H:i:s", time());
                 // Activate comment for now
                 if ($comment_spam == 1) {
                     $comment->comment_spam = 1;
                     $comment->comment_active = 0;
                 } else {
                     $comment->comment_spam = 0;
                     $comment->comment_active = Kohana::config('settings.allow_comments') == 1 ? 1 : 0;
                 }
                 $comment->save();
                 // Event::comment_add - Added a New Comment
                 Event::run('ushahidi_action.comment_add', $comment);
                 // Notify Admin Of New Comment
                 $send = notifications::notify_admins("[" . Kohana::config('settings.site_name') . "] " . Kohana::lang('notifications.admin_new_comment.subject'), Kohana::lang('notifications.admin_new_comment.message') . "\n\n'" . strtoupper($incident->incident_title) . "'" . "\n" . url::base() . 'reports/view/' . $id);
                 // Redirect
                 url::redirect('reports/view/' . $id);
             } else {
                 // No! We have validation errors, we need to show the form again, with the errors
                 // Repopulate the form fields
                 $form = arr::overwrite($form, $post->as_array());
                 // Populate the error fields, if any
                 $errors = arr::overwrite($errors, $post->errors('comments'));
                 $form_error = TRUE;
             }
         }
         // Filters
         $incident_title = $incident->incident_title;
         $incident_description = nl2br($incident->incident_description);
         Event::run('ushahidi_filter.report_title', $incident_title);
         Event::run('ushahidi_filter.report_description', $incident_description);
         // Add Features
         $this->template->content->features_count = $incident->geometry->count();
         $this->template->content->features = $incident->geometry;
         $this->template->content->incident_id = $incident->id;
         $this->template->content->incident_title = $incident_title;
         $this->template->content->incident_description = $incident_description;
         $this->template->content->incident_location = $incident->location->location_name;
         $this->template->content->incident_latitude = $incident->location->latitude;
         $this->template->content->incident_longitude = $incident->location->longitude;
         $this->template->content->incident_date = date('M j Y', strtotime($incident->incident_date));
         $this->template->content->incident_time = date('H:i', strtotime($incident->incident_date));
         $this->template->content->incident_category = $incident->incident_category;
         // Incident rating
         $this->template->content->incident_rating = $incident->incident_rating == '' ? 0 : $incident->incident_rating;
         // 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;
             }
         }
         $this->template->content->incident_verified = $incident->incident_verified;
         // Retrieve Comments (Additional Information)
         $this->template->content->comments = "";
         if (Kohana::config('settings.allow_comments')) {
             $this->template->content->comments = new View('reports_comments');
             $incident_comments = array();
             if ($id) {
                 $incident_comments = Incident_Model::get_comments($id);
             }
             $this->template->content->comments->incident_comments = $incident_comments;
         }
     }
     // Add Neighbors
     $this->template->content->incident_neighbors = Incident_Model::get_neighbouring_incidents($id, TRUE, 0, 5);
     // News Source links
     $this->template->content->incident_news = $incident_news;
     // Video links
     $this->template->content->incident_videos = $incident_video;
     // Images
     $this->template->content->incident_photos = $incident_photo;
     // Create object of the video embed class
     $video_embed = new VideoEmbed();
     $this->template->content->videos_embed = $video_embed;
     // Javascript Header
     $this->themes->map_enabled = TRUE;
     $this->themes->photoslider_enabled = TRUE;
     $this->themes->videoslider_enabled = TRUE;
     $this->themes->js = new View('reports_view_js');
     $this->themes->js->incident_id = $incident->id;
     $this->themes->js->default_map = Kohana::config('settings.default_map');
     $this->themes->js->default_zoom = Kohana::config('settings.default_zoom');
     $this->themes->js->latitude = $incident->location->latitude;
     $this->themes->js->longitude = $incident->location->longitude;
     $this->themes->js->incident_zoom = $incident->incident_zoom;
     $this->themes->js->incident_photos = $incident_photo;
     // Initialize custom field array
     $this->template->content->custom_forms = new View('reports_view_custom_forms');
     $form_field_names = customforms::get_custom_form_fields($id, $incident->form_id, FALSE, "view");
     $this->template->content->custom_forms->form_field_names = $form_field_names;
     // Are we allowed to submit comments?
     $this->template->content->comments_form = "";
     if (Kohana::config('settings.allow_comments')) {
         $this->template->content->comments_form = new View('reports_comments_form');
         $this->template->content->comments_form->user = $this->user;
         $this->template->content->comments_form->form = $form;
         $this->template->content->comments_form->form_field_names = $form_field_names;
         $this->template->content->comments_form->captcha = $captcha;
         $this->template->content->comments_form->errors = $errors;
         $this->template->content->comments_form->form_error = $form_error;
     }
     // If the Admin is Logged in - Allow for an edit link
     $this->template->content->logged_in = $this->logged_in;
     // Rebuild Header Block
     $this->template->header->header_block = $this->themes->header_block();
 }
Example #27
0
	/**
	 * Submits a new report.
	 */
	public function submit($id = false, $saved = false)
	{
		// 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' => '',
			'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;

		if ($saved == 'saved')
		{
			$form_saved = TRUE;
		}
		else
		{
			$form_saved = FALSE;
		}


		// 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'] = $this->_get_custom_form_fields($id,'',true);
		//GET custom forms
		$forms = array();
		foreach (ORM::factory('form')->find_all() 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 = 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('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" AND $_POST['incident_ampm'] != "pm")
			{
				$post->add_error('incident_ampm','values');
			}

			// Validate for maximum and minimum latitude values
			$post->add_rules('latitude', 'required', 'between[-90,90]');
			$post->add_rules('longitude', 'required', 'between[-180,180]');
			$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]');
			}

			// Test to see if things passed the rule checks
			if ($post->validate())
			{
				// STEP 1: SAVE LOCATION
				$location = new Location_Model();
				$location->location_name = $post->location_name;
				$location->latitude = $post->latitude;
				$location->longitude = $post->longitude;
				$location->location_date = date("Y-m-d H:i:s",time());
				$location->save();

				// STEP 2: SAVE INCIDENT
				$incident = new Incident_Model();
				$incident->location_id = $location->id;
				$incident->form_id = $post->form_id;
				$incident->user_id = 0;
				$incident->incident_title = $post->incident_title;
				$incident->incident_description = $post->incident_description;

				$incident_date=explode("/",$post->incident_date);

				// The $_POST['date'] is a value posted by form in mm/dd/yyyy format
				$incident_date=$incident_date[2]."-".$incident_date[0]."-".$incident_date[1];
				$incident_time = $post->incident_hour
					.":".$post->incident_minute
					.":00 ".$post->incident_ampm;
				$incident->incident_date = date( "Y-m-d H:i:s", strtotime($incident_date . " " . $incident_time) );
				$incident->incident_dateadd = date("Y-m-d H:i:s",time());
				$incident->save();

				// STEP 3: SAVE CATEGORIES
				foreach($post->incident_category as $item)
				{
					$incident_category = new Incident_Category_Model();
					$incident_category->incident_id = $incident->id;
					$incident_category->category_id = $item;
					$incident_category->save();
				}

				// STEP 4: SAVE MEDIA
				// a. News
				foreach($post->incident_news as $item)
				{
					if (!empty($item))
					{
						$news = new Media_Model();
						$news->location_id = $location->id;
						$news->incident_id = $incident->id;
						$news->media_type = 4;		// News
						$news->media_link = $item;
						$news->media_date = date("Y-m-d H:i:s",time());
						$news->save();
					}
				}

				// b. Video
				foreach($post->incident_video as $item)
				{
					if (!empty($item))
					{
						$video = new Media_Model();
						$video->location_id = $location->id;
						$video->incident_id = $incident->id;
						$video->media_type = 2;		// Video
						$video->media_link = $item;
						$video->media_date = date("Y-m-d H:i:s",time());
						$video->save();
					}
				}

				// c. Photos
				$filenames = upload::save('incident_photo');
				$i = 1;

				foreach ($filenames as $filename)
				{
					$new_filename = $incident->id."_".$i."_".time();
					
					$file_type = strrev(substr(strrev($filename),0,4));
					
					// IMAGE SIZES: 800X600, 400X300, 89X59
					
					// Large size
					Image::factory($filename)->resize(800,600,Image::AUTO)
						->save(Kohana::config('upload.directory', TRUE).$new_filename.$file_type);

					// Medium size
					Image::factory($filename)->resize(400,300,Image::HEIGHT)
						->save(Kohana::config('upload.directory', TRUE).$new_filename."_m".$file_type);
					
					// Thumbnail
					Image::factory($filename)->resize(89,59,Image::HEIGHT)
						->save(Kohana::config('upload.directory', TRUE).$new_filename."_t".$file_type);	

					// Remove the temporary file
					unlink($filename);

					// Save to DB
					$photo = new Media_Model();
					$photo->location_id = $location->id;
					$photo->incident_id = $incident->id;
					$photo->media_type = 1; // Images
					$photo->media_link = $new_filename.$file_type;
					$photo->media_medium = $new_filename."_m".$file_type;
					$photo->media_thumb = $new_filename."_t".$file_type;
					$photo->media_date = date("Y-m-d H:i:s",time());
					$photo->save();
					$i++;
				}

				// STEP 7: SAVE CUSTOM FORM FIELDS
				if (isset($post->custom_field))
				{
					foreach($post->custom_field as $key => $value)
					{
						$form_response = ORM::factory('form_response')
						->where('form_field_id', $key)
						->where('incident_id', $incident->id)
						->find();
						if ($form_response->loaded == true)
						{
							$form_response->form_field_id = $key;
							$form_response->form_response = $value;
							$form_response->save();
						}
						else
						{
							$form_response = new Form_Response_Model();
							$form_response->form_field_id = $key;
							$form_response->incident_id = $incident->id;
							$form_response->form_response = $value;
							$form_response->save();
						}
					}
				}

				// STEP 5: SAVE PERSONAL INFORMATION
				$person = new Incident_Person_Model();
				$person->location_id = $location->id;
				$person->incident_id = $incident->id;
				$person->person_first = $post->person_first;
				$person->person_last = $post->person_last;
				$person->person_email = $post->person_email;
				$person->person_date = date("Y-m-d H:i:s",time());
				$person->save();

				// Action::report_add - Added a New Report
				Event::run('ushahidi_action.report_add', $incident);

				url::redirect('reports/thanks');
			}

			// No! We have validation errors, we need to show the form again, with the errors
			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');

		// 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;

		// Javascript Header
		$this->themes->map_enabled = TRUE;
		$this->themes->datepicker_enabled = TRUE;
		$this->themes->treeview_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'];
		}

		// Rebuild Header Block
		$this->template->header->header_block = $this->themes->header_block();
	}
Example #28
0
 /**
  * Retrieve Single Marker (and its neighbours)
  * 
  * @param int $incident_id
  */
 public function single($incident_id = 0)
 {
     $json_features = array();
     $incident_id = intval($incident_id);
     // Check if incident valid/approved
     if (!Incident_Model::is_valid_incident($incident_id, TRUE)) {
         throw new Kohana_404_Exception();
     }
     // Load the incident
     // @todo avoid the double load here
     $marker = ORM::factory('incident')->where('incident.incident_active', 1)->with('location')->find($incident_id);
     if (!$marker->loaded) {
         throw new Kohana_404_Exception();
     }
     // Get geojson features for main incident (including geometry)
     $json_features = $this->markers_geojson(array($marker), 0, null, null, TRUE);
     // Get the neigbouring incidents & their json (without geometries)
     $neighbours = Incident_Model::get_neighbouring_incidents($incident_id, FALSE, 20, 100);
     if ($neighbours) {
         $json_features = array_merge($json_features, $this->markers_geojson($neighbours, 0, null, null, FALSE));
     }
     Event::run('ushahidi_filter.json_single_features', $json_features);
     $this->render_geojson($json_features);
 }
 /**
  * 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' => '', 'incident_source' => '', 'incident_information' => '');
     $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 = 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('location_id', 'numeric');
         $post->add_rules('incident_id', 'required', '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[0,23]');
         if ($this->api_service->verify_array_index($_POST, 'incident_ampm')) {
             if ($_POST['incident_ampm'] != "am" && $_POST['incident_ampm'] != "pm") {
                 $post->add_error('incident_ampm', 'values');
             }
         }
         $post->add_rules('latitude', 'required', 'between[-90,90]');
         $post->add_rules('longitude', 'required', 'between[-180,180]');
         $post->add_rules('location_name', 'required', 'length[3,200]');
         $post->add_rules('incident_category', 'required', 'length[1,100]');
         // 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]');
         }
         $post->add_rules('incident_active', 'required', 'between[0,1]');
         $post->add_rules('incident_verified', 'required', 'length[0,1]');
         $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()) {
             $incident_id = $post->incident_id;
             $location_id = $post->location_id;
             // SAVE INCIDENT
             // SAVE LOCATION (***IF IT DOES NOT EXIST***)
             $location = new Location_Model($location_id);
             $location->location_name = $post->location_name;
             $location->latitude = $post->latitude;
             $location->longitude = $post->longitude;
             $location->location_date = date("Y-m-d H:i:s", time());
             $location->save();
             $incident = new Incident_Model($incident_id);
             $incident->location_id = $location->id;
             $incident->user_id = 0;
             $incident->incident_title = $post->incident_title;
             $incident->incident_description = $post->incident_description;
             $incident_date = explode("/", $post->incident_date);
             /**
              * where the $_POST['date'] is a value posted by form in
              * mm/dd/yyyy format
              */
             $incident_date = $incident_date[2] . "-" . $incident_date[0] . "-" . $incident_date[1];
             $incident_time = $post->incident_hour . ":" . $post->incident_minute . ":00 " . $post->incident_ampm;
             $incident->incident_date = date("Y-m-d H:i:s", strtotime($incident_date . " " . $incident_time));
             $incident->incident_datemodify = date("Y-m-d H:i:s", time());
             // Incident Evaluation Info
             $incident->incident_active = $post->incident_active;
             $incident->incident_verified = $post->incident_verified;
             $incident->incident_source = $post->incident_source;
             $incident->incident_information = $post->incident_information;
             $incident->save();
             // Record Approval/Verification Action
             $verify = new Verify_Model();
             $verify->incident_id = $incident->id;
             $verify->user_id = $_SESSION['auth_user']->id;
             // Record 'Verified By' Action
             $verify->verified_date = date("Y-m-d H:i:s", time());
             if ($post->incident_active == 1) {
                 $verify->verified_status = '1';
             } elseif ($post->incident_verified == 1) {
                 $verify->verified_status = '2';
             } elseif ($post->incident_active == 1 && $post->incident_verified == 1) {
                 $verify->verified_status = '3';
             } else {
                 $verify->verified_status = '0';
             }
             $verify->save();
             // SAVE CATEGORIES
             //check if data is csv or a single value.
             $pos = strpos($post->incident_category, ",");
             if ($pos === false) {
                 //for backward compactibility. will drop support for it in the future.
                 if (@unserialize($post->incident_category)) {
                     $categories = unserialize($post->incident_category);
                 } else {
                     $categories = array($post->incident_category);
                 }
             } else {
                 $categories = explode(",", $post->incident_category);
             }
             if (!empty($categories) and is_array($categories)) {
                 // STEP 3: SAVE CATEGORIES
                 ORM::factory('Incident_Category')->where('incident_id', $incident->id)->delete_all();
                 // Delete Previous Entries
                 foreach ($categories as $item) {
                     $incident_category = new Incident_Category_Model();
                     $incident_category->incident_id = $incident->id;
                     $incident_category->category_id = $item;
                     $incident_category->save();
                 }
             }
             // STEP 4: SAVE MEDIA
             // a. News
             if (!empty($post->incident_news) && is_array($post->incident_news)) {
                 ORM::factory('Media')->where('incident_id', $incident->id)->where('media_type <> 1')->delete_all();
                 // Delete Previous Entries
                 foreach ($post->incident_news as $item) {
                     if (!empty($item)) {
                         $news = new Media_Model();
                         $news->location_id = $location->id;
                         $news->incident_id = $incident->id;
                         $news->media_type = 4;
                         // News
                         $news->media_link = $item;
                         $news->media_date = date("Y-m-d H:i:s", time());
                         $news->save();
                     }
                 }
             }
             // b. Video
             if (!empty($post->incident_video) && is_array($post->incident_video)) {
                 foreach ($post->incident_video as $item) {
                     if (!empty($item)) {
                         $video = new Media_Model();
                         $video->location_id = $location->id;
                         $video->incident_id = $incident->id;
                         $video->media_type = 2;
                         // Video
                         $video->media_link = $item;
                         $video->media_date = date("Y-m-d H:i:s", time());
                         $video->save();
                     }
                 }
             }
             // c. Photos
             if (!empty($post->incident_photo)) {
                 $filenames = upload::save('incident_photo');
                 $i = 1;
                 foreach ($filenames as $filename) {
                     $new_filename = $incident->id . "_" . $i . "_" . time();
                     // Resize original file... make sure its max 408px wide
                     Image::factory($filename)->resize(408, 248, Image::AUTO)->save(Kohana::config('upload.directory', TRUE) . $new_filename . ".jpg");
                     // Create thumbnail
                     Image::factory($filename)->resize(70, 41, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_t.jpg");
                     // Remove the temporary file
                     unlink($filename);
                     // Save to DB
                     $photo = new Media_Model();
                     $photo->location_id = $location->id;
                     $photo->incident_id = $incident->id;
                     $photo->media_type = 1;
                     // Images
                     $photo->media_link = $new_filename . ".jpg";
                     $photo->media_thumb = $new_filename . "_t.jpg";
                     $photo->media_date = date("Y-m-d H:i:s", time());
                     $photo->save();
                     $i++;
                 }
             }
             // SAVE PERSONAL INFORMATION IF ITS FILLED UP
             if (!empty($post->person_first) or !empty($post->person_last)) {
                 ORM::factory('Incident_Person')->where('incident_id', $incident->id)->delete_all();
                 $person = new Incident_Person_Model();
                 $person->location_id = $location->id;
                 $person->incident_id = $incident->id;
                 $person->person_first = $post->person_first;
                 $person->person_last = $post->person_last;
                 $person->person_email = $post->person_email;
                 $person->person_date = date("Y-m-d H:i:s", time());
                 $person->save();
             }
             return $this->response(0);
             //success
         } 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 #30
0
 /**
  * Adds hash tweets in JSON format to the database and saves the sender as a new
  * Reporter if they don't already exist
  * @param string $data - Twitter JSON results
  */
 private function add_hash_tweets($data)
 {
     $services = new Service_Model();
     $service = $services->where('service_name', 'Twitter')->find();
     if (!$service) {
         return;
     }
     // HACK: Make twitter IDs be strings so 32bit php doesn't choke on them - Nigel McNie
     $data = preg_replace('/"id":(\\d+)/', '"id":"$1"', $data);
     $tweets = json_decode($data, false);
     if (!$tweets) {
         return;
     }
     if (isset($tweets->{'error'})) {
         return;
     }
     $tweet_results = $tweets->{'results'};
     foreach ($tweet_results as $tweet) {
         // Skip over duplicate tweets
         $tweet_hash = $this->tweet_hash($tweet->text);
         if ($this->is_tweet_registered($tweet_hash)) {
             continue;
         }
         $reporter = ORM::factory('reporter')->where('service_id', $service->id)->where('service_account', $tweet->{'from_user'})->find();
         if (!$reporter->loaded) {
             // get default reporter level (Untrusted)
             $level = ORM::factory('level')->where('level_weight', 0)->find();
             $reporter->service_id = $service->id;
             $reporter->level_id = $level->id;
             $reporter->service_userid = null;
             $reporter->service_account = $tweet->{'from_user'};
             $reporter->reporter_first = null;
             $reporter->reporter_last = null;
             $reporter->reporter_email = null;
             $reporter->reporter_phone = null;
             $reporter->reporter_ip = null;
             $reporter->reporter_date = date('Y-m-d');
             $reporter->save();
         }
         if ($reporter->level_id > 1 && count(ORM::factory('message')->where('service_messageid', $tweet->{'id'})->find_all()) == 0) {
             // Save Tweet as Message
             $message = new Message_Model();
             $message->parent_id = 0;
             $message->incident_id = 0;
             $message->user_id = 0;
             $message->reporter_id = $reporter->id;
             $message->message_from = $tweet->{'from_user'};
             $message->message_to = null;
             $message->message = $tweet->{'text'};
             $message->message_type = 1;
             // Inbox
             $tweet_date = date("Y-m-d H:i:s", strtotime($tweet->{'created_at'}));
             $message->message_date = $tweet_date;
             $message->service_messageid = $tweet->{'id'};
             $message->save();
             // Mark this tweet as received for the duplicate checker
             $this->register_tweet($message->id, $tweet_hash);
             // Action::message_twitter_add - Twitter Message Received!
             Event::run('ushahidi_action.message_twitter_add', $message);
         }
         // Auto-Create A Report if Reporter is Trusted
         $reporter_weight = $reporter->level->level_weight;
         $reporter_location = $reporter->location;
         if ($reporter_weight > 0 and $reporter_location) {
             $incident_title = text::limit_chars($message->message, 50, "...", false);
             // Create Incident
             $incident = new Incident_Model();
             $incident->location_id = $reporter_location->id;
             $incident->incident_title = $incident_title;
             $incident->incident_description = $message->message;
             $incident->incident_date = $tweet_date;
             $incident->incident_dateadd = date("Y-m-d H:i:s", time());
             $incident->incident_active = 1;
             if ($reporter_weight == 2) {
                 $incident->incident_verified = 1;
             }
             $incident->save();
             // Update Message with Incident ID
             $message->incident_id = $incident->id;
             $message->save();
             // Save Incident Category
             $trusted_categories = ORM::factory("category")->where("category_trusted", 1)->find();
             if ($trusted_categories->loaded) {
                 $incident_category = new Incident_Category_Model();
                 $incident_category->incident_id = $incident->id;
                 $incident_category->category_id = $trusted_categories->id;
                 $incident_category->save();
             }
         }
     }
 }