/** * Displays a single category checkbox. */ public static function display_category_checkbox($category, $selected_categories, $form_field) { $html = ''; $cid = $category->id; // Get locale $l = Kohana::config('locale.language.0'); $translated_title = Category_Lang_Model::category_title($cid,$l); if($translated_title) { $category_title = $translated_title; }else{ $category_title = $category->category_title; } //$category_title = $category->category_title; $category_color = $category->category_color; // Category is selected. $category_checked = in_array($cid, $selected_categories); $disabled = ""; if ($category->children->count() > 0) { $disabled = " disabled=\"disabled\""; } $html .= form_ex::checkbox($form_field.'['.$cid.']', $cid, $category_checked, ' class="check-box"'.$disabled); $html .= '<label for="'.$form_field.'['.$cid.']'.'">'.$category_title.'</label>'; return $html; }
/** * Get array of category lang entries * @param int category id */ static function category_langs($category_id = FALSE) { // If we haven't already, grab all category_lang entries at once // We often list all categories at once so its more efficient to just get them all. if (!isset(self::$category_langs)) { $category_langs = ORM::factory('category_lang')->find_all(); self::$category_langs = array(); foreach ($category_langs as $category_lang) { self::$category_langs[$category_lang->category_id][$category_lang->locale]['id'] = $category_lang->id; self::$category_langs[$category_lang->category_id][$category_lang->locale]['category_title'] = $category_lang->category_title; self::$category_langs[$category_lang->category_id][$category_lang->locale]['category_description'] = $category_lang->category_description; } } // Not sure we need to bother with this if ($category_id and isset(self::$category_langs[$category_id])) { return array($category_id => self::$category_langs[$category_id]); } return self::$category_langs; }
/** * Displays a single category checkbox. */ public static function display_category_checkbox($category, $selected_categories, $form_field, $enable_parents = FALSE) { $html = ''; $cid = $category->id; // Get locale $l = Kohana::config('locale.language.0'); $translated_title = Category_Lang_Model::category_title($cid, $l); $category_title = $translated_title ? $translated_title : $category->category_title; //$category_title = $category->category_title; $category_color = $category->category_color; // Category is selected. $category_checked = in_array($cid, $selected_categories); $disabled = ""; if (!$enable_parents and $category->children->count() > 0) { $disabled = " disabled=\"disabled\""; } $html .= form::checkbox($form_field . '[]', $cid, $category_checked, ' class="check-box"' . $disabled); $html .= $category_title; return $html; }
/** * Generates a category tree view - recursively iterates * * @return string */ public static function get_category_tree_view() { // To hold the category data $category_data = array(); // Database table prefix $table_prefix = Kohana::config('database.default.table_prefix'); // Database instance $db = new Database(); // Fetch the other categories $sql = "SELECT c.id, c.parent_id, c.category_title, c.category_color, c.category_image, c.category_image_thumb, COUNT(i.id) report_count " . "FROM " . $table_prefix . "category c " . "LEFT JOIN " . $table_prefix . "category c_parent ON (c.parent_id = c_parent.id) " . "LEFT JOIN " . $table_prefix . "incident_category ic ON (ic.category_id = c.id) " . "LEFT JOIN " . $table_prefix . "incident i ON (ic.incident_id = i.id AND i.incident_active = 1 ) " . "WHERE c.category_visible = 1 " . "AND (c_parent.category_visible = 1 OR c.parent_id = 0)" . "AND c.category_title != \"NONE\" " . "GROUP BY c.id " . "ORDER BY c.category_title ASC"; // Create nested array - all in one pass foreach ($db->query($sql) as $category) { // If this is a parent category, just add it to the array if ($category->parent_id == 0) { // save children and report_count if already been created. $children = isset($category_data[$category->id]['children']) ? $category_data[$category->id]['children'] : array(); $report_count = isset($category_data[$category->id]['report_count']) ? $category_data[$category->id]['report_count'] : 0; $category_data[$category->id] = array('category_title' => Category_Lang_Model::category_title($category->id, Kohana::config('locale.language.0')), 'parent_id' => $category->parent_id, 'category_color' => $category->category_color, 'category_image' => $category->category_image, 'category_image_thumb' => $category->category_image_thumb, 'report_count' => $category->report_count + $report_count, 'children' => $children); } else { // If we haven't processed the parent yet, add placeholder parent category if (!array_key_exists($category->parent_id, $category_data)) { $category_data[$category->parent_id] = array('children' => array(), 'report_count' => 0); } // Add children $category_data[$category->parent_id]['children'][$category->id] = array('category_title' => Category_Lang_Model::category_title($category->id, Kohana::config('locale.language.0')), 'parent_id' => $category->parent_id, 'category_color' => $category->category_color, 'category_image' => $category->category_image, 'category_image_thumb' => $category->category_image_thumb, 'report_count' => $category->report_count, 'children' => array()); // Add to parent report count too $category_data[$category->parent_id]['report_count'] += $category->report_count; } } // Generate and return the HTML return self::_generate_treeview_html($category_data); }
public function index($cluster_id = 0) { // Cacheable Controller $this->is_cachable = TRUE; $this->template->header->this_page = 'reports'; $this->template->content = new View('reports'); $this->themes->js = new View('reports_js'); // Get locale $l = Kohana::config('locale.language.0'); $db = new Database; // Get incident_ids if we are to filter by category $allowed_ids = array(); if (isset($_GET['c']) AND (int) $_GET['c']!=0) { $category_id = (int) $_GET['c']; $query = 'SELECT ic.incident_id AS incident_id FROM '.$this->table_prefix.'incident_category AS ic INNER JOIN '.$this->table_prefix.'category AS c ON (ic.category_id = c.id) WHERE c.id='.$category_id.' OR c.parent_id='.$category_id.';'; $query = $db->query($query); if ($query->count()) { foreach ( $query as $items ) { $allowed_ids[] = $items->incident_id; } } else { $allowed_ids[] = "-1"; } } // Get location_ids if we are to filter by location $location_ids = array(); // Break apart location variables, if necessary $southwest = array(); if (isset($_GET['sw'])) { $southwest = explode(",",$_GET['sw']); } $northeast = array(); if (isset($_GET['ne'])) { $northeast = explode(",",$_GET['ne']); } if ( count($southwest) == 2 AND count($northeast) == 2 ) { $lon_min = (float) $southwest[0]; $lon_max = (float) $northeast[0]; $lat_min = (float) $southwest[1]; $lat_max = (float) $northeast[1]; $query = 'SELECT id FROM '.$this->table_prefix.'location WHERE latitude >='.$lat_min.' AND latitude <='.$lat_max.' AND longitude >='.$lon_min.' AND longitude <='.$lon_max; $query = $db->query($query); foreach ( $query as $items ) { $location_ids[] = $items->id; } } elseif (isset($_GET['l']) AND !empty($_GET['l']) AND $_GET['l']!=0) { $location_ids[] = (int) $_GET['l']; } // Get the count $incident_id_in = '1=1'; if (count($allowed_ids) > 0) { $incident_id_in = 'id IN ('.implode(',',$allowed_ids).')'; } $location_id_in = '1=1'; if (count($location_ids) > 0) { $location_id_in = 'location_id IN ('.implode(',',$location_ids).')'; } // Pagination $pagination = new Pagination(array( 'query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => ORM::factory("incident") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->count_all() )); // Reports $incidents = ORM::factory("incident") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->orderby("incident_date", "desc") ->find_all((int) Kohana::config('settings.items_per_page'), $pagination->sql_offset); // Swap out category titles with their proper localizations using an array (cleaner way to do this?) $localized_categories = array(); foreach ($incidents as $incident) { foreach ($incident->category AS $category) { $ct = (string)$category->category_title; if( ! isset($localized_categories[$ct])) { $translated_title = Category_Lang_Model::category_title($category->id,$l); $localized_categories[$ct] = $category->category_title; if($translated_title) { $localized_categories[$ct] = $translated_title; } } } } $this->template->content->localized_categories = $localized_categories; $this->template->content->incidents = $incidents; //Set default as not showing pagination. Will change below if necessary. $this->template->content->pagination = ""; // Pagination and Total Num of Report Stats if ($pagination->total_items == 1) { $plural = ""; } else { $plural = "s"; } if ($pagination->total_items > 0) { $current_page = ($pagination->sql_offset/ (int) Kohana::config('settings.items_per_page')) + 1; $total_pages = ceil($pagination->total_items/ (int) Kohana::config('settings.items_per_page')); if ($total_pages > 1) { // If we want to show pagination $this->template->content->pagination_stats = Kohana::lang('ui_admin.showing_page').' '.$current_page.' '.Kohana::lang('ui_admin.of').' '.$total_pages.' '.Kohana::lang('ui_admin.pages'); $this->template->content->pagination = $pagination; } else { // If we don't want to show pagination $this->template->content->pagination_stats = $pagination->total_items.' '.Kohana::lang('ui_admin.reports'); } } else { $this->template->content->pagination_stats = '('.$pagination->total_items.' report'.$plural.')'; } // Category Title, if Category ID available $category_id = ( isset($_GET['c']) AND !empty($_GET['c']) ) ? $_GET['c'] : "0"; $category = ORM::factory('category') ->find($category_id); if($category->loaded) { $translated_title = Category_Lang_Model::category_title($category_id,$l); if($translated_title) { $this->template->content->category_title = $translated_title; }else{ $this->template->content->category_title = $category->category_title; } }else{ $this->template->content->category_title = ""; } // Collect report stats $this->template->content->report_stats = new View('reports_stats'); // Total Reports $total_reports = Incident_Model::get_total_reports(TRUE); // Average Reports Per Day $oldest_timestamp = Incident_Model::get_oldest_report_timestamp(); // Round the number of days up to the nearest full day $days_since = ceil((time() - $oldest_timestamp) / 86400); if ($days_since < 1) { $avg_reports_per_day = $total_reports; }else{ $avg_reports_per_day = round(($total_reports / $days_since),2); } // Percent Verified $total_verified = Incident_Model::get_total_reports_by_verified(true); $percent_verified = ($total_reports == 0) ? '-' : round((($total_verified / $total_reports) * 100),2).'%'; $this->template->content->report_stats->total_reports = $total_reports; $this->template->content->report_stats->avg_reports_per_day = $avg_reports_per_day; $this->template->content->report_stats->percent_verified = $percent_verified; $this->template->header->header_block = $this->themes->header_block(); }
function index() { $this->template->content = new View('admin/categories'); $this->template->content->title = Kohana::lang('ui_admin.categories'); // Locale (Language) Array $locales = locale::get_i18n(); // Setup and initialize form field names $form = array ( 'action' => '', 'category_id' => '', 'parent_id' => '', 'category_title' => '', 'category_description' => '', 'category_color' => '', 'category_image' => '', 'category_image_thumb' => '' ); // Add the different language form keys for fields foreach($locales as $lang_key => $lang_name){ $form['category_title_'.$lang_key] = ''; } // copy the form as errors, so the errors will be stored with keys corresponding to the form field names $errors = $form; $form_error = FALSE; $form_saved = FALSE; $form_action = ""; $parents_array = array(); // 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 Action if ($post->action == 'a') { // Add some rules, the input field, followed by a list of checks, carried out in order $post->add_rules('parent_id','required','numeric'); $post->add_rules('category_title','required', 'length[3,80]'); $post->add_rules('category_description','required'); $post->add_rules('category_color','required', 'length[6,6]'); $post->add_rules('category_image', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[50K]'); $post->add_callbacks('parent_id', array($this,'parent_id_chk')); // Add the different language form keys for fields foreach($locales as $lang_key => $lang_name){ $post->add_rules('category_title_lang['.$lang_key.']','length[3,80]'); } } // Test to see if things passed the rule checks if ($post->validate()) { $category_id = $post->category_id; $category = new Category_Model($category_id); // Grab languages if they already exist $category_lang = Category_Lang_Model::category_langs($category->id); if(isset($category_lang[$category->id])) { $category_lang = $category_lang[$category->id]; }else{ $category_lang = FALSE; } if( $post->action == 'd' ) { // Delete Action // Delete localizations ORM::factory('category_lang') ->where(array('category_id' => $category_id)) ->delete_all(); // Delete category itself ORM::factory('category') ->where('category_trusted != 1') ->delete($category_id); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.deleted')); } elseif( $post->action == 'v' ) { // Show/Hide Action if ($category->loaded==true) { if ($category->category_visible == 1) { $category->category_visible = 0; } else { $category->category_visible = 1; } $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } elseif( $post->action == 'i' ) { // Delete Image/Icon Action if ($category->loaded==true) { $category_image = $category->category_image; $category_image_thumb = $category->category_image_thumb; if ( ! empty($category_image) AND file_exists(Kohana::config('upload.directory', TRUE).$category_image)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image); } if ( ! empty($category_image_thumb) AND file_exists(Kohana::config('upload.directory', TRUE).$category_image_thumb)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image_thumb); } $category->category_image = null; $category->category_image_thumb = null; $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } elseif( $post->action == 'a' ) { // Save Action $category->parent_id = $post->parent_id; $category->category_title = $post->category_title; $category->category_type = 5; $category->category_description = $post->category_description; $category->category_color = $post->category_color; $category->save(); // Save Localizations foreach($post->category_title_lang as $lang_key => $localized_category_name){ if(isset($category_lang[$lang_key]['id'])) { // Update $cl = ORM::factory('category_lang',$category_lang[$lang_key]['id']); }else{ // Add New $cl = ORM::factory('category_lang'); } $cl->category_title = $localized_category_name; $cl->locale = $lang_key; $cl->category_id = $category->id; $cl->save(); } // Upload Image/Icon $filename = upload::save('category_image'); if ($filename) { $new_filename = "category_".$category->id."_".time(); // Resize Image to 32px if greater Image::factory($filename)->resize(32,32,Image::HEIGHT) ->save(Kohana::config('upload.directory', TRUE) . $new_filename.".png"); // Create a 16x16 version too Image::factory($filename)->resize(16,16,Image::HEIGHT) ->save(Kohana::config('upload.directory', TRUE) . $new_filename."_16x16.png"); // Remove the temporary file unlink($filename); // Delete Old Image $category_old_image = $category->category_image; if ( ! empty($category_old_image) AND file_exists(Kohana::config('upload.directory', TRUE).$category_old_image)) unlink(Kohana::config('upload.directory', TRUE).$category_old_image); // Save $category->category_image = $new_filename.".png"; $category->category_image_thumb = $new_filename."_16x16.png"; $category->save(); } $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.added_edited')); // Empty $form array array_fill_keys($form, ''); } } // 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('category')); $form_error = TRUE; } } // Pagination $pagination = new Pagination(array( 'query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page_admin'), 'total_items' => ORM::factory('category') ->where('parent_id','0') ->count_all() )); $categories = ORM::factory('category') ->with('category_lang') ->where('parent_id','0') ->orderby('category_title', 'asc') ->find_all((int) Kohana::config('settings.items_per_page_admin'), $pagination->sql_offset); $parents_array = ORM::factory('category') ->where('parent_id','0') ->select_list('id', 'category_title'); // add none to the list $parents_array[0] = "--- Top Level Category ---"; // Put "--- Top Level Category ---" at the top of the list ksort($parents_array); $this->template->content->form = $form; $this->template->content->errors = $errors; $this->template->content->form_error = $form_error; $this->template->content->form_saved = $form_saved; $this->template->content->form_action = $form_action; $this->template->content->pagination = $pagination; $this->template->content->total_items = $pagination->total_items; $this->template->content->categories = $categories; $this->template->content->parents_array = $parents_array; // Javascript Header $this->template->colorpicker_enabled = TRUE; $this->template->js = new View('admin/categories_js'); $this->template->form_error = $form_error; $this->template->content->locale_array = $locales; $this->template->js->locale_array = $locales; }
/** * Get categories as an tree array * @param bool Get category count? * @param bool Include hidden categories * @return array **/ public static function get_category_tree_data($count = FALSE, $include_hidden = FALSE) { // To hold the category data $category_data = array(); // Database table prefix $table_prefix = Kohana::config('database.default.table_prefix'); // Database instance $db = new Database(); // Fetch the other categories if ($count) { $sql = "SELECT c.id, c.parent_id, c.category_title, c.category_color, c.category_image, c.category_image_thumb, COUNT(i.id) report_count " . "FROM " . $table_prefix . "category c " . "LEFT JOIN " . $table_prefix . "category c_parent ON (c.parent_id = c_parent.id) " . "LEFT JOIN " . $table_prefix . "incident_category ic ON (ic.category_id = c.id) " . "LEFT JOIN " . $table_prefix . "incident i ON (ic.incident_id = i.id AND i.incident_active = 1 ) " . "WHERE 1=1 " . (!$include_hidden ? "AND c.category_visible = 1 " : "") . (!$include_hidden ? "AND (c_parent.category_visible = 1 OR c.parent_id = 0)" : "") . "GROUP BY c.id " . "ORDER BY c.category_position ASC"; } else { $sql = "SELECT c.id, c.parent_id, c.category_title, c.category_color, c.category_image, c.category_image_thumb " . "FROM " . $table_prefix . "category c " . "LEFT JOIN " . $table_prefix . "category c_parent ON (c.parent_id = c_parent.id) " . "WHERE 1=1 " . (!$include_hidden ? "AND c.category_visible = 1 " : "") . (!$include_hidden ? "AND (c_parent.category_visible = 1 OR c.parent_id = 0)" : "") . "ORDER BY c.category_position ASC"; } // Create nested array - all in one pass foreach ($db->query($sql) as $category) { // If we didn't fetch report_count set fake value if (!$count) { $category->report_count = 0; } // If this is a parent category, just add it to the array if ($category->parent_id == 0) { // save children and report_count if already been created. $children = isset($category_data[$category->id]['children']) ? $category_data[$category->id]['children'] : array(); $report_count = isset($category_data[$category->id]['report_count']) ? $category_data[$category->id]['report_count'] : 0; $category_data[$category->id] = array('category_id' => $category->id, 'category_title' => html::escape(Category_Lang_Model::category_title($category->id)), 'category_description' => html::escape(Category_Lang_Model::category_description($category->id)), 'category_color' => $category->category_color, 'category_image' => $category->category_image, 'children' => $children, 'category_image_thumb' => $category->category_image_thumb, 'parent_id' => $category->parent_id, 'report_count' => $category->report_count + $report_count); } else { // If we haven't processed the parent yet, add placeholder parent category if (!array_key_exists($category->parent_id, $category_data)) { $category_data[$category->parent_id] = array('category_id' => $category->parent_id, 'category_title' => '', 'category_description' => '', 'parent_id' => 0, 'category_color' => '', 'category_image' => '', 'category_image_thumb' => '', 'children' => array(), 'report_count' => 0); } // Add children $category_data[$category->parent_id]['children'][$category->id] = array('category_id' => $category->id, 'category_title' => html::escape(Category_Lang_Model::category_title($category->id)), 'category_description' => html::escape(Category_Lang_Model::category_description($category->id)), 'parent_id' => $category->parent_id, 'category_color' => $category->category_color, 'category_image' => $category->category_image, 'category_image_thumb' => $category->category_image_thumb, 'report_count' => $category->report_count, 'children' => array()); // Add to parent report count too $category_data[$category->parent_id]['report_count'] += $category->report_count; } } return $category_data; }
public static function set_categories($map_controller, $on_backend = false, $group = false) { // Check for localization of parent category // Get locale $l = Kohana::config('locale.language.0'); $parent_categories = array(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Check to see if we're dealing with a group, and thus //should show group specific categories /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if ($group != false) { //check and make sure the simpel groups category is installed $plugin = ORM::factory('plugin')->where('plugin_name', 'simplegroups')->where('plugin_active', '1')->find(); if (!$plugin) { throw new Exception("A group was set in adminmap_helper::set_categories() when the SimpleGroupl plugin is not installed"); } $cats = ORM::factory('simplegroups_category'); if (!$on_backend) { $cats = $cats->where('category_visible', '1'); } $cats = $cats->where('parent_id', '0'); $cats = $cats->where('applies_to_report', 1); $cats = $cats->where('simplegroups_groups_id', $group->id)->find_all(); foreach ($cats as $category) { ///////////////////////////////////////////////////////////////////////////////////////////// // Get the children ///////////////////////////////////////////////////////////////////////////////////////////// $children = array(); foreach ($category->children as $child) { // Check for localization of child category $translated_title = Simplegroups_category_lang_Model::simplegroups_category_title($child->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children["sg_" . $child->id] = array($display_title, $child->category_color, $child->category_image); } $translated_title = Simplegroups_category_lang_Model::simplegroups_category_title($category->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $category->category_title; } // Put it all together $parent_categories["sg_" . $category->id] = array($display_title, $category->category_color, $category->category_image, $children); } } ///////////////////////////////////////////////////////////////////////////////////////////// // Get all active top level categories ///////////////////////////////////////////////////////////////////////////////////////////// $cats = ORM::factory('category'); if (!$on_backend) { $cats = $cats->where('category_visible', '1'); } $cats = $cats->where('parent_id', '0')->find_all(); foreach ($cats as $category) { ///////////////////////////////////////////////////////////////////////////////////////////// // Get the children ///////////////////////////////////////////////////////////////////////////////////////////// $children = array(); foreach ($category->children as $child) { // Check for localization of child category $translated_title = Category_Lang_Model::category_title($child->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children[$child->id] = array($display_title, $child->category_color, $child->category_image); if ($child->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $child->id); if (!$trusted->count_all()) { unset($children[$child->id]); } } } $translated_title = Category_Lang_Model::category_title($category->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $category->category_title; } // Put it all together $parent_categories[$category->id] = array($display_title, $category->category_color, $category->category_image, $children); if ($category->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $category->id); if (!$trusted->count_all()) { unset($parent_categories[$category->id]); } } } $map_controller->template->content->categories = $parent_categories; }
/** * Lists the reports. * @param int $page */ function index($page = 1, $group_id = false) { // Cacheable Controller $this->is_cachable = TRUE; $this->template->header->this_page = 'reports'; $this->template->content = new View('reports'); $this->themes->js = new View('reports_js'); // Get locale $l = Kohana::config('locale.language.0'); $db = new Database(); if (!empty($_GET['status'])) { $status = strtolower($_GET['status']); if ($status == 'a') { $filter = 'incident.incident_active = 0'; } elseif ($status == 'v') { $filter = 'incident.incident_verified = 0'; } elseif ($status == 't') { $filter = 'incident.incident_verified = 1'; } elseif ($status == 'f') { $filter = 'incident.incident_assigned = 1'; } elseif ($status == 'd') { $filter = 'incident.incident_disputed = 0'; } else { $status = "0"; $filter = '1=1'; } } else { $status = "0"; $filter = "1=1"; } // check, has the form been submitted? $form_error = FALSE; $form_saved = FALSE; $form_action = ""; $db = new Database(); // Category ID $category_ids = array(); if (isset($_GET['c']) and !empty($_GET['c'])) { $category_ids = explode(",", $_GET['c']); //get rid of that trailing "," } else { $category_ids = array("0"); } // logical operator $logical_operator = "or"; if (isset($_GET['lo']) and !empty($_GET['lo'])) { $logical_operator = $_GET['lo']; } $approved_text = " incident.incident_active = 1 "; $location_where = ""; // Break apart location variables, if necessary $southwest = array(); if (isset($_GET['sw'])) { $southwest = explode(",", $_GET['sw']); } $northeast = array(); if (isset($_GET['ne'])) { $northeast = explode(",", $_GET['ne']); } if (count($southwest) == 2 and count($northeast) == 2) { $lon_min = (double) $southwest[0]; $lon_max = (double) $northeast[0]; $lat_min = (double) $southwest[1]; $lat_max = (double) $northeast[1]; $location_where = ' AND (location.latitude >=' . $lat_min . ' AND location.latitude <=' . $lat_max . ' AND location.longitude >=' . $lon_min . ' AND location.longitude <=' . $lon_max . ') '; } $group_where = " AND ( " . $this->table_prefix . "simplegroups_groups_incident.simplegroups_groups_id = " . $group_id . ") "; $joins = groups::get_joins_for_groups($category_ids); $sg_category_to_table_mapping = groups::get_category_to_table_mapping(); $reports_count = adminmap_reports::get_reports_count($category_ids, $approved_text, $location_where . " AND " . $filter . $group_where, $logical_operator, $joins, $sg_category_to_table_mapping); echo $reports_count . " " . Kohana::config('settings.items_per_page'); // Pagination $pagination = new Pagination(array('query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => $reports_count)); $incidents = adminmap_reports::get_reports($category_ids, $approved_text, $location_where . " AND " . $filter . $group_where, $logical_operator, "incident.incident_date", "asc", (int) Kohana::config('settings.items_per_page'), $pagination->sql_offset, $joins, $sg_category_to_table_mapping); //Set default as not showing pagination. Will change below if necessary. $this->template->content->pagination = ""; // Pagination and Total Num of Report Stats if ($pagination->total_items == 1) { $plural = ""; } else { $plural = "s"; } if ($pagination->total_items > 0) { $current_page = $pagination->sql_offset / (int) Kohana::config('settings.items_per_page') + 1; $total_pages = ceil($pagination->total_items / (int) Kohana::config('settings.items_per_page')); if ($total_pages > 1) { // If we want to show pagination $this->template->content->pagination_stats = Kohana::lang('ui_admin.showing_page') . ' ' . $current_page . ' ' . Kohana::lang('ui_admin.of') . ' ' . $total_pages . ' ' . Kohana::lang('ui_admin.pages'); $this->template->content->pagination = $pagination; } else { // If we don't want to show pagination $this->template->content->pagination_stats = $pagination->total_items . ' ' . Kohana::lang('ui_admin.reports'); } } else { $this->template->content->pagination_stats = '(' . $pagination->total_items . ' report' . $plural . ')'; } //locations $location_in = array(); foreach ($incidents as $incident) { $location_in[] = $incident->location_id; } //check if location_in is not empty if (count($location_in) > 0) { // Get location names $query = 'SELECT id, location_name FROM ' . $this->table_prefix . 'location WHERE id IN (' . implode(',', $location_in) . ')'; $locations_query = $db->query($query); $locations = array(); foreach ($locations_query as $loc) { $locations[$loc->id] = $loc->location_name; } } else { $locations = array(); } $this->template->content->locations = $locations; //categories $localized_categories = array(); foreach ($incidents as $incident) { foreach ($incident->category as $category) { $ct = (string) $category->category_title; if (!isset($localized_categories[$ct])) { $translated_title = Category_Lang_Model::category_title($category->id, $l); $localized_categories[$ct] = $category->category_title; if ($translated_title) { $localized_categories[$ct] = $translated_title; } } } } $this->template->content->localized_categories = $localized_categories; // Category Title, if Category ID available $category_title = "All Categories"; $count = 0; foreach ($category_ids as $cat_id) { $category = ORM::factory('category')->find($cat_id); if ($category->loaded) { $count++; if ($count > 1) { $category_title = $category_title . " " . strtoupper($logical_operator) . " "; } $category_title = $category_title . $category->category_title; } } $this->template->content->category_title = $category_title . ": "; //GET countries $countries = array(); foreach (ORM::factory('country')->orderby('country')->find_all() as $country) { // Create a list of all categories $this_country = $country->country; if (strlen($this_country) > 35) { $this_country = substr($this_country, 0, 35) . "..."; } $countries[$country->id] = $this_country; } $this->template->content->countries = $countries; $this->template->content->incidents = $incidents; $this->template->content->pagination = $pagination; $this->template->content->form_error = $form_error; $this->template->content->form_saved = $form_saved; $this->template->content->form_action = $form_action; // Total Reports $this->template->content->total_items = $pagination->total_items; // Status Tab $this->template->content->status = $status; $this->template->header->header_block = $this->themes->header_block(); }
/** * Function: set_categories * * Description: Sets up the UI element that displays the boolean (and/or) filter * * @param boolean $on_backend - True if the output of this function will grace a page on the backend * @param int $group - The database ID of a Simple Group group, or false if there isn't one. * @param string $categories_view - Path to the view that will render this filter * @param string $categories_view_id - HTML element ID of the UI for this filter * @param bool $alphabetize - True if the categories should be listed in alphabetical order, false they'll be listed in the order they are set on the manage page. * @throws Exception - If you provide a group id in $group, but the simple group plugin isn't installed * @return obj - The view all ready to be inserted into your template of choice. * * Views: depends on what the user passes in * * Results: Returns a view all ready to be inserted into your template of choice. */ public static function set_categories($on_backend = false, $group = false, $categories_view = "enhancedmap/categories_filter", $categories_view_id = "category_switch", $alphabetize = false) { $view = new View($categories_view); // Check for localization of parent category // Get locale $l = Kohana::config('locale.language.0'); $parent_categories = array(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Check to see if we're dealing with a group, and thus //should show group specific categories /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if ($group != false) { //check and make sure the simpel groups category is installed $plugin = ORM::factory('plugin')->where('plugin_name', 'simplegroups')->where('plugin_active', '1')->find(); if (!$plugin) { throw new Exception("A group was set in enhancedmap_helper::set_categories() when the SimpleGroupl plugin is not installed"); } $cats = ORM::factory('simplegroups_category'); if (!$on_backend or ORM::factory('enhancedmap_settings')->where('key', 'show_hidden_categories_backend')->find()->value != 'true') { $cats = $cats->where('category_visible', '1'); } $cats = $cats->where('parent_id', '0'); $cats = $cats->where('applies_to_report', 1); $cats = $cats->where('simplegroups_groups_id', $group->id); if ($alphabetize) { $cats = $cats->orderby('category_title', 'ASC'); } $cats = $cats->find_all(); foreach ($cats as $category) { ///////////////////////////////////////////////////////////////////////////////////////////// // Get the children ///////////////////////////////////////////////////////////////////////////////////////////// $children = array(); foreach ($category->children as $child) { // Check for localization of child category $translated_title = Simplegroups_category_lang_Model::simplegroups_category_title($child->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children["sg_" . $child->id] = array($display_title, $child->category_color, $child->category_image); } $translated_title = Simplegroups_category_lang_Model::simplegroups_category_title($category->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $category->category_title; } // Put it all together $parent_categories["sg_" . $category->id] = array($display_title, $category->category_color, $category->category_image, $children); } } ///////////////////////////////////////////////////////////////////////////////////////////// // Get all active top level categories ///////////////////////////////////////////////////////////////////////////////////////////// $cats = ORM::factory('category'); if (!$on_backend or ORM::factory('enhancedmap_settings')->where('key', 'show_hidden_categories_backend')->find()->value != 'true') { $cats = $cats->where('category_visible', '1'); } $cats = $cats->where('parent_id', '0'); if ($alphabetize) { $cats = $cats->orderby('category_title', 'ASC'); } else { $cats = $cats->orderby('category_position', 'asc'); } $cats = $cats->find_all(); foreach ($cats as $category) { ///////////////////////////////////////////////////////////////////////////////////////////// // Get the children ///////////////////////////////////////////////////////////////////////////////////////////// $children = array(); foreach ($category->children as $child) { // Check for localization of child category $translated_title = Category_Lang_Model::category_title($child->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children[$child->id] = array($display_title, $child->category_color, $child->category_image); if ($child->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $child->id); if (!$trusted->count_all()) { unset($children[$child->id]); } } } $translated_title = Category_Lang_Model::category_title($category->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $category->category_title; } // Put it all together $parent_categories[$category->id] = array($display_title, $category->category_color, $category->category_image, $children); if ($category->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $category->id); if (!$trusted->count_all()) { unset($parent_categories[$category->id]); } } } $view->categories = $parent_categories; $view->categories_view_id = $categories_view_id; return $view; }
/** * Import categories via XML * @param DOMNodeList Object $categories * @return bool */ public function import_categories($categories) { /* Import individual categories*/ foreach ($categories->getElementsByTagName('category') as $category) { // Increment category counter $this->totalcategories++; // Category Title $cat_title = xml::get_node_text($category, 'title'); // Category Description $cat_description = xml::get_node_text($category, 'description'); // If either the category title or description is not provided if (!$cat_title or !$cat_description) { $this->errors[] = Kohana::lang('import.xml.category_error') . $this->totalcategories; } else { // If this category does not already exist in the database if (!isset($this->existing_categories[utf8::strtoupper($cat_title)])) { // Get category attributes $cat_color = xml::get_node_text($category, 'color', FALSE); $cat_visible = $category->getAttribute('visible'); $cat_trusted = $category->getAttribute('trusted'); /* Get other category elements */ // Parent Category $cat_parent = xml::get_node_text($category, 'parent'); if ($cat_parent) { $parent_id = isset($this->existing_categories[utf8::strtoupper($cat_parent)]) ? $this->existing_categories[utf8::strtoupper($cat_parent)] : 0; } // Save the Category $new_category = new Category_Model(); $new_category->category_title = $cat_title; $new_category->category_description = $cat_description ? $cat_description : NULL; $new_category->parent_id = isset($parent_id) ? $parent_id : 0; $new_category->category_color = $cat_color ? $cat_color : '000000'; $new_category->category_visible = (isset($cat_visible) and in_array($cat_visible, $this->allowable)) ? $cat_visible : 1; $new_category->category_trusted = (isset($cat_trusted) and in_array($cat_trusted, $this->allowable)) ? $cat_trusted : 0; $new_category->category_position = count($this->existing_categories); $new_category->save(); // Add this new category to array of existing categories $this->existing_categories[utf8::strtoupper($cat_title)] = $new_category->id; // Also add it to the array of categories added during import $this->categories_added[] = $new_category->id; $this->notices[] = Kohana::lang('import.new_category') . html::escape($cat_title); } /* Category Translations */ $c_translations = $category->getElementsByTagName('translations'); // Get the current category's id $cat_id = $this->existing_categories[utf8::strtoupper($cat_title)]; // If category translations exist if ($c_translations->length > 0) { $cat_translations = $c_translations->item(0); foreach ($cat_translations->getElementsByTagName('translation') as $translation) { // Get Localization $locale = xml::get_node_text($translation, 'locale', FALSE); // Does the locale attribute exist in the document? And is it empty? if ($locale) { // Check if category translation exists for this localization $existing_translations = ORM::factory('category_lang')->where('category_id', $cat_id)->where('locale', $locale)->find_all(); // If Category translation does not exist, save it if (count($existing_translations) == 0) { // Get category title for this localization $trans_title = xml::get_node_text($translation, 'translation_title'); // Category Description $trans_description = xml::get_node_text($translation, 'translation_description'); // If we're missing the translated category title if (!$trans_title) { $this->notices[] = Kohana::lang('import.xml.translation_title') . $this->totalcategories . ': ' . utf8::strtoupper($locale); } else { // Save Category Translations $cl = new Category_Lang_Model(); $cl->locale = $locale; $cl->category_id = $cat_id; $cl->category_title = $trans_title; $cl->category_description = $trans_description ? $trans_description : NULL; $cl->save(); // Add this to array of category translations added during import $this->category_translations_added[] = $cl->id; $this->notices[] = Kohana::lang('import.xml.translation_added') . '"' . utf8::strtoupper($locale) . '" for ' . $cat_title; } } } else { $this->notices[] = Kohana::lang('import.xml.missing_localization') . $this->totalcategories; } } } } } // End individual category import // If we have errors, return FALSE, else TRUE return count($this->errors) === 0; }
public function index($cluster_id = 0) { // Cacheable Controller $this->is_cachable = TRUE; $this->template->header->this_page = 'reports'; $this->template->content = new View('reports'); $this->themes->js = new View('reports_js'); // Get locale $l = Kohana::config('locale.language.0'); $this->template->content->area_name = ""; $this->template->content->disp_distance = ""; //FORMのhiddenタグ用パラメータ初期化と代入 if(isset($_SESSION["locale"])){ $_GET["l"] = $_SESSION["locale"]; } // 引き回すGETパラメータのテンプレートへの引き渡し $this->template->content->keyword = valid::initGetVal('keyword',"text"); $this->template->content->address = valid::initGetVal('address',"text"); $this->template->content->distance = valid::initGetVal('distance',"number"); $this->template->content->c = valid::initGetVal('c',"number"); $this->template->content->sw = valid::initGetVal('sw',"text"); $this->template->content->ne = valid::initGetVal('ne',"text"); $this->template->content->l = valid::initGetVal('l',"natural_numbewr"); $this->template->content->mode = valid::initGetVal('mode',"text"); $this->template->content->order = valid::initGetVal('order',"text"); $db = new Database; // Get incident_ids if we are to filter by category $allowed_ids = array(); if (isset($_GET['c']) AND !empty($_GET['c']) AND $_GET['c']!=0) { $category_id = $db->escape($_GET['c']); $query = 'SELECT ic.incident_id AS incident_id FROM '.$this->table_prefix.'incident_category AS ic INNER JOIN '.$this->table_prefix.'category AS c ON (ic.category_id = c.id) WHERE c.id='.$category_id.' OR c.parent_id='.$category_id.';'; $query = $db->query($query); foreach ( $query as $items ) { $allowed_ids[] = $items->incident_id; } } // Get location_ids if we are to filter by location $location_ids = array(); // Break apart location variables, if necessary $southwest = array(); if (isset($_GET['sw'])) { $southwest = explode(",",$_GET['sw']); } $northeast = array(); if (isset($_GET['ne'])) { $northeast = explode(",",$_GET['ne']); } //指定地区の指定半径内インシデント取得でGoogleMAPAPIで緯度経度を取得できなかった場合DBを取りに行かないようにするためのフラグ $dbget_flg = true; $this->template->content->choices_flg = false; //指定地区の指定半径内インシデント取得処理 if(isset($_GET["address"]) && trim($_GET["address"]) !== "" && isset($_GET["distance"]) && is_numeric($_GET["distance"]) && $_GET["distance"] > 0){ $address = urlencode($_GET["address"]); // http://www.geocoding.jp/を利用して指定地区名の緯度経度を取得 $geocoding_url = 'http://www.geocoding.jp/api/?q='.$address; $geo_geocoding = @file_get_contents($geocoding_url,false,stream_context_create(array('http' => array('timeout'=>$this->api_timeout)))); // APIのエラーハンドリング if($geo_geocoding === FALSE){ if(count($http_response_header) > 0){ $stat_tokens = explode(' ', $http_response_header[0]); switch($stat_tokens[1]){ case 404: // 404 Not found の場合 break; case 500: // 500 Internal Server Error の場合 break; default: // その他 break; } }else{ // タイムアウトの場合 } }else{ $geo_geocoding = simplexml_load_string($geo_geocoding); } //結果の取得とインシデントの取得 if(isset($geo_geocoding->coordinate)){ if(isset($geo_geocoding->coordinate->lat) && isset($geo_geocoding->coordinate->lng)){ $lat_center = $geo_geocoding->coordinate->lat; $lon_center = $geo_geocoding->coordinate->lng; $area_name = $geo_geocoding->address; $_GET["address"] = $this->template->content->area_name = trim($area_name); if($_GET["distance"] >= 1){ $this->template->content->disp_distance = $_GET["distance"]."km"; }else{ $this->template->content->disp_distance = ($_GET["distance"]*1000)."m"; } $query = 'SELECT id FROM '.$this->table_prefix.'location WHERE (round(sqrt(pow(('.$this->table_prefix.'location.latitude - '.$lat_center.')/0.0111, 2) + pow(('.$this->table_prefix.'location.longitude - '.$lon_center.')/0.0091, 2)), 1)) <= '.$_GET["distance"]; $query = $db->query($query); foreach ( $query as $items ) { $location_ids[] = $items->id; } } }elseif(isset($geo_geocoding->choices)){ $this->template->content->choices_flg = true; $dbget_flg = false; } //TOPの赤丸からのインシデント取得処理 }elseif ( count($southwest) == 2 AND count($northeast) == 2 ){ $lon_min = (float) $southwest[0]; $lon_max = (float) $northeast[0]; $lat_min = (float) $southwest[1]; $lat_max = (float) $northeast[1]; $lon_center = ($lon_min+$lon_max) / 2; $lat_center = ($lat_min+$lat_max) / 2; $dist1 = (round(sqrt(pow(($lat_max - $lat_center)/0.0111, 2) + pow(($lon_max - $lon_center)/0.0091, 2)), 1)); $dist2 = (round(sqrt(pow(($lat_min - $lat_center)/0.0111, 2) + pow(($lon_min - $lon_center)/0.0091, 2)), 1)); // http://www.finds.jp/を利用して中央地点の地名を取得 $finds_url = 'http://www.finds.jp/ws/rgeocode.php?json&lat='.$lat_center.'&lon='.$lon_center; $geo_finds = @file_get_contents($finds_url,false,stream_context_create(array('http' => array('timeout'=>$this->api_timeout)))); // APIのエラーハンドリング if($geo_finds === FALSE){ if(count($http_response_header) > 0){ $stat_tokens = explode(' ', $http_response_header[0]); switch($stat_tokens[1]){ case 404: // 404 Not found の場合 break; case 500: // 500 Internal Server Error の場合 break; default: // その他 break; } }else{ // タイムアウトの場合 } }else{ $geo_finds = json_decode($geo_finds,true); } if($geo_finds["status"]===200 || $geo_finds["status"]===201 ||$geo_finds["status"]===202){ $area_name = str_replace(' ','',$geo_finds["result"]["prefecture"]["pname"].$geo_finds["result"]["municipality"]["mname"]); if(isset($area_name) && $area_name !== ""){ $_GET["address"] = $this->template->content->area_name = $area_name; } } //指定範囲内のインシデントを取得 $query = 'SELECT id FROM '.$this->table_prefix.'location WHERE latitude >='.$lat_min.' AND latitude <='.$lat_max.' AND longitude >='.$lon_min.' AND longitude <='.$lon_max; $query = $db->query($query); foreach ( $query as $items ) { $location_ids[] = $items->id; } }elseif (isset($_GET['l']) AND !empty($_GET['l']) AND $_GET['l']!=0){ $location_ids[] = (int) $_GET['l']; } // Get the count $incident_id_in = '1=1'; if (count($allowed_ids) > 0) { $incident_id_in = 'incident.id IN ('.implode(',',$allowed_ids).')'; } $location_id_in = '1=1'; if (count($location_ids) > 0) { $location_id_in = 'location_id IN ('.implode(',',$location_ids).')'; } // 検索キーワード取得 if(isset($_GET["keyword"]) && trim($_GET["keyword"]) !==""){ $keywords = array(); $keyword = str_replace(" "," ",$_GET["keyword"]); $keywords = explode(" ",$keyword); } // キーワード検索の初期化(キーワードがない場合のエラー対応) $keyword_like = "1=1"; if(isset($keywords) && count($keywords)){ $keyword_like = array(); foreach($keywords as $val){ $keyword_like[] = "(incident_title like '%".addslashes($val)."%' OR incident_description like '%".addslashes($val)."%')"; } $keyword_like = implode(' AND ',$keyword_like); } if($dbget_flg){ // formからの送信の場合 if(isset($_GET["mode"])){ // 共通処理としてのページネーション // Pagination $pagination = new Pagination(array( 'query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => ORM::factory("incident") ->join($this->table_prefix.'location',$this->table_prefix.'location.id',$this->table_prefix.'incident.location_id',"LEFT OUTER") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->where($keyword_like) ->count_all() )); // Reports // 中心座標が取得できていれば if(isset($lat_center)){ // ソート順を定義 if(isset($_GET["order"]) && $_GET["order"]=="new"){ // 新着順 $order = array( "incident_date"=>"desc", '(round(sqrt(pow(('.$this->table_prefix.'location.latitude - '.$lat_center.')/0.0111, 2) + pow(('.$this->table_prefix.'location.longitude - '.$lon_center.')/0.0091, 2)), 1))'=>"asc" ); }elseif(isset($_GET["order"]) && $_GET["order"]=="dist"){ // 近隣順 $order = array( '(round(sqrt(pow(('.$this->table_prefix.'location.latitude - '.$lat_center.')/0.0111, 2) + pow(('.$this->table_prefix.'location.longitude - '.$lon_center.')/0.0091, 2)), 1))'=>"asc", "incident_date"=>"desc" ); } // SELECT句に中心点からの距離を追加 $select = $this->table_prefix.'incident.*,(round(sqrt(pow(('.$this->table_prefix.'location.latitude - '.$lat_center.')/0.0111, 2) + pow(('.$this->table_prefix.'location.longitude - '.$lon_center.')/0.0091, 2)), 1)) as dist'; }else{ // 中心座標が取れていなければ新着順で固定 $order = array( "incident_date"=>"desc" ); // SELECT句はincidentsの全レコード $select = $this->table_prefix.'incident.*'; } if($_GET["mode"]=="areaorder"){ $incidents = ORM::factory("incident") ->select($select,false) ->join($this->table_prefix.'location',$this->table_prefix.'location.id',$this->table_prefix.'incident.location_id',"LEFT OUTER") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->where($keyword_like) ->orderby('(round(sqrt(pow(('.$this->table_prefix.'location.latitude - '.$lat_center.')/0.0111, 2) + pow(('.$this->table_prefix.'location.longitude - '.$lon_center.')/0.0091, 2)), 1))', "asc",false) ->find_all((int) Kohana::config('settings.items_per_page'), $pagination->sql_offset); }elseif($_GET["mode"]=="areasearch"){ if(isset($_GET["order"]) && isset($_GET["order"])){ $escape = false; }else{ $escape = true; } // Reports $incidents = ORM::factory("incident") ->select($select,$escape) ->join($this->table_prefix.'location',$this->table_prefix.'location.id',$this->table_prefix.'incident.location_id',"LEFT OUTER") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->where($keyword_like) ->orderby($order,NULL,$escape) ->find_all((int) Kohana::config('settings.items_per_page'), $pagination->sql_offset); } }else{ // Pagination $pagination = new Pagination(array( 'query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => ORM::factory("incident") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->where($keyword_like) ->count_all() )); // Reports $incidents = ORM::factory("incident") ->where("incident_active", 1) ->where($location_id_in) ->where($incident_id_in) ->where($keyword_like) ->orderby("incident_date", "desc") ->find_all((int) Kohana::config('settings.items_per_page'), $pagination->sql_offset); } }else{ $incidents = array(); $pagination = new Pagination(); } // Swap out category titles with their proper localizations using an array (cleaner way to do this?) // $query = 'SELECT id,category_title,category_color FROM category WHERE category_visible = 1 AND category_trusted = 0'; $query = 'SELECT id,category_title,category_color,category_image_thumb FROM category ORDER BY category_type desc;'; $query = $db->query($query); $category_master = array(); $localized_categories = array(); foreach($query as $row){ $category_master[$row->id]['title'] = $row->category_title; $category_master[$row->id]['color'] = $row->category_color; $category_master[$row->id]['category_image_thumb'] = $row->category_image_thumb; $localized_categories[(string)$row->category_title] = $row->category_title; $localized_categories[(string)$row->category_title]['title'] = $row->category_title; $localized_categories[(string)$row->category_title]['color'] = $row->category_title; } $this->template->content->category_master = $category_master; $this->template->content->localized_categories = $localized_categories; $this->template->content->incidents = $incidents; //Set default as not showing pagination. Will change below if necessary. $this->template->content->pagination = ""; // Pagination and Total Num of Report Stats if ($pagination->total_items == 1) { $plural = ""; } else { $plural = "s"; } if ($pagination->total_items > 0) { $current_page = ($pagination->sql_offset/ (int) Kohana::config('settings.items_per_page')) + 1; $total_pages = ceil($pagination->total_items/ (int) Kohana::config('settings.items_per_page')); if ($total_pages > 1) { // If we want to show pagination if((isset($_GET["l"]) && ($_GET["l"] === "ja_JP" || $_GET["l"] === "")) OR (!isset($_GET["l"]))){ $this->template->content->pagination_stats = "全".$total_pages."中".$current_page.Kohana::lang('ui_admin.showing_page'); }else{ $this->template->content->pagination_stats = Kohana::lang('ui_admin.showing_page').' '.$current_page.' '.Kohana::lang('ui_admin.of').' '.$total_pages.' '.Kohana::lang('ui_admin.pages'); } $this->template->content->pagination = $pagination; } else { // If we don't want to show pagination $this->template->content->pagination_stats = $pagination->total_items.' '.Kohana::lang('ui_admin.reports'); } } else { $this->template->content->pagination_stats = '('.$pagination->total_items.' report'.$plural.')'; } // Category Title, if Category ID available $category_id = ( isset($_GET['c']) AND !empty($_GET['c']) ) ? $_GET['c'] : "0"; $category = ORM::factory('category') ->find($category_id); if($category->loaded) { $translated_title = Category_Lang_Model::category_title($category_id,$l); if($translated_title) { $this->template->content->category_title = $translated_title; }else{ $this->template->content->category_title = $category->category_title; } }else{ $this->template->content->category_title = ""; } // Collect report stats $this->template->content->report_stats = new View('reports_stats'); // Total Reports $total_reports = Incident_Model::get_total_reports(TRUE); // Average Reports Per Day $oldest_timestamp = Incident_Model::get_oldest_report_timestamp(); // Round the number of days up to the nearest full day $days_since = ceil((time() - $oldest_timestamp) / 86400); if ($days_since < 1) { $avg_reports_per_day = $total_reports; }else{ $avg_reports_per_day = round(($total_reports / $days_since),2); } // Percent Verified $total_verified = Incident_Model::get_total_reports_by_verified(true); $percent_verified = ($total_reports == 0) ? '-' : round((($total_verified / $total_reports) * 100),2).'%'; $this->template->content->report_stats->total_reports = $total_reports; $this->template->content->report_stats->avg_reports_per_day = $avg_reports_per_day; $this->template->content->report_stats->percent_verified = $percent_verified; $this->template->header->action_name = Kohana::lang('ui_main.reports_title_index'); $this->template->header->header_block = $this->themes->header_block(); }
/** * Get all categories * * @param string response_type - XML or JSON * * @return string */ public function get_categories_by_all() { $items = array(); //will hold the items from the query $data = array(); //items to parse to json $json_categories = array(); //incidents to parse to json $ret_json_or_xml = ''; //will hold the json/xml string to return //find incidents $this->query = "SELECT c.id, c.parent_id, c.category_title as title, c.category_description as description, \n c.category_color as color, c.category_position as position, c.category_image_thumb AS icon\n FROM `" . $this->table_prefix . "category` c\n LEFT JOIN `" . $this->table_prefix . "category` c_parent ON (c.parent_id = c_parent.id) WHERE\n c.category_visible = 1 AND (c_parent.category_visible = 1 OR c.parent_id = 0) ORDER BY c.category_position ASC"; $items = $this->db->query($this->query); $translations = Category_Lang_Model::category_langs(); // Set the no. of records fetched $this->record_count = $items->count(); $i = 0; $this->replar = array(); //assists in proper xml generation $url_prefix = url::base() . Kohana::config('upload.relative_directory') . '/'; foreach ($items as $item) { $item->icon = $item->icon ? $url_prefix . $item->icon : ''; //needs different treatment depending on the output if ($this->response_type == 'json' or $this->response_type == 'jsonp') { $json_categories[] = array("category" => $item, "translations" => isset($translations[$item->id]) ? $translations[$item->id] : array()); } else { $item->translations = array(); if (isset($translations[$item->id])) { foreach ($translations[$item->id] as $lang => $translation) { $translation['lang'] = $lang; $item->translations['translation' . $translation['id']] = array('translation' => $translation); $this->replar[] = 'translation' . $translation['id']; } } $json_categories['category' . $i] = array("category" => $item); $this->replar[] = 'category' . $i; } $i++; } //create the json array $data = array("payload" => array("domain" => $this->domain, "categories" => $json_categories), "error" => $this->api_service->get_error_msg(0)); if ($this->response_type == 'json' or $this->response_type == 'jsonp') { $ret_json_or_xml = $this->array_as_json($data); } else { $ret_json_or_xml = $this->array_as_xml($data, $this->replar); } return $ret_json_or_xml; }
/** * Function to import CSV file referenced by the file handle * @param string $filehandle * @return bool */ function import($file) { // Get contents of CSV file $data = file_get_contents($file); // Normalize new lines, replace ANY unicode new line with \n (should cover Mac OS9, Unix, Windows, etc) $replacedata = preg_replace('/\\R/u', "\n", mb_convert_encoding($data, 'UTF-8')); // Check for preg error, and fall back to original data if (preg_last_error() !== PREG_NO_ERROR) { $replacedata = $data; } // Replace file content file_put_contents($file, $replacedata); if ($filehandle = fopen($_FILES['uploadfile']['tmp_name'], 'r')) { $csvtable = new Csvtable($filehandle); // Set the required columns of the CSV file $requiredcolumns = array('INCIDENT TITLE', 'INCIDENT DATE'); foreach ($requiredcolumns as $requiredcolumn) { // If the CSV file is missing any required column, return an error if (!$csvtable->hasColumn($requiredcolumn)) { $this->errors[] = Kohana::lang('import.csv.required_column') . '"' . $requiredcolumn . '"'; } } if (count($this->errors)) { return false; } // So we can assign category id to incidents, based on category title $this->existing_categories = ORM::factory('category')->select_list('category_title', 'id'); //Since we capitalize the category names from the CSV file, we should also capitlize the //category titles here so we get case insensative behavior. For some reason users don't //always captilize the cateogry names as they enter them in $temp_cat = array(); foreach ($this->existing_categories as $title => $id) { $temp_cat[utf8::strtoupper($title)] = $id; // Add translated titles too $langs = Category_Lang_Model::category_langs($id); if (isset($langs[$id])) { foreach ($langs[$id] as $l) { $temp_cat[utf8::strtoupper($l['category_title'])] = $id; } } } $this->existing_categories = $temp_cat; // So we can check if incident already exists in database $this->incident_ids = ORM::factory('incident')->select_list('id', 'id'); $this->time = date("Y-m-d H:i:s", time()); $rows = $csvtable->getRows(); $this->totalreports = count($rows); $this->rownumber = 0; // Loop through CSV rows foreach ($rows as $row) { $this->rownumber++; if (isset($row['#']) and isset($this->incident_ids[$row['#']])) { $this->notices[] = Kohana::lang('import.incident_exists') . $row['#']; } else { if ($this->import_report($row)) { $this->importedreports++; } else { $this->rollback(); return false; } } } } else { $this->errors[] = Kohana::lang('ui_admin.file_open_error'); } // If we have errors, return FALSE, else TRUE return count($this->errors) === 0; }
public function index($cluster_id = 0) { // Cacheable Controller $this->is_cachable = TRUE; $this->template->header->this_page = 'reports'; $this->template->content = new View('reports'); $this->themes->js = new View('reports_js'); // Get locale $l = Kohana::config('locale.language.0'); $db = new Database(); // Get incident_ids if we are to filter by category $allowed_ids = array(); $category_ids_in = NULL; $category_ids = array(); $category_ids_string = array(); $design_response_category = (int) Kohana::config('pps.design_response_category_id'); if (isset($_GET['c']) and !empty($_GET['c']) and $_GET['c'] != 0) { $category_ids_string = is_array($_GET['c']) ? $_GET['c'] : array($_GET['c']); } else { // default to design response search $category_ids_string = array('' . $design_response_category); } if (!empty($category_ids_string)) { foreach ($category_ids_string as $category_id) { $category_ids[] = (int) str_replace("'", "", $db->escape($category_id)); } $query = 'SELECT incident_id, count(*) AS count FROM incident_category WHERE category_id in (' . implode(',', $category_ids) . ') GROUP BY incident_id HAVING count=' . count($category_ids); $query = $db->query($query); if (count($query) === 0) { $allowed_ids[] = -1; } else { foreach ($query as $items) { $allowed_ids[] = $items->incident_id; } } } // Get location_ids if we are to filter by location $location_ids = array(); // Break apart location variables, if necessary $southwest = array(); if (isset($_GET['sw'])) { $southwest = explode(",", $_GET['sw']); } $northeast = array(); if (isset($_GET['ne'])) { $northeast = explode(",", $_GET['ne']); } if (count($southwest) == 2 and count($northeast) == 2) { $lon_min = (double) $southwest[0]; $lon_max = (double) $northeast[0]; $lat_min = (double) $southwest[1]; $lat_max = (double) $northeast[1]; $query = 'SELECT id FROM ' . $this->table_prefix . 'location WHERE latitude >=' . $lat_min . ' AND latitude <=' . $lat_max . ' AND longitude >=' . $lon_min . ' AND longitude <=' . $lon_max; $query = $db->query($query); foreach ($query as $items) { $location_ids[] = $items->id; } } elseif (isset($_GET['l']) and !empty($_GET['l']) and $_GET['l'] != 0) { $location_ids[] = (int) $_GET['l']; } // borough filtering if (isset($_GET['b']) and $_GET['b'] !== "any") { $query = 'SELECT id FROM location where borough=' . $db->escape($_GET['b']); $query = $db->query($query); $boro_ids = array(); foreach ($query as $items) { $boro_ids[] = $items->id; } if (count($boro_ids) === 0) { // no boroughs found, trigger no results for query $location_ids = array(-1); } elseif (count($location_ids) > 0) { // make locations_ids the intersection of the two $new_locids = array(); foreach ($location_ids as $locid) { if (in_array($locid, $boro_ids)) { $new_locids[] = $locid; } } $location_ids = $new_locids; } else { $location_ids = $boro_ids; } } // Get the count $incident_id_in = '1=1'; if (count($allowed_ids) > 0) { $incident_id_in = 'id IN (' . implode(',', $allowed_ids) . ')'; } $location_id_in = '1=1'; if (count($location_ids) > 0) { $location_id_in = 'location_id IN (' . implode(',', $location_ids) . ')'; } // Pagination $pagination = new Pagination(array('query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => ORM::factory("incident")->where("incident_active", 1)->where($location_id_in)->where($incident_id_in)->count_all())); // Reports if (!isset($_GET['sort']) or $_GET['sort'] === 'comments') { $loc_id_in = count($location_ids) === 0 ? "1=1" : "location.id in (" . implode(',', $location_ids) . ")"; $inc_id_in = str_replace('id', 'incident.id', $incident_id_in); $incident_query = 'SELECT incident.id, COUNT(comment.incident_id) as numcomments FROM incident LEFT JOIN comment on incident.id=comment.incident_id LEFT JOIN location on incident.location_id=location.id where incident_active=1 AND ' . $inc_id_in . ' AND ' . $loc_id_in . ' GROUP BY incident.id ORDER BY numcomments desc'; $incident_query .= ' LIMIT ' . Kohana::config('settings.items_per_page_admin') . ' OFFSET ' . $pagination->sql_offset; $incident_id_results = $db->query($incident_query); $incidents = array(); foreach ($incident_id_results as $incident) { // XXX geting each incident individually to populate the array is inefficient // but I can't figure out how to tell the orm to do this with our version of kohana $incident_obj = ORM::factory("incident")->where("id=" . $incident->id)->find_all(); if (!empty($incident_obj)) { $incidents[] = $incident_obj[0]; } } } else { $incidents = ORM::factory("incident")->where("incident_active", 1)->where($location_id_in)->where($incident_id_in)->orderby("incident_dateadd", "desc")->find_all((int) Kohana::config('settings.items_per_page_admin'), $pagination->sql_offset); } // Swap out category titles with their proper localizations using an array (cleaner way to do this?) $localized_categories = array(); foreach ($incidents as $incident) { foreach ($incident->category as $category) { $ct = (string) $category->category_title; if (!isset($localized_categories[$ct])) { $translated_title = Category_Lang_Model::category_title($category->id, $l); $localized_categories[$ct] = $category->category_title; if ($translated_title) { $localized_categories[$ct] = $translated_title; } } } } $this->template->content->localized_categories = $localized_categories; $this->template->content->incidents = $incidents; // add in person submitted information $person_submitted_info = array(); foreach ($incidents as $incident) { $incident_person = ORM::factory('incident_person')->where('incident_id', $incident->id)->find(); if ($incident_person->loaded) { $person_submitted_info[$incident->id] = array('first_name' => $incident_person->person_first, 'last_name' => $incident_person->person_last); } } $this->template->content->person_submitted_info = $person_submitted_info; //Set default as not showing pagination. Will change below if necessary. $this->template->content->pagination = ""; // Pagination and Total Num of Report Stats if ($pagination->total_items == 1) { $plural = ""; } else { $plural = "s"; } if ($pagination->total_items > 0) { $current_page = $pagination->sql_offset / (int) Kohana::config('settings.items_per_page') + 1; $total_pages = ceil($pagination->total_items / (int) Kohana::config('settings.items_per_page')); if ($total_pages > 1) { // If we want to show pagination $this->template->content->pagination_stats = Kohana::lang('ui_admin.showing_page') . ' ' . $current_page . ' ' . Kohana::lang('ui_admin.of') . ' ' . $total_pages . ' ' . Kohana::lang('ui_admin.pages'); $this->template->content->pagination = $pagination; } else { // If we don't want to show pagination $this->template->content->pagination_stats = $pagination->total_items . ' ' . Kohana::lang('ui_admin.reports'); } } else { $this->template->content->pagination_stats = '(' . $pagination->total_items . ' report' . $plural . ')'; } // this is used as text display for search results string $category_titles = array(); if ($category_ids_in) { $categories = ORM::factory('category')->where('id ' . $category_ids_in)->find_all(); foreach ($categories as $category) { $category_titles[] = $category->category_title; } } $this->template->content->category_titles = $category_titles; $scale_category = ORM::factory('category')->where('category_title', 'Scale')->find(); $context_category = ORM::factory('category')->where('category_title', 'Context')->find(); $visible_categories = ORM::factory('category')->where('parent_id IN (' . implode(",", array($scale_category->id, $context_category->id)) . ')')->find_all(); $scale_categories = array(); $context_categories = array(); foreach ($visible_categories as $visible_category) { if ($visible_category->parent_id === $scale_category->id) { $scale_categories[] = $visible_category; } elseif ($visible_category->parent_id === $context_category->id) { // design response category should be first in context list // also assuming that the design response is under the context category if ($visible_category->id === $design_response_category) { array_unshift($context_categories, $visible_category); } else { array_push($context_categories, $visible_category); } } } $this->template->content->scale_categories = $scale_categories; $this->template->content->context_categories = $context_categories; $this->template->content->selected_categories = $category_ids; // Collect report stats $this->template->content->report_stats = new View('reports_stats'); // Total Reports $total_reports = Incident_Model::get_total_reports(TRUE); // Average Reports Per Day $oldest_timestamp = Incident_Model::get_oldest_report_timestamp(); // Round the number of days up to the nearest full day $days_since = ceil((time() - $oldest_timestamp) / 86400); if ($days_since < 1) { $avg_reports_per_day = $total_reports; } else { $avg_reports_per_day = round($total_reports / $days_since, 2); } // Percent Verified $total_verified = Incident_Model::get_total_reports_by_verified(true); $percent_verified = $total_reports == 0 ? '-' : round($total_verified / $total_reports * 100, 2) . '%'; $this->template->content->report_stats->total_reports = $total_reports; $this->template->content->report_stats->avg_reports_per_day = $avg_reports_per_day; $this->template->content->report_stats->percent_verified = $percent_verified; $this->template->header->header_block = $this->themes->header_block(); }
public function index() { $this->template->header->this_page = 'home'; $this->template->content = new View('main/layout'); // Cacheable Main Controller $this->is_cachable = TRUE; // Map and Slider Blocks $div_map = new View('main/map'); $div_timeline = new View('main/timeline'); // Filter::map_main - Modify Main Map Block Event::run('ushahidi_filter.map_main', $div_map); // Filter::map_timeline - Modify Main Map Block Event::run('ushahidi_filter.map_timeline', $div_timeline); $this->template->content->div_map = $div_map; $this->template->content->div_timeline = $div_timeline; // Check if there is a site message $this->template->content->site_message = ''; $site_message = trim(Kohana::config('settings.site_message')); if ($site_message != '') { // Send the site message to both the header and the main content body // so a theme can utilize it in either spot. $this->template->content->site_message = $site_message; $this->template->header->site_message = $site_message; } // Get locale $l = Kohana::config('locale.language.0'); // Get all active top level categories $parent_categories = array(); $all_parents = ORM::factory('category')->where('category_visible', '1')->where('parent_id', '0')->find_all(); foreach ($all_parents as $category) { // Get The Children $children = array(); foreach ($category->children as $child) { $child_visible = $child->category_visible; if ($child_visible) { // Check for localization of child category $display_title = Category_Lang_Model::category_title($child->id, $l); $ca_img = $child->category_image != NULL ? url::convert_uploaded_to_abs($child->category_image) : NULL; $children[$child->id] = array($display_title, $child->category_color, $ca_img); } } // Check for localization of parent category $display_title = Category_Lang_Model::category_title($category->id, $l); // Put it all together $ca_img = $category->category_image != NULL ? url::convert_uploaded_to_abs($category->category_image) : NULL; $parent_categories[$category->id] = array($display_title, $category->category_color, $ca_img, $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 Default Color $this->template->content->default_map_all = Kohana::config('settings.default_map_all'); // Get default icon $this->template->content->default_map_all_icon = ''; if (Kohana::config('settings.default_map_all_icon_id')) { $icon_object = ORM::factory('media')->find(Kohana::config('settings.default_map_all_icon_id')); $this->template->content->default_map_all_icon = Kohana::config('upload.relative_directory') . "/" . $icon_object->media_medium; } // 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 external apps $external_apps = array(); // Catch errors, in case we have an old db try { $external_apps = ORM::factory('externalapp')->find_all(); } catch (Exception $e) { } $this->template->content->external_apps = $external_apps; // Get The START, END and Incident Dates $startDate = ""; $endDate = ""; $display_startDate = 0; $display_endDate = 0; $db = new Database(); // Next, Get the Range of Years $query = $db->query('SELECT DATE_FORMAT(incident_date, \'%Y-%c\') AS dates ' . 'FROM ' . $this->table_prefix . 'incident ' . 'WHERE incident_active = 1 ' . 'GROUP BY DATE_FORMAT(incident_date, \'%Y-%c\') ' . 'ORDER BY incident_date'); $first_year = date('Y'); $last_year = date('Y'); $first_month = 1; $last_month = 12; $i = 0; foreach ($query as $data) { $date = explode('-', $data->dates); $year = $date[0]; $month = $date[1]; // Set first year if ($i == 0) { $first_year = $year; $first_month = $month; } // Set last dates $last_year = $year; $last_month = $month; $i++; } $show_year = $first_year; $selected_start_flag = TRUE; while ($show_year <= $last_year) { $startDate .= "<optgroup label=\"" . $show_year . "\">"; $s_m = 1; if ($show_year == $first_year) { // If we are showing the first year, the starting month may not be January $s_m = $first_month; } $l_m = 12; if ($show_year == $last_year) { // If we are showing the last year, the ending month may not be December $l_m = $last_month; } for ($i = $s_m; $i <= $l_m; $i++) { if ($i < 10) { // All months need to be two digits $i = "0" . $i; } $startDate .= "<option value=\"" . strtotime($show_year . "-" . $i . "-01") . "\""; if ($selected_start_flag == TRUE) { $display_startDate = strtotime($show_year . "-" . $i . "-01"); $startDate .= " selected=\"selected\" "; $selected_start_flag = FALSE; } $startDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $show_year . "</option>"; } $startDate .= "</optgroup>"; $endDate .= "<optgroup label=\"" . $show_year . "\">"; for ($i = $s_m; $i <= $l_m; $i++) { if ($i < 10) { // All months need to be two digits $i = "0" . $i; } $endDate .= "<option value=\"" . strtotime($show_year . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59") . "\""; if ($i == $l_m and $show_year == $last_year) { $display_endDate = strtotime($show_year . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59"); $endDate .= " selected=\"selected\" "; } $endDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $show_year . "</option>"; } $endDate .= "</optgroup>"; // Show next year $show_year++; } Event::run('ushahidi_filter.active_startDate', $display_startDate); Event::run('ushahidi_filter.active_endDate', $display_endDate); Event::run('ushahidi_filter.startDate', $startDate); Event::run('ushahidi_filter.endDate', $endDate); $this->template->content->div_timeline->startDate = $startDate; $this->template->content->div_timeline->endDate = $endDate; // Javascript Header $this->themes->map_enabled = TRUE; $this->themes->slider_enabled = TRUE; if (Kohana::config('settings.enable_timeline')) { $this->themes->timeline_enabled = TRUE; } // Map Settings $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->themes->js = new View('main/main_js'); $this->themes->js->marker_radius = ($marker_radius >= 1 and $marker_radius <= 10) ? $marker_radius : 5; $this->themes->js->marker_opacity = ($marker_opacity >= 1 and $marker_opacity <= 10) ? $marker_opacity * 0.1 : 0.9; $this->themes->js->marker_stroke_width = ($marker_stroke_width >= 1 and $marker_stroke_width <= 5) ? $marker_stroke_width : 2; $this->themes->js->marker_stroke_opacity = ($marker_stroke_opacity >= 1 and $marker_stroke_opacity <= 10) ? $marker_stroke_opacity * 0.1 : 0.9; $this->themes->js->active_startDate = $display_startDate; $this->themes->js->active_endDate = $display_endDate; $this->themes->js->blocks_per_row = Kohana::config('settings.blocks_per_row'); }
public function index() { $this->template->header->this_page = 'bigmap'; $this->template->content = new View('adminmap/print_mapview'); //set the CSS for this plugin::add_stylesheet("adminmap/css/print_adminmap"); plugin::add_stylesheet("adminmap/css/jquery.hovertip-1.0"); //make sure the right java script files are used. plugin::add_javascript("adminmap/js/jquery.address-1.4.min.js"); plugin::add_javascript("adminmap/js/jquery.flot"); plugin::add_javascript("adminmap/js/excanvas.min"); plugin::add_javascript("adminmap/js/timeline"); plugin::add_javascript("adminmap/js/jquery.hovertip-1.0"); // Cacheable Main Controller $this->is_cachable = TRUE; // Map and Slider Blocks $div_map = new View('adminmap/big_main_map'); $div_timeline = new View('adminmap/print_main_timeline'); // Filter::map_main - Modify Main Map Block Event::run('ushahidi_filter.map_main', $div_map); // Filter::map_timeline - Modify Main Map Block Event::run('ushahidi_filter.map_timeline', $div_timeline); $this->template->content->div_map = $div_map; $this->template->content->div_timeline = $div_timeline; // Get locale $l = Kohana::config('locale.language.0'); // 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) { // Check for localization of child category $translated_title = Category_Lang_Model::category_title($child->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children[$child->id] = array($display_title, $child->category_color, $child->category_image); if ($child->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $child->id); if (!$trusted->count_all()) { unset($children[$child->id]); } } } // Check for localization of parent category $translated_title = Category_Lang_Model::category_title($category->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $category->category_title; } // Put it all together $parent_categories[$category->id] = array($display_title, $category->category_color, $category->category_image, $children); if ($category->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $category->id); if (!$trusted->count_all()) { unset($parent_categories[$category->id]); } } } $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)->find_all() as $share) { $shares[$share->id] = array($share->sharing_name, $share->sharing_color); } $this->template->content->shares = $shares; // Get Default Color $this->template->content->default_map_all = Kohana::config('settings.default_map_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"); } //run some custom events for the timeline plugin Event::run('ushahidi_filter.active_startDate', $active_startDate); Event::run('ushahidi_filter.active_endDate', $active_endDate); Event::run('ushahidi_filter.active_month', $active_month); // 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>"; } //run more custom events for the timeline plugin Event::run('ushahidi_filter.startDate', $startDate); Event::run('ushahidi_filter.endDate', $endDate); $this->template->content->div_timeline->startDate = $startDate; $this->template->content->div_timeline->endDate = $endDate; // Javascript Header $this->themes->map_enabled = true; $this->themes->main_page = 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->themes->js = new View('adminmap/print_mapview_js'); $this->themes->js->json_url = $clustering == 1 ? "json/cluster" : "json"; $this->themes->js->marker_radius = $marker_radius >= 1 && $marker_radius <= 10 ? $marker_radius : 5; $this->themes->js->marker_opacity = $marker_opacity >= 1 && $marker_opacity <= 10 ? $marker_opacity * 0.1 : 0.9; $this->themes->js->marker_stroke_width = $marker_stroke_width >= 1 && $marker_stroke_width <= 5 ? $marker_stroke_width : 2; $this->themes->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->themes->js->numZoomLevels = $numZoomLevels; $this->themes->js->minZoomLevel = $minZoomLevel; $this->themes->js->maxZoomLevel = $maxZoomLevel; // pdestefanis - allows to limit the extents of the map $this->themes->js->lonFrom = $lonFrom; $this->themes->js->latFrom = $latFrom; $this->themes->js->lonTo = $lonTo; $this->themes->js->latTo = $latTo; $this->themes->js->default_map = Kohana::config('settings.default_map'); $this->themes->js->default_zoom = Kohana::config('settings.default_zoom'); $this->themes->js->latitude = Kohana::config('settings.default_lat'); $this->themes->js->longitude = Kohana::config('settings.default_lon'); $this->themes->js->default_map_all = Kohana::config('settings.default_map_all'); // $this->themes->js->active_startDate = $active_startDate; $this->themes->js->active_endDate = $active_endDate; //$myPacker = new javascriptpacker($js , 'Normal', false, false); //$js = $myPacker->pack(); // Rebuild Header Block $this->template->header->header_block = $this->themes->header_block(); }
/** * Helper method for adding parent categories to the category data * * @param array $array Pointer to the array containing the category data * @param mixed $category Object Category object to be added tot he array */ private static function _extend_category_data(array &$array, $category) { // Check if the category is a top-level parent category $temp_category = $category->parent_id == 0 ? $category : ORM::factory('category', $category->parent_id); if ($temp_category instanceof Category_Model and !$temp_category->loaded) { return FALSE; } // Extend the array if (!array_key_exists($temp_category->id, $array)) { // Get the report count $report_count = property_exists($temp_category, 'report_count') ? $temp_category->report_count : 0; $array[$temp_category->id] = array('category_title' => Category_Lang_Model::category_title($temp_category->id, Kohana::config('locale.language.0')), 'parent_id' => $temp_category->parent_id, 'category_color' => $temp_category->category_color, 'report_count' => $report_count, 'children' => array()); return TRUE; } return FALSE; }
?> </span> </a> <?php } else { ?> <a class="r_category" href="<?php echo url::site("reports/?c={$category->id}"); ?> "> <span class="r_cat-box" style="background-color:#<?php echo $category->category_color; ?> ;"></span> <span class="r_cat-desc"><?php echo Category_Lang_Model::category_title($category->id); ?> </span> </a> <?php } ?> <?php } ?> </div> <?php // Action::report_extra_media - Add items to the report list in the media section Event::run('ushahidi_action.report_extra_media', $incident_id); ?> </div>
} elseif ($incident_mode == 3) { $submit_mode = "EMAIL"; $submit_by = $incident_orm->message->message_from; } elseif ($incident_mode == 4) { $submit_mode = "TWITTER"; $submit_by = $incident_orm->message->message_from; } // Get the country name $country_name = $incident->country_id != 0 ? $countries[$incident->country_id] : $countries[Kohana::config('settings.default_country')]; // Incident location $incident_location = $incident->location_id ? $incident->location_name . ', ' . $country_name : Kohana::lang('ui_main.none'); // Retrieve Incident Categories $incident_category = ""; if ($incident_orm->incident_category->count() > 0) { foreach ($incident_orm->incident_category as $category) { $incident_category .= Category_Lang_Model::category_title($category->category_id) . " "; } } else { $incident_category .= Kohana::lang('ui_main.none'); } // Incident Status $incident_approved = $incident->incident_active; $incident_verified = $incident->incident_verified; // Get Edit Log $edit_count = $incident_orm->verify->count(); $edit_css = $edit_count == 0 ? "post-edit-log-gray" : "post-edit-log-blue"; $edit_log = "<div class=\"" . $edit_css . "\">" . "<a href=\"javascript:showLog('edit_log_" . $incident_id . "')\">" . Kohana::lang('ui_admin.edit_log') . ":</a> (" . $edit_count . ")</div>" . "<div id=\"edit_log_" . $incident_id . "\" class=\"post-edit-log\"><ul>"; foreach ($incident_orm->verify as $verify) { $edit_log .= "<li>" . Kohana::lang('ui_admin.edited_by') . " " . html::specialchars($verify->user->name) . " : " . $verify->verified_date . "</li>"; } $edit_log .= "</ul></div>";
/** * Helper method to load the report listing view */ private function _get_report_listing_view($locale = '') { // Check if the local is empty if (empty($locale)) { $locale = Kohana::config('locale.language.0'); } // Load the report listing view $report_listing = new View('reports_listing'); // Fetch all incidents $all_incidents = reports::fetch_incidents(); // Pagination $pagination = new Pagination(array('style' => 'front-end-reports', 'query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => $all_incidents->count())); // Reports $incidents = Incident_Model::get_incidents(reports::$params, $pagination); // Swap out category titles with their proper localizations using an array (cleaner way to do this?) $localized_categories = array(); foreach ($incidents as $incident) { $incident = ORM::factory('incident', $incident->incident_id); foreach ($incident->category as $category) { $ct = (string) $category->category_title; if (!isset($localized_categories[$ct])) { $translated_title = Category_Lang_Model::category_title($category->id, $locale); $localized_categories[$ct] = $category->category_title; if ($translated_title) { $localized_categories[$ct] = $translated_title; } } } } // Set the view content $report_listing->incidents = $incidents; $report_listing->localized_categories = $localized_categories; //Set default as not showing pagination. Will change below if necessary. $report_listing->pagination = ""; // Pagination and Total Num of Report Stats $plural = $pagination->total_items == 1 ? "" : "s"; // Set the next and previous page numbers $report_listing->next_page = $pagination->next_page; $report_listing->previous_page = $pagination->previous_page; if ($pagination->total_items > 0) { $current_page = $pagination->sql_offset / $pagination->items_per_page + 1; $total_pages = ceil($pagination->total_items / $pagination->items_per_page); if ($total_pages >= 1) { $report_listing->pagination = $pagination; // Show the total of report // @todo This is only specific to the frontend reports theme $report_listing->stats_breadcrumb = $pagination->current_first_item . '-' . $pagination->current_last_item . ' of ' . $pagination->total_items . ' ' . Kohana::lang('ui_main.reports'); } else { // If we don't want to show pagination $report_listing->stats_breadcrumb = $pagination->total_items . ' ' . Kohana::lang('ui_admin.reports'); } } else { $report_listing->stats_breadcrumb = '(' . $pagination->total_items . ' report' . $plural . ')'; } // Return return $report_listing; }
/** * Add Edit Categories */ public function index() { $this->template->content = new View('admin/categories'); $this->template->content->title = Kohana::lang('ui_admin.categories'); // Locale (Language) Array $locales = ush_locale::get_i18n(); // Setup and initialize form field names $form = array('action' => '', 'category_id' => '', 'parent_id' => '', 'category_title' => '', 'category_description' => '', 'category_color' => '', 'category_image' => '', 'category_image_thumb' => '', 'form_auth_token' => ''); // Add the different language form keys for fields foreach ($locales as $lang_key => $lang_name) { $form['category_title_' . $lang_key] = ''; } // Copy the form as errors, so the errors will be stored with keys corresponding to the form field names $errors = $form; $form_error = FALSE; $form_saved = FALSE; $form_action = ""; $parents_array = array(); // Check, has the form been submitted, if so, setup validation if ($_POST) { // Fetch the post data $post_data = array_merge($_POST, $_FILES); // Extract category-specific information $category_data = arr::extract($post_data, 'parent_id', 'category_title', 'category_description', 'category_color'); // Extract category image and category languages for independent validation $secondary_data = arr::extract($post_data, 'category_image', 'category_title_lang', 'action'); // Setup validation for the secondary data $post = Validation::factory($secondary_data)->pre_filter('trim', TRUE); // Add validation for the add/edit action if ($post->action == 'a') { $post->add_rules('category_image', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[50K]'); // Add the different language form keys for fields foreach ($locales as $lang_key => $lang_name) { $post->add_rules('category_title_lang[' . $lang_key . ']', 'length[3,80]'); } } // Category instance for the operation $category = (!empty($_POST['category_id']) and Category_Model::is_valid_category($_POST['category_id'])) ? new Category_Model($_POST['category_id']) : new Category_Model(); // Check the specified action if ($post->action == 'a') { // Test to see if things passed the rule checks if ($category->validate($category_data) and $post->validate(FALSE)) { // Save the category $category->save(); // Get the category localization $languages = $category->loaded ? Category_Lang_Model::category_langs($category->id) : FALSE; $category_lang = isset($languages[$category->id]) ? $languages[$category->id] : FALSE; // Save localizations foreach ($post->category_title_lang as $lang_key => $localized_category_name) { $cl = isset($category_lang[$lang_key]['id']) ? ORM::factory('category_lang', $category_lang[$lang_key]['id']) : ORM::factory('category_lang'); $cl->category_title = $localized_category_name; $cl->locale = $lang_key; $cl->category_id = $category->id; $cl->save(); } // Upload Image/Icon $filename = upload::save('category_image'); if ($filename) { $new_filename = "category_" . $category->id . "_" . time(); // Name the files for the DB $cat_img_file = $new_filename . ".png"; $cat_img_thumb_file = $new_filename . "_16x16.png"; // Resize Image to 32px if greater Image::factory($filename)->resize(32, 32, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $cat_img_file); // Create a 16x16 version too Image::factory($filename)->resize(16, 16, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $cat_img_thumb_file); // Okay, now we have these three different files on the server, now check to see // if we should be dropping them on the CDN if (Kohana::config("cdn.cdn_store_dynamic_content")) { $cat_img_file = cdn::upload($cat_img_file); $cat_img_thumb_file = cdn::upload($cat_img_thumb_file); // We no longer need the files we created on the server. Remove them. $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/'; unlink($local_directory . $new_filename . ".png"); unlink($local_directory . $new_filename . "_16x16.png"); } // Remove the temporary file unlink($filename); // Delete Old Image $category_old_image = $category->category_image; if (!empty($category_old_image)) { if (file_exists(Kohana::config('upload.directory', TRUE) . $category_old_image)) { unlink(Kohana::config('upload.directory', TRUE) . $category_old_image); } elseif (Kohana::config("cdn.cdn_store_dynamic_content") and valid::url($category_old_image)) { cdn::delete($category_old_image); } } // Save $category->category_image = $cat_img_file; $category->category_image_thumb = $cat_img_thumb_file; $category->save(); Event::run('ushahidi_action.category_save', $post); } $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.added_edited')); // Empty $form array array_fill_keys($form, ''); } else { // Validation failed // Repopulate the form fields $form = arr::overwrite($form, array_merge($category_data->as_array(), $post->as_array())); // populate the error fields, if any $errors = arr::overwrite($errors, array_merge($category_data->errors('category'), $post->errors('category'))); $form_error = TRUE; } } elseif ($post->action == 'd' and $post->validate()) { // Delete action if ($category->loaded) { ORM::factory('category_lang')->where(array('category_id' => $category->id))->delete_all(); // Check for all subcategories tied to this category and make them top level $children = ORM::factory('category')->where('parent_id', $category->id)->find_all(); if ($children) { foreach ($children as $child) { $sub_cat = new Category_Model($child->id); $sub_cat->parent_id = 0; $sub_cat->save(); } } // Check for all reports tied to this category to be deleted $result = ORM::factory('incident_category')->where('category_id', $category->id)->find_all(); // If there are reports returned by the query if ($result) { foreach ($result as $orphan) { $orphan_incident_id = $orphan->incident_id; // Check if the report is tied to any other category $count = ORM::factory('incident_category')->where('incident_id', $orphan_incident_id)->count_all(); // If this report is tied to only one category(is uncategorized) if ($count == 1) { // Assign it to the special category for uncategorized reports $orphaned = ORM::factory('incident_category', $orphan->id); $orphaned->category_id = 5; $orphaned->save(); // Deactivate the report so that it's not accessible on the frontend $orphaned_report = ORM::factory('incident', $orphan_incident_id); $orphaned_report->incident_active = 0; $orphaned_report->save(); } else { ORM::factory('incident_category')->delete($orphan->id); } } } // @todo Delete the category image // Delete category itself - except if it is trusted ORM::factory('category')->where('category_trusted != 1')->delete($category->id); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.deleted')); } } elseif ($post->action == 'v' and $post->validate()) { // Show/Hide Action if ($category->loaded) { // Check for all subcategories tied to this category $children = ORM::factory('category')->where('parent_id', $category->id)->find_all(); // Then show/hide subcategories based on status of parent category foreach ($children as $child) { $sub_cat = new Category_Model($child->id); $sub_cat->category_visible = $category->category_visible == 1 ? 0 : 1; $sub_cat->save(); } // Change status of the Parent Category $category->category_visible = $category->category_visible == 1 ? 0 : 1; $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } elseif ($post->action == 'i' and $post->validate()) { // Delete Image/Icon Action if ($category->loaded) { $category_image = $category->category_image; $category_image_thumb = $category->category_image_thumb; // Delete the main image if (!empty($category_image) and file_exists(Kohana::config('upload.directory', TRUE) . $category_image)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image); } // Delete the thumb if (!empty($category_image_thumb) and file_exists(Kohana::config('upload.directory', TRUE) . $category_image_thumb)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image_thumb); } $category->category_image = NULL; $category->category_image_thumb = NULL; $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } } // Pagination $pagination = new Pagination(array('query_string' => 'page', 'items_per_page' => $this->items_per_page, 'total_items' => ORM::factory('category')->where('parent_id', '0')->count_all())); $categories = ORM::factory('category')->with('category_lang')->where('parent_id', '0')->orderby('category_title', 'asc')->find_all($this->items_per_page, $pagination->sql_offset); $parents_array = ORM::factory('category')->where('parent_id', '0')->where('category_trusted != 1')->select_list('id', 'category_title'); // add none to the list $parents_array[0] = "--- Top Level Category ---"; // Put "--- Top Level Category ---" at the top of the list ksort($parents_array); $this->template->content->form = $form; $this->template->content->errors = $errors; $this->template->content->form_error = $form_error; $this->template->content->form_saved = $form_saved; $this->template->content->form_action = $form_action; $this->template->content->pagination = $pagination; $this->template->content->total_items = $pagination->total_items; $this->template->content->categories = $categories; $this->template->content->parents_array = $parents_array; // Javascript Header $this->template->colorpicker_enabled = TRUE; $this->template->tablerowsort_enabled = TRUE; $this->template->js = new View('admin/categories_js'); $this->template->form_error = $form_error; $this->template->content->locale_array = $locales; $this->template->js->locale_array = $locales; }
public function index() { $this->template->header->this_page = 'home'; $this->template->content = new View('main'); // Cacheable Main Controller $this->is_cachable = TRUE; // Map and Slider Blocks $div_map = new View('main_map'); $div_timeline = new View('main_timeline'); // Filter::map_main - Modify Main Map Block Event::run('ushahidi_filter.map_main', $div_map); // Filter::map_timeline - Modify Main Map Block Event::run('ushahidi_filter.map_timeline', $div_timeline); $this->template->content->div_map = $div_map; $this->template->content->div_timeline = $div_timeline; // Check if there is a site message $this->template->content->site_message = ''; $site_message = trim(Kohana::config('settings.site_message')); if($site_message != '') { $this->template->content->site_message = $site_message; } // Get locale $l = Kohana::config('locale.language.0'); // Get all active top level categories $parent_categories = array(); $parentCategoryId = 0; foreach ( Category_Model::getCategories($parentCategoryId) as $category ) { // Get The Children $children = array(); foreach ($category->children as $child) { // Check for localization of child category $translated_title = Category_Lang_Model::category_title($child->id,$l); if($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children[$child->id] = array( $display_title, $child->category_color, $child->category_image ); if ($child->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident") ->join("incident_category","incident.id","incident_category.incident_id") ->where("category_id",$child->id); if ( ! $trusted->count_all()) { unset($children[$child->id]); } } } // Check for localization of parent category $translated_title = Category_Lang_Model::category_title($category->id,$l); if($translated_title) { $display_title = $translated_title; }else{ $display_title = $category->category_title; } // Put it all together $parent_categories[$category->id] = array( $display_title, $category->category_color, $category->category_image, $children ); if ($category->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident") ->join("incident_category","incident.id","incident_category.incident_id") ->where("category_id",$category->id); if ( ! $trusted->count_all()) { unset($parent_categories[$category->id]); } } } $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) ->find_all() as $share) { $shares[$share->id] = array($share->sharing_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') ->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 $feed_arrays = ORM::factory('feed') ->where('feed_active',1) ->limit('10') ->orderby('feed_update', 'asc') ->find_all(); $feeds = array(); foreach($feed_arrays as $val){ $feeds[]=array("id"=>$val->id,"name"=>$val->feed_name,"url"=>$val->feed_url); } foreach($feeds as $key => $this_feed){ $feeds[$key]["feed_item"] = ORM::factory('feed_item') ->limit('10') ->where('feed_id',$this_feed["id"]) ->orderby('item_date', 'desc') ->find_all(); } $this->template->content->feeds = $feeds; // コメントつきインシデント取得 $db = new Database; $query = 'SELECT incident_id FROM '.$this->table_prefix.'comment AS ic WHERE ic.comment_active = 1 GROUP BY incident_id ORDER BY MAX(comment_date) DESC LIMIT 0,20;'; $query = $db->query($query); $incident_ids = array(); foreach($query as $items){ $incident_ids[$items->incident_id] =$items->incident_id; } $incident_ids_in = '1=1'; if (count($incident_ids) > 0) { $incident_ids_in = 'incident.id IN ('.implode(',',$incident_ids).')'; } $this->template->content->comment_incidents = ORM::factory('incident') ->select($this->table_prefix.'incident.*,'.$this->table_prefix.'comment.id as comment_id,'.$this->table_prefix.'comment.comment_date') ->join($this->table_prefix.'comment',$this->table_prefix.'comment.incident_id',$this->table_prefix.'incident.id',"LEFT") ->where('incident_active', '1') ->where($incident_ids_in) ->orderby('comment_date', 'desc') ->limit('10') ->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->div_timeline->startDate = $startDate; $this->template->content->div_timeline->endDate = $endDate; // Javascript Header $this->themes->map_enabled = TRUE; $this->themes->main_page = 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->themes->js = new View('main_js'); $this->themes->js->json_url = ($clustering == 1) ? "json/cluster" : "json"; $this->themes->js->marker_radius = ($marker_radius >=1 && $marker_radius <= 10 ) ? $marker_radius : 5; $this->themes->js->marker_opacity = ($marker_opacity >=1 && $marker_opacity <= 10 ) ? $marker_opacity * 0.1 : 0.9; $this->themes->js->marker_stroke_width = ($marker_stroke_width >=1 && $marker_stroke_width <= 5 ) ? $marker_stroke_width : 2; $this->themes->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->themes->js->numZoomLevels = $numZoomLevels; $this->themes->js->minZoomLevel = $minZoomLevel; $this->themes->js->maxZoomLevel = $maxZoomLevel; // pdestefanis - allows to limit the extents of the map $this->themes->js->lonFrom = $lonFrom; $this->themes->js->latFrom = $latFrom; $this->themes->js->lonTo = $lonTo; $this->themes->js->latTo = $latTo; $this->themes->js->default_map = Kohana::config('settings.default_map'); $this->themes->js->default_zoom = Kohana::config('settings.default_zoom'); $this->themes->js->latitude = Kohana::config('settings.default_lat'); $this->themes->js->longitude = Kohana::config('settings.default_lon'); $this->themes->js->default_map_all = Kohana::config('settings.default_map_all'); // $this->themes->js->active_startDate = $active_startDate; $this->themes->js->active_endDate = $active_endDate; //$myPacker = new javascriptpacker($js , 'Normal', false, false); //$js = $myPacker->pack(); // Rebuild Header Block $this->template->header->header_block = $this->themes->header_block(); }
public function index() { $this->template->header->this_page = 'home'; $this->template->content = new View('main'); // Cacheable Main Controller $this->is_cachable = TRUE; // Map and Slider Blocks $div_map = new View('main_map'); $div_timeline = new View('main_timeline'); // Filter::map_main - Modify Main Map Block Event::run('ushahidi_filter.map_main', $div_map); // Filter::map_timeline - Modify Main Map Block Event::run('ushahidi_filter.map_timeline', $div_timeline); $this->template->content->div_map = $div_map; $this->template->content->div_timeline = $div_timeline; // Check if there is a site message $this->template->content->site_message = ''; $site_message = trim(Kohana::config('settings.site_message')); if ($site_message != '') { $this->template->content->site_message = $site_message; } // Get locale $l = Kohana::config('locale.language.0'); // Get all active top level categories $parent_categories = array(); foreach (ORM::factory('category')->where('category_visible', '1')->where('parent_id', '0')->orderby('category_position', 'asc')->find_all() as $category) { // Get The Children $children = array(); foreach ($category->orderby('category_position', 'asc')->children as $child) { $child_visible = $child->category_visible; if ($child_visible) { // Check for localization of child category $display_title = Category_Lang_Model::category_title($child->id, $l); $ca_img = $child->category_image != NULL ? url::convert_uploaded_to_abs($child->category_image) : NULL; $children[$child->id] = array($display_title, $child->category_color, $ca_img); if ($child->category_trusted) { // Get Trusted Category Count $trusted = $this->get_trusted_category_count($child->id); if (!$trusted->count_all()) { unset($children[$child->id]); } } } } // Check for localization of parent category $display_title = Category_Lang_Model::category_title($category->id, $l); // Put it all together $ca_img = $category->category_image != NULL ? url::convert_uploaded_to_abs($category->category_image) : NULL; $parent_categories[$category->id] = array($display_title, $category->category_color, $ca_img, $children); if ($category->category_trusted) { // Get Trusted Category Count $trusted = $this->get_trusted_category_count($category->id); if (!$trusted->count_all()) { unset($parent_categories[$category->id]); } } } $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)->find_all() as $share) { $shares[$share->id] = array($share->sharing_name, $share->sharing_color); } $this->template->content->shares = $shares; // 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 The START, END and Incident Dates $startDate = ""; $endDate = ""; $display_startDate = 0; $display_endDate = 0; $db = new Database(); // Next, Get the Range of Years $query = $db->query('SELECT DATE_FORMAT(incident_date, \'%Y-%c\') AS dates FROM ' . $this->table_prefix . 'incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_date, \'%Y-%c\') ORDER BY incident_date'); $first_year = date('Y'); $last_year = date('Y'); $first_month = 1; $last_month = 12; $i = 0; foreach ($query as $data) { $date = explode('-', $data->dates); $year = $date[0]; $month = $date[1]; // Set first year if ($i == 0) { $first_year = $year; $first_month = $month; } // Set last dates $last_year = $year; $last_month = $month; $i++; } $show_year = $first_year; $selected_start_flag = TRUE; while ($show_year <= $last_year) { $startDate .= "<optgroup label=\"" . $show_year . "\">"; $s_m = 1; if ($show_year == $first_year) { // If we are showing the first year, the starting month may not be January $s_m = $first_month; } $l_m = 12; if ($show_year == $last_year) { // If we are showing the last year, the ending month may not be December $l_m = $last_month; } for ($i = $s_m; $i <= $l_m; $i++) { if ($i < 10) { // All months need to be two digits $i = "0" . $i; } $startDate .= "<option value=\"" . strtotime($show_year . "-" . $i . "-01") . "\""; if ($selected_start_flag == TRUE) { $display_startDate = strtotime($show_year . "-" . $i . "-01"); $startDate .= " selected=\"selected\" "; $selected_start_flag = FALSE; } $startDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $show_year . "</option>"; } $startDate .= "</optgroup>"; $endDate .= "<optgroup label=\"" . $show_year . "\">"; for ($i = $s_m; $i <= $l_m; $i++) { if ($i < 10) { // All months need to be two digits $i = "0" . $i; } $endDate .= "<option value=\"" . strtotime($show_year . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59") . "\""; if ($i == $l_m and $show_year == $last_year) { $display_endDate = strtotime($show_year . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59"); $endDate .= " selected=\"selected\" "; } $endDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $show_year . "</option>"; } $endDate .= "</optgroup>"; // Show next year $show_year++; } Event::run('ushahidi_filter.active_startDate', $display_startDate); Event::run('ushahidi_filter.active_endDate', $display_endDate); Event::run('ushahidi_filter.startDate', $startDate); Event::run('ushahidi_filter.endDate', $endDate); $this->template->content->div_timeline->startDate = $startDate; $this->template->content->div_timeline->endDate = $endDate; // Javascript Header $this->themes->map_enabled = TRUE; $this->themes->main_page = 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->themes->js = new View('main_js'); $this->themes->js->json_url = $clustering == 1 ? "json/cluster" : "json"; $this->themes->js->marker_radius = $marker_radius >= 1 && $marker_radius <= 10 ? $marker_radius : 5; $this->themes->js->marker_opacity = $marker_opacity >= 1 && $marker_opacity <= 10 ? $marker_opacity * 0.1 : 0.9; $this->themes->js->marker_stroke_width = $marker_stroke_width >= 1 && $marker_stroke_width <= 5 ? $marker_stroke_width : 2; $this->themes->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->themes->js->numZoomLevels = $numZoomLevels; $this->themes->js->minZoomLevel = $minZoomLevel; $this->themes->js->maxZoomLevel = $maxZoomLevel; // pdestefanis - allows to limit the extents of the map $this->themes->js->lonFrom = $lonFrom; $this->themes->js->latFrom = $latFrom; $this->themes->js->lonTo = $lonTo; $this->themes->js->latTo = $latTo; $this->themes->js->default_map = Kohana::config('settings.default_map'); $this->themes->js->default_zoom = Kohana::config('settings.default_zoom'); $this->themes->js->latitude = Kohana::config('settings.default_lat'); $this->themes->js->longitude = Kohana::config('settings.default_lon'); $this->themes->js->default_map_all = Kohana::config('settings.default_map_all'); $this->themes->js->active_startDate = $display_startDate; $this->themes->js->active_endDate = $display_endDate; $this->themes->js->blocks_per_row = Kohana::config('settings.blocks_per_row'); //$myPacker = new javascriptpacker($js , 'Normal', false, false); //$js = $myPacker->pack(); // Rebuild Header Block $this->template->header->header_block = $this->themes->header_block(); }
} ?> </div> <?php } ?> </td> </tr> <?php // Get All Category Children foreach ($category->children as $child) { $category_id = $child->id; $parent_id = $child->parent_id; $category_title = Category_Lang_Model::category_title($category_id); $category_description = substr(Category_Lang_Model::category_description($category_id), 0, 150); $category_color = $child->category_color; $category_image = $child->category_image != NULL ? url::convert_uploaded_to_abs($child->category_image) : NULL; $category_visible = $child->category_visible; $fillFields = array(); $fillFields['category_id'] = $child->id; $fillFields['parent_id'] = $child->parent_id; $fillFields['category_title'] = $child->category_title; $fillFields['category_description'] = $child->category_description; $fillFields['category_color'] = $child->category_color; $fillFields['category_image'] = $child->category_image; $fillFields['locale'] = $category->locale; $fillFields['category_langs'] = array(); foreach ($child->category_lang as $category_lang) { $fillFields['category_langs'][$category_lang->locale] = array('category_title' => $category_lang->category_title, 'category_description' => $category_lang->category_description); }
/** * Helper method to load the report listing view */ private function _get_report_listing_view($locale = '') { // Check if the local is empty if (empty($locale)) { $locale = Kohana::config('locale.language.0'); } // Load the report listing view $report_listing = new View('reports/list'); // Fetch all incidents $incidents = reports::fetch_incidents(TRUE); // Pagination $pagination = reports::$pagination; // For compatibility with older custom themes: // Generate array of category titles with their proper localizations using an array // DO NOT use this in new code, call Category_Lang_Model::category_title() directly foreach (Category_Model::categories() as $category) { $localized_categories[$category['category_title']] = Category_Lang_Model::category_title($category['category_id']); } // Set the view content $report_listing->incidents = $incidents; $report_listing->localized_categories = $localized_categories; //Set default as not showing pagination. Will change below if necessary. $report_listing->pagination = ""; // Pagination and Total Num of Report Stats $plural = $pagination->total_items == 1 ? "" : "s"; // Set the next and previous page numbers $report_listing->next_page = $pagination->next_page; $report_listing->previous_page = $pagination->previous_page; if ($pagination->total_items > 0) { $current_page = $pagination->sql_offset / $pagination->items_per_page + 1; $total_pages = ceil($pagination->total_items / $pagination->items_per_page); if ($total_pages >= 1) { $report_listing->pagination = $pagination; // Show the total of report // @todo This is only specific to the frontend reports theme $report_listing->stats_breadcrumb = $pagination->current_first_item . '-' . $pagination->current_last_item . ' of ' . $pagination->total_items . ' ' . Kohana::lang('ui_main.reports'); } else { // If we don't want to show pagination $report_listing->stats_breadcrumb = $pagination->total_items . ' ' . Kohana::lang('ui_admin.reports'); } } else { $report_listing->stats_breadcrumb = '(' . $pagination->total_items . ' report' . $plural . ')'; } // Return return $report_listing; }
$category_description = html::escape(Category_Lang_Model::category_description($category)); $color_css = 'class="category-icon swatch" style="background-color:#' . $category_color . '"'; if ($category_info[2] != NULL) { $category_image = html::image(array('src' => $category_image)); $color_css = 'class="category-icon"'; } echo '<li>' . '<a href="#" id="cat_' . $category . '" title="' . $category_description . '">' . '<span ' . $color_css . '>' . $category_image . '</span>' . '<span class="category-title">' . $category_title . '</span>' . '</a>'; // Get Children echo '<div class="hide" id="child_' . $category . '">'; if (sizeof($category_info[3]) != 0) { echo '<ul>'; foreach ($category_info[3] as $child => $child_info) { $child_title = html::escape($child_info[0]); $child_color = $child_info[1]; $child_image = $child_info[2] != NULL ? url::convert_uploaded_to_abs($child_info[2]) : NULL; $child_description = html::escape(Category_Lang_Model::category_description($child)); $color_css = 'class="category-icon swatch" style="background-color:#' . $child_color . '"'; if ($child_info[2] != NULL) { $child_image = html::image(array('src' => $child_image)); $color_css = 'class="category-icon"'; } echo '<li>' . '<a href="#" id="cat_' . $child . '" title="' . $child_description . '">' . '<span ' . $color_css . '>' . $child_image . '</span>' . '<span class="category-title">' . $child_title . '</span>' . '</a>' . '</li>'; } echo '</ul>'; } echo '</div></li>'; } ?> </ul> <?php }
$category_description = htmlentities(Category_Lang_Model::category_description($category), ENT_QUOTES, "UTF-8"); $color_css = 'class="category-icon swatch" style="background-color:#' . $category_color . '"'; if ($category_info[2] != NULL) { $category_image = html::image(array('src' => $category_image)); $color_css = 'class="category-icon"'; } echo '<li>' . '<a href="#" id="cat_' . $category . '" title="' . $category_description . '">' . '<span ' . $color_css . '>' . $category_image . '</span>' . '<span class="category-title">' . $category_title . '</span>' . '</a>'; // Get Children echo '<div class="hide" id="child_' . $category . '">'; if (sizeof($category_info[3]) != 0) { echo '<ul>'; foreach ($category_info[3] as $child => $child_info) { $child_title = htmlentities($child_info[0], ENT_QUOTES, "UTF-8"); $child_color = $child_info[1]; $child_image = $child_info[2] != NULL ? url::convert_uploaded_to_abs($child_info[2]) : NULL; $child_description = htmlentities(Category_Lang_Model::category_description($child), ENT_QUOTES, "UTF-8"); $color_css = 'class="category-icon swatch" style="background-color:#' . $child_color . '"'; if ($child_info[2] != NULL) { $child_image = html::image(array('src' => $child_image)); $color_css = 'class="category-icon"'; } echo '<li>' . '<a href="#" id="cat_' . $child . '" title="' . $child_description . '">' . '<span ' . $color_css . '>' . $child_image . '</span>' . '<span class="category-title">' . $child_title . '</span>' . '</a>' . '</li>'; } echo '</ul>'; } echo '</div></li>'; } ?> </ul> <!-- / category filters -->
public function index($width = 400) { $this->template->header->this_page = 'bigmap'; $this->template->content = new View('adminmap/iframe_mapview'); $this->template->content->site_name = $this->template->header->site_name; //set the CSS for this plugin::add_stylesheet("adminmap/css/iframe_adminmap"); plugin::add_stylesheet("adminmap/css/jquery.hovertip-1.0"); //make sure the right java script files are used. //plugin::add_javascript("adminmap/js/jquery.address-1.4.min.js"); plugin::add_javascript("adminmap/js/jquery.flot"); plugin::add_javascript("adminmap/js/excanvas.min"); plugin::add_javascript("adminmap/js/timeline"); plugin::add_javascript("adminmap/js/jquery.hovertip-1.0"); // Cacheable Main Controller $this->is_cachable = TRUE; // Map and Slider Blocks $div_timeline = new View('adminmap/iframe_main_timeline'); // Filter::map_timeline - Modify Main Map Block Event::run('ushahidi_filter.map_timeline', $div_timeline); $this->template->content->div_timeline = $div_timeline; $this->template->content->width = $width; // Get locale $l = Kohana::config('locale.language.0'); // 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) { // Check for localization of child category $translated_title = Category_Lang_Model::category_title($child->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $child->category_title; } $children[$child->id] = array($display_title, $child->category_color, $child->category_image); if ($child->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $child->id); if (!$trusted->count_all()) { unset($children[$child->id]); } } } // Check for localization of parent category $translated_title = Category_Lang_Model::category_title($category->id, $l); if ($translated_title) { $display_title = $translated_title; } else { $display_title = $category->category_title; } // Put it all together $parent_categories[$category->id] = array($display_title, $category->category_color, $category->category_image, $children); if ($category->category_trusted) { // Get Trusted Category Count $trusted = ORM::factory("incident")->join("incident_category", "incident.id", "incident_category.incident_id")->where("category_id", $category->id); if (!$trusted->count_all()) { unset($parent_categories[$category->id]); } } } $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)->find_all() as $share) { $shares[$share->id] = array($share->sharing_name, $share->sharing_color); } $this->template->content->shares = $shares; // Get Default Color $this->template->content->default_map_all = Kohana::config('settings.default_map_all'); // Get The START, END and Incident Dates $startDate = ""; $endDate = ""; $display_startDate = 0; $display_endDate = 0; $db = new Database(); // Next, Get the Range of Years $query = $db->query('SELECT DATE_FORMAT(incident_date, \'%Y-%c\') AS dates FROM ' . $this->table_prefix . 'incident WHERE incident_active = 1 GROUP BY DATE_FORMAT(incident_date, \'%Y-%c\') ORDER BY incident_date'); $first_year = date('Y'); $last_year = date('Y'); $first_month = 1; $last_month = 12; $i = 0; foreach ($query as $data) { $date = explode('-', $data->dates); $year = $date[0]; $month = $date[1]; // Set first year if ($i == 0) { $first_year = $year; $first_month = $month; } // Set last dates $last_year = $year; $last_month = $month; $i++; } $show_year = $first_year; $selected_start_flag = TRUE; while ($show_year <= $last_year) { $startDate .= "<optgroup label=\"" . $show_year . "\">"; $s_m = 1; if ($show_year == $first_year) { // If we are showing the first year, the starting month may not be January $s_m = $first_month; } $l_m = 12; if ($show_year == $last_year) { // If we are showing the last year, the ending month may not be December $l_m = $last_month; } for ($i = $s_m; $i <= $l_m; $i++) { if ($i < 10) { // All months need to be two digits $i = "0" . $i; } $startDate .= "<option value=\"" . strtotime($show_year . "-" . $i . "-01") . "\""; if ($selected_start_flag == TRUE) { $display_startDate = strtotime($show_year . "-" . $i . "-01"); $startDate .= " selected=\"selected\" "; $selected_start_flag = FALSE; } $startDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $show_year . "</option>"; } $startDate .= "</optgroup>"; $endDate .= "<optgroup label=\"" . $show_year . "\">"; for ($i = $s_m; $i <= $l_m; $i++) { if ($i < 10) { // All months need to be two digits $i = "0" . $i; } $endDate .= "<option value=\"" . strtotime($show_year . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59") . "\""; if ($i == $l_m and $show_year == $last_year) { $display_endDate = strtotime($show_year . "-" . $i . "-" . date('t', mktime(0, 0, 0, $i, 1)) . " 23:59:59"); $endDate .= " selected=\"selected\" "; } $endDate .= ">" . date('M', mktime(0, 0, 0, $i, 1)) . " " . $show_year . "</option>"; } $endDate .= "</optgroup>"; // Show next year $show_year++; } Event::run('ushahidi_filter.active_startDate', $display_startDate); Event::run('ushahidi_filter.active_endDate', $display_endDate); Event::run('ushahidi_filter.startDate', $startDate); Event::run('ushahidi_filter.endDate', $endDate); $this->template->content->div_timeline->startDate = $startDate; $this->template->content->div_timeline->endDate = $endDate; // Javascript Header $this->themes->map_enabled = true; $this->themes->main_page = 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->themes->js = new View('adminmap/iframe_mapview_js'); $this->themes->js->json_url = $clustering == 1 ? "bigmap_json/cluster" : "bigmap_json"; $this->themes->js->marker_radius = $marker_radius >= 1 && $marker_radius <= 10 ? $marker_radius : 5; $this->themes->js->marker_opacity = $marker_opacity >= 1 && $marker_opacity <= 10 ? $marker_opacity * 0.1 : 0.9; $this->themes->js->marker_stroke_width = $marker_stroke_width >= 1 && $marker_stroke_width <= 5 ? $marker_stroke_width : 2; $this->themes->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->themes->js->numZoomLevels = $numZoomLevels; $this->themes->js->minZoomLevel = $minZoomLevel; $this->themes->js->maxZoomLevel = $maxZoomLevel; // pdestefanis - allows to limit the extents of the map $this->themes->js->lonFrom = $lonFrom; $this->themes->js->latFrom = $latFrom; $this->themes->js->lonTo = $lonTo; $this->themes->js->latTo = $latTo; $this->themes->js->default_map = Kohana::config('settings.default_map'); $this->themes->js->default_zoom = Kohana::config('settings.default_zoom'); $this->themes->js->latitude = Kohana::config('settings.default_lat'); $this->themes->js->longitude = Kohana::config('settings.default_lon'); $this->themes->js->default_map_all = Kohana::config('settings.default_map_all'); // $this->themes->js->active_startDate = $display_startDate; $this->themes->js->active_endDate = $display_endDate; //$myPacker = new javascriptpacker($js , 'Normal', false, false); //$js = $myPacker->pack(); // Rebuild Header Block $this->template->header->header_block = $this->themes->header_block(); }
/** * Add Edit Categories */ public function index() { $this->template->content = new View('admin/categories'); $this->template->content->title = Kohana::lang('ui_admin.categories'); // Locale (Language) Array $locales = locale::get_i18n(); // Setup and initialize form field names $form = array('action' => '', 'category_id' => '', 'parent_id' => '', 'category_title' => '', 'category_description' => '', 'category_color' => '', 'category_image' => '', 'category_image_thumb' => ''); // Add the different language form keys for fields foreach ($locales as $lang_key => $lang_name) { $form['category_title_' . $lang_key] = ''; } // Copy the form as errors, so the errors will be stored with keys corresponding to the form field names $errors = $form; $form_error = FALSE; $form_saved = FALSE; $form_action = ""; $parents_array = array(); // Check, has the form been submitted, if so, setup validation if ($_POST) { // Fetch the post data $post_data = array_merge($_POST, $_FILES); // Extract category-specific information $category_data = arr::extract($post_data, 'parent_id', 'category_title', 'category_description', 'category_color'); // Extract category image and category languages for independent validation $secondary_data = arr::extract($post_data, 'category_image', 'category_title_lang', 'action'); // Setup validation for the secondary data $post = Validation::factory($secondary_data)->pre_filter('trim', TRUE); // Add validation for the add/edit action if ($post->action == 'a') { $post->add_rules('category_image', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[50K]'); // Add the different language form keys for fields foreach ($locales as $lang_key => $lang_name) { $post->add_rules('category_title_lang[' . $lang_key . ']', 'length[3,80]'); } } // Category instance for the operation $category = (!empty($_POST['category_id']) and Category_Model::is_valid_category($_POST['category_id'])) ? new Category_Model($_POST['category_id']) : new Category_Model(); // Check the specified action if ($post->action == 'a') { // Test to see if things passed the rule checks if ($category->validate($category_data) and $post->validate()) { // Save the category $category->save(); // Get the category localization $languages = $category->loaded ? Category_Lang_Model::category_langs($category->id) : FALSE; $category_lang = isset($languages[$category->id]) ? $languages[$category->id] : FALSE; // Save localizations foreach ($post->category_title_lang as $lang_key => $localized_category_name) { $cl = isset($category_lang[$lang_key]['id']) ? ORM::factory('category_lang', $category_lang[$lang_key]['id']) : ORM::factory('category_lang'); $cl->category_title = $localized_category_name; $cl->locale = $lang_key; $cl->category_id = $category->id; $cl->save(); } // Upload Image/Icon $filename = upload::save('category_image'); if ($filename) { $new_filename = "category_" . $category->id . "_" . time(); // Resize Image to 32px if greater Image::factory($filename)->resize(32, 32, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . ".png"); // Create a 16x16 version too Image::factory($filename)->resize(16, 16, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_16x16.png"); // Remove the temporary file unlink($filename); // Delete Old Image $category_old_image = $category->category_image; if (!empty($category_old_image) and file_exists(Kohana::config('upload.directory', TRUE) . $category_old_image)) { unlink(Kohana::config('upload.directory', TRUE) . $category_old_image); } // Save $category->category_image = $new_filename . ".png"; $category->category_image_thumb = $new_filename . "_16x16.png"; $category->save(); } $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.added_edited')); // Empty $form array array_fill_keys($form, ''); } else { // Validation failed // Repopulate the form fields $form = arr::overwrite($form, array_merge($category_data->as_array(), $post->as_array())); // populate the error fields, if any $errors = arr::overwrite($errors, array_merge($category_data->errors('category'), $post->errors('category'))); $form_error = TRUE; } } elseif ($post->action == 'd') { // Delete action if ($category->loaded) { ORM::factory('category_lang')->where(array('category_id' => $category->id))->delete_all(); // @todo Delete the category image // Delete category itself - except if it is trusted ORM::factory('category')->where('category_trusted != 1')->delete($category->id); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.deleted')); } } elseif ($post->action == 'v') { // Show/Hide Action if ($category->loaded) { $category->category_visible = $category->category_visible == 1 ? 0 : 1; $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } elseif ($post->action == 'i') { // Delete Image/Icon Action if ($category->loaded) { $category_image = $category->category_image; $category_image_thumb = $category->category_image_thumb; if (!empty($category_image) and file_exists(Kohana::config('upload.directory', TRUE) . $category_image)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image); } if (!empty($category_image_thumb) and file_exists(Kohana::config('upload.directory', TRUE) . $category_image_thumb)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image_thumb); } $category->category_image = NULL; $category->category_image_thumb = NULL; $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } } // Pagination $pagination = new Pagination(array('query_string' => 'page', 'items_per_page' => $this->items_per_page, 'total_items' => ORM::factory('category')->where('parent_id', '0')->count_all())); $categories = ORM::factory('category')->with('category_lang')->where('parent_id', '0')->orderby('category_position', 'asc')->orderby('category_title', 'asc')->find_all($this->items_per_page, $pagination->sql_offset); $parents_array = ORM::factory('category')->where('parent_id', '0')->select_list('id', 'category_title'); // add none to the list $parents_array[0] = "--- Top Level Category ---"; // Put "--- Top Level Category ---" at the top of the list ksort($parents_array); $this->template->content->form = $form; $this->template->content->errors = $errors; $this->template->content->form_error = $form_error; $this->template->content->form_saved = $form_saved; $this->template->content->form_action = $form_action; $this->template->content->pagination = $pagination; $this->template->content->total_items = $pagination->total_items; $this->template->content->categories = $categories; $this->template->content->parents_array = $parents_array; // Javascript Header $this->template->colorpicker_enabled = TRUE; $this->template->tablerowsort_enabled = TRUE; $this->template->js = new View('admin/categories_js'); $this->template->form_error = $form_error; $this->template->content->locale_array = $locales; $this->template->js->locale_array = $locales; }