/** * Creates the required database tables for the sharing module */ public function run_install() { // Create the database tables // Include the table_prefix $this->db->query("\n\t\t\tCREATE TABLE IF NOT EXISTS `" . Kohana::config('database.default.table_prefix') . "sharing_site`\n\t\t\t(\n\t\t\t\t`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\t\t`site_name` varchar(150) NOT NULL COMMENT 'name that appears on the front end',\n\t\t\t\t`site_url` varchar(255) NOT NULL COMMENT 'url of the deployment to share with',\n\t\t\t\t`site_color` varchar(20) DEFAULT 'CC0000' COMMENT 'color that shows the shared reports',\n\t\t\t\t`site_active` tinyint(4) NOT NULL DEFAULT '1' COMMENT 'sharing active or inactive ',\n\t\t\t\t`share_categories` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'sharing active or inactive ',\n\t\t\t\t`share_reports` tinyint(4) NOT NULL DEFAULT '1' COMMENT 'sharing active or inactive ',\n\t\t\t\t`site_username` varchar(150) NOT NULL COMMENT 'username for the remote site',\n\t\t\t\t`site_password` varchar(150) NOT NULL COMMENT 'password for the remote site',\n\t\t\t\tPRIMARY KEY (id)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Stores sites we are getting shared reports from'\n\t\t\t"); $result = $this->db->query("SHOW COLUMNS FROM `sharing_site` LIKE 'site_username';"); if ($result->count() == 0) { $this->db->query(' ALTER TABLE `sharing_site` ADD COLUMN `site_username` varchar(150) NOT NULL COMMENT \'username for the remote site\', ADD COLUMN `site_password` varchar(150) NOT NULL COMMENT \'password for the remote site\' '); } $this->db->query("\n\t\t\tCREATE TABLE IF NOT EXISTS `" . Kohana::config('database.default.table_prefix') . "sharing_incident`\n\t\t\t(\n\t\t\t\t`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\t\t`location_id` bigint(20) unsigned NOT NULL,\n\t\t\t\t`sharing_site_id` INT UNSIGNED NOT NULL,\n\t\t\t\t`remote_incident_id` BIGINT(20) UNSIGNED NOT NULL,\n\t\t\t\t`updated` datetime DEFAULT NULL,\n\t\t\t\t`incident_title` varchar(255) NOT NULL COMMENT 'title of the report',\n\t\t\t\t`incident_description` longtext,\n\t\t\t\t`incident_date` datetime DEFAULT NULL,\n\t\t\t\t`incident_mode` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1 - WEB, 2 - SMS, 3 - EMAIL, 4 - TWITTER',\n\t\t\t\t`incident_active` tinyint(4) NOT NULL DEFAULT '0',\n\t\t\t\t`incident_verified` tinyint(4) NOT NULL DEFAULT '0',\n\t\t\t\tPRIMARY KEY (id),\n\t\t\t\tKEY `location_id` (`location_id`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Stores shared reports'\n\t\t\t"); $this->db->query("\n\t\t\tCREATE TABLE IF NOT EXISTS `" . Kohana::config('database.default.table_prefix') . "sharing_incident_category` (\n\t\t\t `id` int(11) NOT NULL AUTO_INCREMENT,\n\t\t\t `sharing_incident_id` bigint(20) unsigned NOT NULL DEFAULT '0',\n\t\t\t `category_id` int(11) unsigned NOT NULL DEFAULT '5',\n\t\t\t PRIMARY KEY (`id`),\n\t\t\t UNIQUE KEY `sharing_incident_category_ids` (`sharing_incident_id`,`category_id`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Stores shared reports categories'\n\t\t\t"); $this->db->query("\n\t\t\tCREATE TABLE IF NOT EXISTS `" . Kohana::config('database.default.table_prefix') . "sharing_incident_media` (\n\t\t\t `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\t `sharing_incident_id` bigint(20) unsigned NOT NULL DEFAULT '0',\n\t\t\t `media_id` bigint(20) unsigned NOT NULL DEFAULT '0',\n\t\t\t PRIMARY KEY (`id`),\n\t\t\t UNIQUE KEY `sharing_incident_media_ids` (`sharing_incident_id`,`media_id`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Stores shared reports media'\n\t\t\t"); $this->db->query("\n\t\t\tCREATE TABLE IF NOT EXISTS `" . Kohana::config('database.default.table_prefix') . "sharing_incident_comment` (\n\t\t\t `id` int(11) NOT NULL AUTO_INCREMENT,\n\t\t\t `sharing_incident_id` bigint(20) unsigned NOT NULL DEFAULT '0',\n\t\t\t `comment_id` int(11) unsigned NOT NULL DEFAULT '5',\n\t\t\t PRIMARY KEY (`id`),\n\t\t\t UNIQUE KEY `sharing_incident_comment_ids` (`sharing_incident_id`,`comment_id`)\n\t\t\t) ENGINE=MyISAM AUTO_INCREMENT=14064 DEFAULT CHARSET=utf8 COMMENT='Stores shared reports comments'\n\t\t\t"); $this->db->query("\n\t\t\tCREATE TABLE IF NOT EXISTS `" . Kohana::config('database.default.table_prefix') . "sharing_category`\n\t\t\t(\n\t\t\t\t`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t\t\t`sharing_site_id` INT UNSIGNED NOT NULL,\n\t\t\t\t`category_id` BIGINT(20) UNSIGNED NOT NULL,\n\t\t\t\t`remote_category_id` BIGINT(20) UNSIGNED NOT NULL,\n\t\t\t\t`updated` datetime DEFAULT NULL,\n\t\t\t\tPRIMARY KEY (id),\n\t\t\t UNIQUE KEY `category_id` (`category_id`),\n\t\t\t UNIQUE KEY `remote_category_id` (`sharing_site_id`,`remote_category_id`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Stores shared categories'\n\t\t\t"); // Create view for querying $this->db->query("\n\t\t\tCREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER VIEW `sharing_combined_incident` AS\n\t\t\t\tSELECT `incident`.`id` AS `id`,\n\t\t\t\t\t`incident`.`incident_title` AS `incident_title`,\n\t\t\t\t\t`incident`.`incident_description` AS `incident_description`,\n\t\t\t\t\t`incident`.`incident_date` AS `incident_date`,\n\t\t\t\t\t`incident`.`incident_mode` AS `incident_mode`,\n\t\t\t\t\t`incident`.`location_id` AS `location_id`,\n\t\t\t\t\t`incident`.`incident_active` AS `incident_active`,\n\t\t\t\t\t`incident`.`incident_verified` AS `incident_verified`,\n\t\t\t\t\t'main' AS `source`,\n\t\t\t\t\tNULL AS `source_url`\n\t\t\t\tFROM `incident`\n\t\t\t\tUNION\n\t\t\t\tSELECT\n\t\t\t\t\t`sharing_incident`.`id` AS `id`,\n\t\t\t\t\t`sharing_incident`.`incident_title` AS `incident_title`,\n\t\t\t\t\t`sharing_incident`.`incident_description` AS `incident_description`,\n\t\t\t\t\t`sharing_incident`.`incident_date` AS `incident_date`,\n\t\t\t\t\t`sharing_incident`.`incident_mode` AS `incident_mode`,\n\t\t\t\t\t`sharing_incident`.`location_id` AS `location_id`,\n\t\t\t\t\t`sharing_incident`.`incident_active` AS `incident_active`,\n\t\t\t\t\t`sharing_incident`.`incident_verified` AS `incident_verified`,\n\t\t\t\t\t`sharing_incident`.`sharing_site_id` AS `source`,\n\t\t\t\t\t`sharing_site`.`site_url` AS `source_url`\n\t\t\t\tFROM `sharing_incident`\n\t\t\t\tLEFT JOIN `sharing_site`\n\t\t\t\t\tON (`sharing_incident`.`sharing_site_id` = `sharing_site`.`id`)\n\t\t\t"); $this->db->query("\n\t\t\tCREATE OR REPLACE ALGORITHM=UNDEFINED DEFINER=CURRENT_USER SQL SECURITY INVOKER VIEW `sharing_combined_incident_category` AS\n\t\t\t\tSELECT `incident_category`.`incident_id` AS `incident_id`,\n\t\t\t\t\tNULL AS `sharing_incident_id`,\n\t\t\t\t\t`incident_category`.`category_id` AS `category_id`\n\t\t\t\tFROM `incident_category`\n\t\t\t\tUNION\n\t\t\t\tSELECT\n\t\t\t\t\tNULL AS `incident_id`,\n\t\t\t\t\t`sharing_incident_category`.`sharing_incident_id` AS `sharing_incident_id`,\n `sharing_incident_category`.`category_id` AS `category_id`\n\t\t\t\tFROM `sharing_incident_category`\n\t\t\t"); //Dump the sharing scheduler item from bundled SQL dump file $this->db->query("DELETE FROM `" . Kohana::config('database.default.table_prefix') . "scheduler` where scheduler_name = 'Sharing' "); // Add sharing in to scheduler table $this->db->query("INSERT IGNORE INTO `" . Kohana::config('database.default.table_prefix') . "scheduler`\n\t\t\t\t(`scheduler_name`,`scheduler_last`,`scheduler_weekday`,`scheduler_day`,`scheduler_hour`,`scheduler_minute`,`scheduler_controller`,`scheduler_active`) VALUES\n\t\t\t\t('Sharing','0','-1','-1','-1','-1','s_sharing','1')"); // Add Other category to the categories list (if it doesn't exist already) $categoryname = "Other"; $other_category = ORM::factory('category')->where('category_title', $categoryname)->where('parent_id', 0)->find(); $current_other_category_id = Settings_Model::get_setting('sharing_other_category_id'); if ($other_category->loaded && empty($current_other_category_id)) { // We already have a category "Other", save setting Settings_Model::save_setting('sharing_other_category_id', $other_category->id); } else { // No category named "Other". Do we have an id save though (maybe it's been renamed) $category = ORM::factory('Category', Settings_Model::get_setting('sharing_other_category_id')); if (!$category->loaded) { $this->notices[] = Kohana::lang('import.new_category') . $categoryname; $category = new Category_Model(); $category->category_title = $categoryname; // We'll use grey for now. Maybe something random? $category->category_color = '000000'; $category->category_visible = 1; // FIXIT: We need to make this zero for non-central deployments? $category->category_trusted = 1; // Trusted - can't delete $category->category_description = "Category with reports that couldn't be categorised from other deployments"; //FIXIT: need to l10n this; $category->category_position = ORM::factory('category')->count_all(); $category->save(); Settings_Model::save_setting('sharing_other_category_id', $category->id); } } }
function index() { $this->template->content = new View('admin/categories'); $this->template->content->title = Kohana::lang('ui_admin.categories'); // setup and initialize form field names $form = array('action' => '', 'category_id' => '', 'parent_id' => '', 'category_title' => '', 'category_description' => '', 'category_color' => '', 'category_image' => ''); // 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); 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')); } // Test to see if things passed the rule checks if ($post->validate()) { $category_id = $post->category_id; $category = new Category_Model($category_id); if ($post->action == 'd') { // Delete Action $category->delete($category_id); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.deleted')); } else { if ($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')); } } else { if ($post->action == 'i') { // Delete Image/Icon Action if ($category->loaded == true) { $category_image = $category->category_image; if (!empty($category_image) && file_exists(Kohana::config('upload.directory', TRUE) . $category_image)) { unlink(Kohana::config('upload.directory', TRUE) . $category_image); } $category->category_image = null; $category->save(); $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.modified')); } } else { if ($post->action == 'a') { // Save Action $category->parent_id = $post->parent_id; $category->category_title = $post->category_title; $category->category_description = $post->category_description; $category->category_color = $post->category_color; $category->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"); // Remove the temporary file unlink($filename); // Delete Old Image $category_old_image = $category->category_image; if (!empty($category_old_image) && 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->save(); } $form_saved = TRUE; $form_action = strtoupper(Kohana::lang('ui_admin.added_edited')); } } } } } 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')->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 ---"; $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; // Locale (Language) Array $this->template->content->locale_array = Kohana::config('locale.all_languages'); // Javascript Header $this->template->colorpicker_enabled = TRUE; $this->template->js = new View('admin/categories_js'); }
/** * Save newly added dynamic categories */ function save_category() { $this->auto_render = FALSE; $this->template = ""; // 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($_POST); // Add some filters $post->pre_filter('trim', TRUE); // Add some rules, the input field, followed by a list of checks, carried out in order $post->add_rules('category_title', 'required', 'length[3,200]'); $post->add_rules('category_description', 'required'); $post->add_rules('category_color', 'required', 'length[6,6]'); // Test to see if things passed the rule checks if ($post->validate()) { // SAVE Category $category = new Category_Model(); $category->category_title = $post->category_title; $category->category_description = $post->category_description; $category->category_color = $post->category_color; $category->save(); $form_saved = TRUE; echo json_encode(array("status" => "saved", "id" => $category->id)); } else { echo json_encode(array("status" => "error")); } } else { echo json_encode(array("status" => "error")); } }
/** * parse feed and send feed items to database */ public function index() { // Max number of feeds to keep $max_feeds = 100; // Today's Date $today = strtotime('now'); // Get All Feeds From DB $feeds = ORM::factory('feed')->find_all(); foreach ($feeds as $feed) { $last_update = $feed->feed_update; // Parse Feed URL using Feed Helper $feed_data = feed::simplepie($feed->feed_url); foreach ($feed_data->get_items(0, 50) as $feed_data_item) { $title = $feed_data_item->get_title(); $link = $feed_data_item->get_link(); $description = $feed_data_item->get_description(); $date = $feed_data_item->get_date(); $latitude = $feed_data_item->get_latitude(); $longitude = $feed_data_item->get_longitude(); $categories = $feed_data_item->get_categories(); // HT: new code $category_ids = new stdClass(); // HT: new code // Make Sure Title is Set (Atleast) if (isset($title) && !empty($title)) { // We need to check for duplicates!!! // Maybe combination of Title + Date? (Kinda Heavy on the Server :-( ) $dupe_count = ORM::factory('feed_item')->where('item_title', $title)->where('item_date', date("Y-m-d H:i:s", strtotime($date)))->count_all(); if ($dupe_count == 0) { // Does this feed have a location?? $location_id = 0; // STEP 1: SAVE LOCATION if ($latitude and $longitude) { $location = new Location_Model(); $location->location_name = "Unknown"; $location->latitude = $latitude; $location->longitude = $longitude; $location->location_date = date("Y-m-d H:i:s", time()); $location->save(); $location_id = $location->id; } $newitem = new Feed_Item_Model(); $newitem->feed_id = $feed->id; $newitem->location_id = $location_id; $newitem->item_title = $title; if (isset($description) and !empty($description)) { $newitem->item_description = $description; } if (isset($link) and !empty($link)) { $newitem->item_link = $link; } if (isset($date) and !empty($date)) { $newitem->item_date = date("Y-m-d H:i:s", strtotime($date)); } else { $newitem->item_date = date("Y-m-d H:i:s", time()); } // HT: new code if (!empty($categories)) { foreach ($categories as $category) { $categoryData = ORM::factory('category')->where('category_title', $category->term)->find(); if ($categoryData->loaded == TRUE) { $category_ids->feed_item_category[$categoryData->id] = $categoryData->id; } elseif (Kohana::config('settings.allow_feed_category')) { $newcategory = new Category_Model(); $newcategory->category_title = $category->term; $newcategory->parent_id = 0; $newcategory->category_description = $category->term; $newcategory->category_color = '000000'; $newcategory->category_visible = 0; $newcategory->save(); $category_ids->feed_item_category[$newcategory->id] = $newcategory->id; } } } // HT: End of new code $newitem->save(); // HT: New code if (!empty($category_ids->feed_item_category)) { feed::save_category($category_ids, $newitem); } // HT: End of New code // Action::feed_item_add - Feed Item Received! Event::run('ushahidi_action.feed_item_add', $newitem); } } } // Get Feed Item Count $feed_count = ORM::factory('feed_item')->where('feed_id', $feed->id)->count_all(); if ($feed_count > $max_feeds) { // Excess Feeds $feed_excess = $feed_count - $max_feeds; } // Set feed update date $feed->feed_update = strtotime('now'); $feed->save(); } }
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; }
/** * Save newly added dynamic categories */ public function save_category() { $this->auto_render = FALSE; $this->template = ""; // 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 // HT: New code for category save with parent $post = arr::extract($_POST, 'parent_id', 'category_title', 'category_description', 'category_color'); // Category instance for the operation $category = new Category_Model(); if ($category->validate($post)) { $category->save(); $form_saved = TRUE; echo json_encode(array("status" => "saved", "id" => $category->id)); } else { echo json_encode(array("status" => "error")); } } else { echo json_encode(array("status" => "error")); } }
/** * 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; }
/** * Function to import a report form a row in the CSV file * @param array $row * @return bool */ function importreport($row) { // If the date is not in proper date format if (!strtotime($row['INCIDENT DATE'])) { $this->errors[] = 'Could not parse incident date "' . htmlspecialchars($row['INCIDENT DATE']) . '" on line ' . ($this->rownumber + 1); } // If a value of Yes or No is NOT set for approval status for the imported row if (isset($row["APPROVED"]) and !in_array($row["APPROVED"], array('NO', 'YES'))) { $this->errors[] = 'APPROVED must be either YES or NO on line ' . ($this->rownumber + 1); } // If a value of Yes or No is NOT set for verified status for the imported row if (isset($row["VERIFIED"]) and !in_array($row["VERIFIED"], array('NO', 'YES'))) { $this->errors[] = 'VERIFIED must be either YES or NO on line ' . ($this->rownumber + 1); } if (count($this->errors)) { return false; } // STEP 1: SAVE LOCATION if (isset($row['LOCATION'])) { $location = new Location_Model(); $location->location_name = isset($row['LOCATION']) ? $row['LOCATION'] : ''; $location->latitude = isset($row['LATITUDE']) ? $row['LATITUDE'] : ''; $location->longitude = isset($row['LONGITUDE']) ? $row['LONGITUDE'] : ''; $location->location_date = $this->time; $location->save(); $this->locations_added[] = $location->id; } // STEP 2: SAVE INCIDENT $incident = new Incident_Model(); $incident->location_id = isset($row['LOCATION']) ? $location->id : 0; $incident->user_id = 0; $incident->incident_title = $row['INCIDENT TITLE']; $incident->incident_description = isset($row['DESCRIPTION']) ? $row['DESCRIPTION'] : ''; $incident->incident_date = date("Y-m-d H:i:s", strtotime($row['INCIDENT DATE'])); $incident->incident_dateadd = $this->time; $incident->incident_active = (isset($row['APPROVED']) and $row['APPROVED'] == 'YES') ? 1 : 0; $incident->incident_verified = (isset($row['VERIFIED']) and $row['VERIFIED'] == 'YES') ? 1 : 0; $incident->save(); $this->incidents_added[] = $incident->id; // STEP 3: SAVE CATEGORIES // If CATEGORIES column exists if (isset($row['CATEGORY'])) { $categorynames = explode(',', trim($row['CATEGORY'])); // Add categories to incident foreach ($categorynames as $categoryname) { // There seems to be an uppercase convention for categories... Don't know why $categoryname = strtoupper(trim($categoryname)); // Empty categoryname not allowed if ($categoryname != '') { if (!isset($this->category_ids[$categoryname])) { $this->notices[] = 'There exists no category "' . htmlspecialchars($categoryname) . '" in database yet.' . ' Added to database.'; $category = new Category_Model(); $category->category_title = $categoryname; // We'll just use black for now. Maybe something random? $category->category_color = '000000'; // because all current categories are of type '5' $category->category_type = 5; $category->category_visible = 1; $category->category_description = $categoryname; $category->save(); $this->categories_added[] = $category->id; // Now category_id is known: This time, and for the rest of the import. $this->category_ids[$categoryname] = $category->id; } $incident_category = new Incident_Category_Model(); $incident_category->incident_id = $incident->id; $incident_category->category_id = $this->category_ids[$categoryname]; $incident_category->save(); $this->incident_categories_added[] = $incident_category->id; } } } return true; }
/** * Submit categories details * * @return int */ private function _submit_categories() { // setup and initialize form field names $form = array('parent_id' => '', 'category_title' => '', 'category_description' => '', 'category_color' => '', 'category_image' => ''); // copy the form as errors, so the errors will be stored //with keys corresponding to the form field names $errors = $form; $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 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')); // Test to see if things passed the rule checks if ($post->validate(FALSE)) { $category = new Category_Model(); // Save Action $category->parent_id = $post->parent_id; $category->category_title = $post->category_title; $category->category_description = $post->category_description; $category->category_color = $post->category_color; $category->save(); //optional if (!empty($post->category_image)) { // 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"); // 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->save(); } } // Empty $form array array_fill_keys($form, ''); } else { // populate the error fields, if any $errors = arr::overwrite($errors, $post->errors('category')); foreach ($errors as $error_item => $error_description) { if (!is_array($error_description)) { $this->error_messages .= $error_description; if ($error_description != end($errors)) { $this->error_messages .= " - "; } } } return 1; // Validation error } } else { return 3; // Not sent by post method. } }
/** * 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; }
function index() { $this->template->content = new View('admin/categories'); $this->template->content->title = 'Categories'; // setup and initialize form field names $form = array('action' => '', 'locale' => '', 'category_id' => '', 'category_title' => '', 'category_description' => '', 'category_color' => ''); // 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 = ""; // 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($_POST); // Add some filters $post->pre_filter('trim', TRUE); if ($post->action == 'a') { // Add some rules, the input field, followed by a list of checks, carried out in order $post->add_rules('locale', 'required', 'alpha_dash', 'length[5]'); $post->add_rules('category_title', 'required', 'length[3,80]'); $post->add_rules('category_description', 'required'); $post->add_rules('category_color', 'required', 'length[6,6]'); } // Test to see if things passed the rule checks if ($post->validate()) { $category_id = $post->category_id; $category = new Category_Model($category_id); if ($post->action == 'd') { $category->delete($category_id); $form_saved = TRUE; $form_action = "DELETED"; } else { if ($post->action == 'v') { 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 = "MODIFIED"; } } else { if ($post->action == 'a') { // SAVE Category $category->locale = $post->locale; $category->category_title = $post->category_title; $category->category_description = $post->category_description; $category->category_color = $post->category_color; $category->save(); $form_saved = TRUE; $form_action = "ADDED/EDITED"; } } } } 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')->count_all())); $categories = ORM::factory('category')->orderby('category_title', 'asc')->find_all((int) Kohana::config('settings.items_per_page_admin'), $pagination->sql_offset); $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; // Locale (Language) Array $this->template->content->locale_array = Kohana::config('locale.all_languages'); // Javascript Header $this->template->colorpicker_enabled = TRUE; $this->template->js = new View('admin/categories_js'); }
/** * Function to import a report form a row in the CSV file * @param array $row * @return bool */ function import_report($row) { // If the date is not in proper date format if (!strtotime($row['INCIDENT DATE'])) { $this->errors[] = Kohana::lang('import.incident_date') . ($this->rownumber + 1) . ': ' . $row['INCIDENT DATE']; } // If a value of Yes or No is NOT set for approval status for the imported row if (isset($row["APPROVED"]) and !in_array(utf8::strtoupper($row["APPROVED"]), array('NO', 'YES'))) { $this->errors[] = Kohana::lang('import.csv.approved') . ($this->rownumber + 1); } // If a value of Yes or No is NOT set for verified status for the imported row if (isset($row["VERIFIED"]) and !in_array(utf8::strtoupper($row["VERIFIED"]), array('NO', 'YES'))) { $this->errors[] = Kohana::lang('import.csv.verified') . ($this->rownumber + 1); } if (count($this->errors)) { return false; } // STEP 1: SAVE LOCATION if (isset($row['LOCATION'])) { $location = new Location_Model(); $location->location_name = isset($row['LOCATION']) ? $row['LOCATION'] : ''; // For Geocoding purposes $location_geocoded = map::geocode($location->location_name); // If we have LATITUDE and LONGITUDE use those if (isset($row['LATITUDE']) and isset($row['LONGITUDE'])) { $location->latitude = isset($row['LATITUDE']) ? $row['LATITUDE'] : 0; $location->longitude = isset($row['LONGITUDE']) ? $row['LONGITUDE'] : 0; } else { $location->latitude = $location_geocoded ? $location_geocoded['latitude'] : 0; $location->longitude = $location_geocoded ? $location_geocoded['longitude'] : 0; } $location->country_id = $location_geocoded ? $location_geocoded['country_id'] : 0; $location->location_date = $this->time; $location->save(); $this->locations_added[] = $location->id; } // STEP 2: SAVE INCIDENT $incident = new Incident_Model(); $incident->location_id = isset($row['LOCATION']) ? $location->id : 0; $incident->user_id = 0; $incident->form_id = (isset($row['FORM #']) and Form_Model::is_valid_form($row['FORM #'])) ? $row['FORM #'] : 1; $incident->incident_title = $row['INCIDENT TITLE']; $incident->incident_description = isset($row['DESCRIPTION']) ? $row['DESCRIPTION'] : ''; $incident->incident_date = date("Y-m-d H:i:s", strtotime($row['INCIDENT DATE'])); $incident->incident_dateadd = $this->time; $incident->incident_active = (isset($row['APPROVED']) and utf8::strtoupper($row['APPROVED']) == 'YES') ? 1 : 0; $incident->incident_verified = (isset($row['VERIFIED']) and utf8::strtoupper($row['VERIFIED']) == 'YES') ? 1 : 0; $incident->save(); $this->incidents_added[] = $incident->id; // STEP 3: Save Personal Information if (isset($row['FIRST NAME']) or isset($row['LAST NAME']) or isset($row['EMAIL'])) { $person = new Incident_Person_Model(); $person->incident_id = $incident->id; $person->person_first = isset($row['FIRST NAME']) ? $row['FIRST NAME'] : ''; $person->person_last = isset($row['LAST NAME']) ? $row['LAST NAME'] : ''; $person->person_email = (isset($row['EMAIL']) and valid::email($row['EMAIL'])) ? $row['EMAIL'] : ''; $person->person_date = date("Y-m-d H:i:s", time()); // Make sure that you're not importing an empty record i.e at least one field has been recorded // If all fields are empty i.e you have an empty record, don't save if (!empty($person->person_first) or !empty($person->person_last) or !empty($person->person_email)) { $person->save(); // Add to array of incident persons added $this->incident_persons_added[] = $person->id; } } // STEP 4: SAVE CATEGORIES // If CATEGORY column exists if (isset($row['CATEGORY'])) { $categorynames = explode(',', trim($row['CATEGORY'])); // Trim whitespace from array values $categorynames = array_map('trim', $categorynames); // Get rid of duplicate category entries in a row $categories = array_unique(array_map('strtolower', $categorynames)); // Add categories to incident foreach ($categories as $categoryname) { // Convert the first string character of the category name to Uppercase $categoryname = utf8::ucfirst($categoryname); // For purposes of adding an entry into the incident_category table $incident_category = new Incident_Category_Model(); $incident_category->incident_id = $incident->id; // If category name exists, add entry in incident_category table if ($categoryname != '') { // Check if the category exists (made sure to convert to uppercase for comparison) if (!isset($this->existing_categories[utf8::strtoupper($categoryname)])) { $this->notices[] = Kohana::lang('import.new_category') . $categoryname; $category = new Category_Model(); $category->category_title = $categoryname; // We'll just use black for now. Maybe something random? $category->category_color = '000000'; // because all current categories are of type '5' $category->category_visible = 1; $category->category_description = $categoryname; $category->category_position = count($this->existing_categories); $category->save(); $this->categories_added[] = $category->id; // Now category_id is known: This time, and for the rest of the import. $this->existing_categories[utf8::strtoupper($categoryname)] = $category->id; } $incident_category->category_id = $this->existing_categories[utf8::strtoupper($categoryname)]; $incident_category->save(); $this->incident_categories_added[] = $incident_category->id; } } } // STEP 5: Save Custom form fields responses // Check for form_id $form_id = (isset($row['FORM #']) and Form_Model::is_valid_form($row['FORM #'])) ? $row['FORM #'] : 1; // Get custom form fields for this particular form $custom_titles = customforms::get_custom_form_fields('', $form_id, false); // Do custom form fields exist on this deployment? if (!empty($custom_titles)) { foreach ($custom_titles as $field_name) { // Check if the column exists in the CSV $rowname = utf8::strtoupper($field_name['field_name']); if (isset($row[$rowname . '-' . $form_id])) { $response = $row[$rowname . '-' . $form_id]; // Grab field_id and field_type $field_id = $field_name['field_id']; $field_type = $field_name['field_type']; // Initialize form response model $form_response = new Form_Response_Model(); $form_response->incident_id = $incident->id; $form_response->form_field_id = $field_id; // If form response exists if ($response != '') { /* Handling case sensitivity issues with custom form field upload */ // Check if the field is a radio button, checkbox OR dropdown field if ($field_type == '5' or $field_type == '6' or $field_type == '7') { // Get field option values $field_values = $field_name['field_default']; // Split field options into individual values $options = explode(",", $field_values); // Since radio button and dropdown fields take single responses if ($field_type == '5' or $field_type == '7') { foreach ($options as $option) { // Carry out a case insensitive comparison between individual field options and csv response // If there's a match, store field option value from the db if (strcasecmp($option, $response) == 0) { $form_response->form_response = $option; } } } // For checkboxes, which accomodate multiple responses if ($field_type == '6') { // Split user responses into single values $csvresponses = explode(",", $response); $values = array(); foreach ($options as $option) { foreach ($csvresponses as $csvresponse) { // Carry out a case insensitive comparison between individual field options and csv response // If there's a match if (strcasecmp($option, $csvresponse) == 0) { // Store field option value from the db $values[] = $option; } } } // Concatenate checkbox values into a string, separated by a comma $form_response->form_response = implode(",", $values); } } else { $form_response->form_response = $response; } // If form_response is provided based on conditions set above, Save the form response if ($form_response->form_response != '') { $form_response->save(); // Add to array of field responses added $this->incident_responses_added[] = $form_response->id; } } } } } return true; }
function importreport($row) { if (!strtotime($row['PROFILE DATE'])) { $this->errors[] = 'Could not parse profile date "' . htmlspecialchars($row['PROFILE DATE']) . '" on line ' . ($this->rownumber + 1); } if (isset($row["APPROVED"]) and !in_array($row["APPROVED"], array('NO', 'YES'))) { $this->errors[] = 'APPROVED must be either YES or NO on line ' . ($this->rownumber + 1); } if (isset($row["VERIFIED"]) and !in_array($row["VERIFIED"], array('NO', 'YES'))) { $this->errors[] = 'VERIFIED must be either YES or NO on line ' . ($this->rownumber + 1); } if (count($this->errors)) { return false; } // STEP 1: SAVE LOCATION if (isset($row['LOCATION'])) { $location = new Location_Model(); $location->location_name = isset($row['LOCATION']) ? $row['LOCATION'] : ''; $location->latitude = isset($row['LATITUDE']) ? $row['LATITUDE'] : ''; $location->longitude = isset($row['LONGITUDE']) ? $row['LONGITUDE'] : ''; $location->location_date = $this->time; $location->save(); $this->locations_added[] = $location->id; } // STEP 2: SAVE INCIDENT $incident = new Incident_Model(); $incident->location_id = isset($row['LOCATION']) ? $location->id : 0; $incident->user_id = 0; $incident->incident_title = $row['PROFILE TITLE']; $incident->incident_description = isset($row['DESCRIPTION']) ? $row['DESCRIPTION'] : ''; $incident->incident_date = date("Y-m-d H:i:s", strtotime($row['PROFILE DATE'])); $incident->incident_dateadd = $this->time; $incident->incident_active = (isset($row['APPROVED']) and $row['APPROVED'] == 'YES') ? 1 : 0; $incident->incident_verified = (isset($row['VERIFIED']) and $row['VERIFIED'] == 'YES') ? 1 : 0; //$incident->save(); $this->incidents_added[] = $incident->id; // STEP 3: SAVE CATEGORIES if (isset($row['CATEGORY'])) { $categorynames = explode(',', trim($row['CATEGORY'])); foreach ($categorynames as $categoryname) { $categoryname = strtoupper(trim($categoryname)); // There seems to be an uppercase convention for categories... Don't know why. if ($categoryname != '') { if (!isset($this->category_ids[$categoryname])) { $this->notices[] = 'There exists no category "' . htmlspecialchars($categoryname) . '" in database yet. Added to database.'; $category = new Category_Model(); $category->category_title = $categoryname; $category->category_color = '000000'; // We'll just use black for now. Maybe something random? $category->category_type = 5; // because all current categories are of type '5' $category->category_visible = 1; $category->category_description = $categoryname; $category->save(); $this->categories_added[] = $category->id; $this->category_ids[$categoryname] = $category->id; // Now category_id is known: This time, and for the rest of the import. } $incident_category = new Incident_Category_Model(); $incident_category->incident_id = $incident->id; $incident_category->category_id = $this->category_ids[$categoryname]; $incident_category->save(); $this->incident_categories_added[] = $incident_category->id; } // empty categoryname not allowed } // add categories to incident } // if CATEGORIES column exists //SAVE Custom fields $custom_form_fields = $this->_get_custom_form_fields($incident->id, 1, false); foreach ($custom_form_fields as $custom_form_field) { $field_name = $custom_form_field['field_name']; $field_name = strtoupper($field_name); if (isset($row[$field_name])) { $form_response = new Form_Response_Model(); $form_response->form_field_id = $custom_form_field['field_id']; $form_response->incident_id = $incident->id; $form_response->form_response = $row[$field_name]; // $form_response->save(); } } return true; }
/** * parse feed and send feed items to database */ public function index() { // Max number of feeds to keep $max_items = 100; // Today's Date $today = strtotime('now'); // Get All Feeds From DB $feeds = ORM::factory('feed')->like('feed_name', 'TED')->find_all(); foreach ($feeds as $feed) { // Get Feed Items with location but no incident yet $feed_items = ORM::factory('feed_item')->where(array('feed_id' => $feed->id, 'location_id !=' => 0, 'incident_id' => 0))->find_all(); foreach ($feed_items as $feed_item) { //echo $feed_item->item_title; $incident = new Incident_Model(); $incident->incident_title = $feed_item->item_title; $incident->incident_description = $feed_item->item_description; $incident->incident_date = $feed_item->item_date; $incident->location_id = $feed_item->location_id; $incident->incident_active = true; $incident->incident_verified = true; if (strpos($feed_item->item_link, 'youtube') !== FALSE) { $id = str_replace(array('http://www.youtube.com/watch?v=', '&feature=youtube_gdata'), '', $feed_item->item_link); // Get extra details from youtube api $json = @file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$id}?v=2&alt=jsonc"); if ($json !== FALSE) { $json = json_decode($json); $thumb = $json->data->thumbnail->hqDefault; if (!$incident->incident_description) { $incident->incident_description = $json->data->description; } foreach ($json->data->tags as $tag) { if (stripos($tag, 'tedx') !== FALSE && strtolower($tag) != 'tedx') { $cat = $tag; break; } } } $incident->save(); $feed_item->incident_id = $incident->id; $feed_item->save(); // Add video $video = new Media_Model(); $video->location_id = $incident->location_id; $video->incident_id = $incident->id; $video->media_type = 2; // Video $video->media_link = $feed_item->item_link; $video->media_thumb = isset($thumb) ? $thumb : ''; $video->media_medium = isset($thumb) ? $thumb : ''; $video->media_date = $feed_item->item_date; $video->save(); // News Link $news = new Media_Model(); $news->location_id = $incident->location_id; $news->incident_id = $incident->id; $news->media_type = 4; // News $news->media_link = $feed_item->item_link; $news->media_date = $feed_item->item_date; $news->save(); // Category if (!empty($cat)) { $db = Database::instance(); $result = $db->query("SELECT `category`.`id` FROM `category` WHERE lower(`category_title`) = ? ORDER BY `category`.`category_position` ASC LIMIT 0, 1", strtolower($cat)); if ($row = $result->current()) { $category_id = $row->id; } else { $category = new Category_Model(); $category->category_title = $cat; // We'll just use blue since its tedx $category->category_color = '002bff'; // because all current categories are of type '5' $category->category_type = 5; $category->category_visible = 1; $category->category_description = $cat; $category->parent_id = 156; // TEDX $category->save(); $category_id = $category->id; } $incident_category = new Incident_Category_Model(); $incident_category->incident_id = $incident->id; $incident_category->category_id = $category_id; $incident_category->save(); } } } } }