/** * Automatically executed before the widget action. Can be used to set * class properties, do authorization checks, and execute other custom code. * * @return void */ public function before() { if (is_numeric($user_id_location = Cookie::get('user_location'))) { $user_location = new Model_Location($user_id_location); if ($user_location->loaded()) { $this->location = $user_location; } } }
/** * CRUD controller: DELETE */ public function action_delete() { $this->auto_render = FALSE; $location = new Model_Location($this->request->param('id')); //update the elements related to that ad if ($location->loaded()) { //update all the siblings this location has and set the location parent $query = DB::update('locations')->set(array('id_location_parent' => $location->id_location_parent))->where('id_location_parent', '=', $location->id_location)->execute(); //update all the ads this location has and set the location parent $query = DB::update('ads')->set(array('id_location' => $location->id_location_parent))->where('id_location', '=', $location->id_location)->execute(); try { $location->delete(); $this->template->content = 'OK'; Alert::set(Alert::SUCCESS, __('Location deleted')); } catch (Exception $e) { Alert::set(Alert::ERROR, $e->getMessage()); } } else { Alert::set(Alert::SUCCESS, __('Location not deleted')); } Request::current()->redirect(Route::url('oc-panel', array('controller' => 'location', 'action' => 'index'))); }
/** * This function will upgrade DB that didn't existed in versions prior to 2.3.0 */ public function action_230() { //Cron update try { DB::query(Database::UPDATE, "UPDATE `" . self::$db_prefix . "crontab` SET period='00 3 * * *' WHERE callback='Sitemap::generate' LIMIT 1")->execute(); DB::query(Database::UPDATE, "UPDATE `" . self::$db_prefix . "crontab` SET period='00 5 * * *' WHERE callback='Core::delete_cache' LIMIT 1")->execute(); DB::query(Database::UPDATE, "UPDATE `" . self::$db_prefix . "crontab` SET period='00 4 1 * *' WHERE callback='Core::optimize_db' LIMIT 1")->execute(); DB::query(Database::UPDATE, "UPDATE `" . self::$db_prefix . "crontab` SET period='00 7 * * *' WHERE callback='Cron_Ad::unpaid' LIMIT 1")->execute(); DB::query(Database::UPDATE, "UPDATE `" . self::$db_prefix . "crontab` SET period='00 8 * * *' WHERE callback='Cron_Ad::expired_featured' LIMIT 1")->execute(); DB::query(Database::UPDATE, "UPDATE `" . self::$db_prefix . "crontab` SET period='00 9 * * *' WHERE callback='Cron_Ad::expired' LIMIT 1")->execute(); } catch (exception $e) { } //control login attempts try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "users` ADD `last_failed` DATETIME NULL DEFAULT NULL ;")->execute(); } catch (exception $e) { } try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "users` ADD `failed_attempts` int(10) unsigned DEFAULT 0")->execute(); } catch (exception $e) { } //categories/locations/users/ads has_image/last_modified try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "categories` ADD `last_modified` DATETIME NULL DEFAULT NULL ;")->execute(); } catch (exception $e) { } try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "categories` ADD `has_image` TINYINT( 1 ) NOT NULL DEFAULT '0' ;")->execute(); } catch (exception $e) { } try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "locations` ADD `last_modified` DATETIME NULL DEFAULT NULL ;")->execute(); } catch (exception $e) { } try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "locations` ADD `has_image` TINYINT( 1 ) NOT NULL DEFAULT '0' ;")->execute(); } catch (exception $e) { } try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "users` ADD `has_image` TINYINT( 1 ) NOT NULL DEFAULT '0' ;")->execute(); } catch (exception $e) { } try { DB::query(Database::UPDATE, "ALTER TABLE `" . self::$db_prefix . "ads` ADD `last_modified` DATETIME NULL DEFAULT NULL ;")->execute(); } catch (exception $e) { } //new configs $configs = array(array('config_key' => 'aws_s3_active', 'group_name' => 'image', 'config_value' => 0), array('config_key' => 'aws_access_key', 'group_name' => 'image', 'config_value' => ''), array('config_key' => 'aws_secret_key', 'group_name' => 'image', 'config_value' => ''), array('config_key' => 'aws_s3_bucket', 'group_name' => 'image', 'config_value' => ''), array('config_key' => 'aws_s3_domain', 'group_name' => 'image', 'config_value' => 0), array('config_key' => 'disallow_nudes', 'group_name' => 'image', 'config_value' => 0), array('config_key' => 'html_head', 'group_name' => 'general', 'config_value' => ''), array('config_key' => 'html_footer', 'group_name' => 'general', 'config_value' => ''), array('config_key' => 'login_to_contact', 'group_name' => 'advertisement', 'config_value' => 0), array('config_key' => 'custom_css', 'group_name' => 'appearance', 'config_value' => 0), array('config_key' => 'custom_css_version', 'group_name' => 'appearance', 'config_value' => 0), array('config_key' => 'only_admin_post', 'group_name' => 'advertisement', 'config_value' => 0), array('config_key' => 'map_active', 'group_name' => 'appearance', 'config_value' => 1), array('config_key' => 'map_jscode', 'group_name' => 'appearance', 'config_value' => ''), array('config_key' => 'map_settings', 'group_name' => 'appearance', 'config_value' => ''), array('config_key' => 'recaptcha_active', 'group_name' => 'general', 'config_value' => ''), array('config_key' => 'recaptcha_secretkey', 'group_name' => 'general', 'config_value' => ''), array('config_key' => 'recaptcha_sitekey', 'group_name' => 'general', 'config_value' => '')); Model_Config::config_array($configs); //upgrade has_image field to use it as images count $ads = new Model_Ad(); $ads = $ads->where('has_images', '>', 0)->find_all(); if (count($ads)) { foreach ($ads as $ad) { $ad->has_images = 0; //begin with 0 images $route = $ad->image_path(); $folder = DOCROOT . $route; $image_keys = array(); if (is_dir($folder)) { //retrive ad pictures foreach (new DirectoryIterator($folder) as $file) { if (!$file->isDot()) { $key = explode('_', $file->getFilename()); $key = end($key); $key = explode('.', $key); $key = isset($key[0]) ? $key[0] : NULL; if (is_numeric($key)) { if (strpos($file->getFilename(), 'thumb_') === 0) { $image_keys[] = $key; } } } } //count images and reordering file names if (count($image_keys)) { asort($image_keys); foreach ($image_keys as $image_key) { $ad->has_images++; @rename($folder . $ad->seotitle . '_' . $image_key . '.jpg', $folder . $ad->seotitle . '_' . $ad->has_images . '.jpg'); @rename($folder . 'thumb_' . $ad->seotitle . '_' . $image_key . '.jpg', $folder . 'thumb_' . $ad->seotitle . '_' . $ad->has_images . '.jpg'); } } } //update has_images count try { $ad->save(); } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } } } //upgrade categories has_image $images_path = DOCROOT . 'images/categories'; if (is_dir($images_path)) { //retrive cat pictures foreach (new DirectoryIterator($images_path) as $file) { if ($file->isFile()) { $cat_name = str_replace('.png', '', $file->getFilename()); $cat = new Model_Category(); $cat->where('seoname', '=', $cat_name)->find(); if ($cat->loaded()) { $cat->has_image = 1; $cat->save(); } } } } //upgrade locations has_image $images_path = DOCROOT . 'images/locations'; if (is_dir($images_path)) { //retrive loc pictures foreach (new DirectoryIterator($images_path) as $file) { if ($file->isFile()) { $loc_name = str_replace('.png', '', $file->getFilename()); $loc = new Model_Location(); $loc->where('seoname', '=', $loc_name)->find(); if ($loc->loaded()) { $loc->has_image = 1; $loc->save(); } } } } //upgrade users has_image $images_path = DOCROOT . 'images/users'; if (is_dir($images_path)) { //retrive user pictures foreach (new DirectoryIterator($images_path) as $file) { if ($file->isFile() and is_numeric($id_user = str_replace('.png', '', $file->getFilename()))) { $user = new Model_User($id_user); if ($user->loaded()) { $user->has_image = 1; $user->save(); } } } } }
/** * Import multiple locations from geonames * @return void */ public function action_geonames() { $this->template->title = __('Geonames'); $this->template->scripts['footer'][] = URL::base('http') . 'themes/default/js/oc-panel/locations-geonames.js'; $location = NULL; if (intval(Core::get('id_location')) > 0) { $location = new Model_Location(Core::get('id_location')); if ($location->loaded()) { Breadcrumbs::add(Breadcrumb::factory()->set_title($location->name)->set_url(Route::url('oc-panel', array('controller' => 'location', 'action' => 'geonames')) . '?id_location=' . $location->id_location)); } else { Alert::set(Alert::ERROR, __('You are selecting a location that does not exist')); $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller()))); } } //update the elements related to that ad if (core::post('geonames_locations') !== "") { $geonames_locations = json_decode(core::post('geonames_locations')); if (count($geonames_locations) > 0) { $obj_location = new Model_Location(); $locations_array = array(); $insert = DB::insert('locations', array('name', 'seoname', 'id_location_parent', 'latitude', 'longitude', 'id_geoname', 'fcodename_geoname', 'order')); $i = 1; $execute = FALSE; foreach ($geonames_locations as $location) { if (!empty($location->name) and !in_array($location->seoname = $obj_location->gen_seoname($location->name), $locations_array)) { $execute = TRUE; $insert = $insert->values(array($location->name, $location->seoname, Core::get('id_location', 1), isset($location->lat) ? $location->lat : NULL, isset($location->long) ? $location->long : NULL, isset($location->id_geoname) ? $location->id_geoname : NULL, isset($location->fcodename_geoname) ? $location->fcodename_geoname : NULL, $i)); $locations_array[] = $location->seoname; $i++; } } // Insert everything with one query. if ($execute == TRUE) { $insert->execute(); Core::delete_cache(); } HTTP::redirect(Route::url('oc-panel', array('controller' => 'location', 'action' => 'index')) . '?id_location=' . Core::get('id_location', 1)); } } else { Alert::set(Alert::INFO, __('Select some locations first.')); } $this->template->content = View::factory('oc-panel/pages/locations/geonames', array('location' => $location)); }
/** * Handle GET requests. */ public function action_index() { try { if (is_numeric($this->request->param('id'))) { $this->action_get(); } else { $output = array(); $ads = new Model_Ad(); $ads->where('status', '=', Model_Ad::STATUS_PUBLISHED); //search with lat and long!! nice! if (isset($this->_params['latitude']) and isset($this->_params['longitude'])) { $ads->select(array(DB::expr('degrees(acos(sin(radians(' . $this->_params['latitude'] . ')) * sin(radians(`latitude`)) + cos(radians(' . $this->_params['latitude'] . ')) * cos(radians(`latitude`)) * cos(radians(abs(' . $this->_params['longitude'] . ' - `longitude`))))) * 69.172'), 'distance'))->where('latitude', 'IS NOT', NULL)->where('longitude', 'IS NOT', NULL); //we unset the search by lat and long if not will be duplicated unset($this->_filter_params['latitude']); unset($this->_filter_params['longitude']); } //only published ads $ads->where('status', '=', Model_Ad::STATUS_PUBLISHED); //if ad have passed expiration time dont show if (core::config('advertisement.expire_date') > 0) { $ads->where(DB::expr('DATE_ADD( published, INTERVAL ' . core::config('advertisement.expire_date') . ' DAY)'), '>', Date::unix2mysql()); } //make a search with q? param if (isset($this->_params['q']) and strlen($this->_params['q'])) { if (core::config('general.search_by_description') == TRUE) { $ads->where_open()->where('title', 'like', '%' . $this->_params['q'] . '%')->or_where('description', 'like', '%' . $this->_params['q'] . '%')->where_close(); } else { $ads->where('title', 'like', '%' . $this->_params['q'] . '%'); } } //getting all the ads of a category. if (isset($this->_filter_params['id_category']) and is_numeric($this->_filter_params['id_category']['value'])) { $category = new Model_Category($this->_filter_params['id_category']['value']); if ($category->loaded()) { $ads->where('id_category', 'in', $category->get_siblings_ids()); unset($this->_filter_params['id_category']); } } //getting all the ads of a location. if (isset($this->_filter_params['id_location']) and is_numeric($this->_filter_params['id_location']['value'])) { $location = new Model_Location($this->_filter_params['id_location']['value']); if ($location->loaded()) { $ads->where('id_location', 'in', $location->get_siblings_ids()); unset($this->_filter_params['id_location']); } } //filter results by param, verify field exists and has a value $ads->api_filter($this->_filter_params); //how many? used in header X-Total-Count $count = $ads->count_all(); //by default sort by published date if (empty($this->_sort)) { $this->_sort['published'] = 'desc'; } //after counting sort values $ads->api_sort($this->_sort); //we add the order by in case was specified, this is not a column so we need to do it manually if (isset($this->_sort['distance']) and isset($this->_params['latitude']) and isset($this->_params['longitude'])) { $ads->order_by('distance', $this->_sort['distance']); } //pagination with headers $pagination = $ads->api_pagination($count, $this->_params['items_per_page']); $ads = $ads->cached()->find_all(); //as array foreach ($ads as $ad) { $a = $ad->as_array(); $a['price'] = i18n::money_format($ad->price); $a['thumb'] = $ad->get_first_image(); $a['customfields'] = Model_Field::get_by_category($ad->id_category); //sorting by distance, lets add it! if (isset($ad->distance)) { $a['distance'] = i18n::format_measurement($ad->distance); } $a['url'] = Route::url('ad', array('category' => $ad->category->seoname, 'seotitle' => $ad->seotitle)); $output[] = $a; } $this->rest_output(array('ads' => $output), 200, $count, $pagination !== FALSE ? $pagination : NULL); } } catch (Kohana_HTTP_Exception $khe) { $this->_error($khe); } }
/** * * NEW ADVERTISEMENT * */ public function action_index() { //Detect early spam users, show him alert if (core::config('general.black_list') == TRUE and Model_User::is_spam(Core::post('email')) === TRUE) { Alert::set(Alert::ALERT, __('Your profile has been disable for posting, due to recent spam content! If you think this is a mistake please contact us.')); $this->redirect('default'); } //advertisement.only_admin_post if (Core::config('advertisement.only_admin_post') == 1 and (!Auth::instance()->logged_in() or Auth::instance()->logged_in() and Auth::instance()->get_user()->id_role != Model_Role::ROLE_ADMIN)) { $this->redirect('default'); } if (Core::post('ajaxValidateCaptcha')) { $this->auto_render = FALSE; $this->template = View::factory('js'); if (captcha::check('publish_new', TRUE)) { $this->template->content = 'true'; } else { $this->template->content = 'false'; } return; } //template header $this->template->title = __('Publish new advertisement'); $this->template->meta_description = __('Publish new advertisement'); $this->template->styles = array('css/jquery.sceditor.default.theme.min.css' => 'screen', 'css/jasny-bootstrap.min.css' => 'screen', '//cdn.jsdelivr.net/sweetalert/0.1.2/sweet-alert.min.css' => 'screen'); $this->template->scripts['footer'][] = 'js/jquery.sceditor.bbcode.min.js'; $this->template->scripts['footer'][] = 'js/jasny-bootstrap.min.js'; $this->template->scripts['footer'][] = 'js/jquery.chained.min.js'; $this->template->scripts['footer'][] = '//cdn.jsdelivr.net/sweetalert/0.1.2/sweet-alert.min.js'; $this->template->scripts['footer'][] = '//cdnjs.cloudflare.com/ajax/libs/ouibounce/0.0.10/ouibounce.min.js'; if (core::config('advertisement.map_pub_new')) { $this->template->scripts['footer'][] = '//maps.google.com/maps/api/js?sensor=false&libraries=geometry&v=3.7'; $this->template->scripts['footer'][] = '//cdn.jsdelivr.net/gmaps/0.4.15/gmaps.min.js'; } $this->template->scripts['footer'][] = 'js/new.js?v=' . Core::VERSION; // redirect to login, if conditions are met if (core::config('advertisement.login_to_post') == TRUE and !Auth::instance()->logged_in()) { Alert::set(Alert::INFO, __('Please, login before posting advertisement!')); HTTP::redirect(Route::url('oc-panel', array('controller' => 'auth', 'action' => 'login'))); } //find all, for populating form select fields $categories = Model_Category::get_as_array(); $order_categories = Model_Category::get_multidimensional(); $order_parent_deep = Model_Category::get_by_deep(); // NO categories redirect ADMIN to categories panel if (count($order_categories) == 0) { if (Auth::instance()->logged_in() and Auth::instance()->get_user()->id_role == Model_Role::ROLE_ADMIN) { Alert::set(Alert::INFO, __('Please, first create some categories.')); $this->redirect(Route::url('oc-panel', array('controller' => 'category', 'action' => 'index'))); } else { Alert::set(Alert::INFO, __('Posting advertisements is not yet available.')); $this->redirect('default'); } } //get locations $locations = Model_Location::get_as_array(); $order_locations = Model_Location::get_multidimensional(); $loc_parent_deep = Model_Location::get_by_deep(); // bool values from DB, to show or hide this fields in view $form_show = array('captcha' => core::config('advertisement.captcha'), 'website' => core::config('advertisement.website'), 'phone' => core::config('advertisement.phone'), 'location' => core::config('advertisement.location'), 'address' => core::config('advertisement.address'), 'price' => core::config('advertisement.price')); $id_category = NULL; $selected_category = new Model_Category(); //if theres a category by post or by get if (Core::request('category') !== NULL) { if (is_numeric(Core::request('category'))) { $selected_category->where('id_category', '=', core::request('category'))->limit(1)->find(); } else { $selected_category->where('seoname', '=', core::request('category'))->limit(1)->find(); } if ($selected_category->loaded()) { $id_category = $selected_category->id_category; } } $id_location = NULL; $selected_location = new Model_Location(); //if theres a location by post or by get if (Core::request('location') !== NULL) { if (is_numeric(Core::request('location'))) { $selected_location->where('id_location', '=', core::request('location'))->limit(1)->find(); } else { $selected_location->where('seoname', '=', core::request('location'))->limit(1)->find(); } if ($selected_location->loaded()) { $id_location = $selected_location->id_location; } } //render view publish new $this->template->content = View::factory('pages/ad/new', array('categories' => $categories, 'order_categories' => $order_categories, 'order_parent_deep' => $order_parent_deep, 'locations' => $locations, 'order_locations' => $order_locations, 'loc_parent_deep' => $loc_parent_deep, 'form_show' => $form_show, 'id_category' => $id_category, 'selected_category' => $selected_category, 'id_location' => $id_location, 'selected_location' => $selected_location, 'fields' => Model_Field::get_all())); if ($this->request->post()) { if (captcha::check('publish_new')) { $data = $this->request->post(); $validation = Validation::factory($data); //validate location since its optional if (core::config('advertisement.location')) { if (count($locations) > 1) { $validation = $validation->rule('location', 'not_empty')->rule('location', 'digit'); } } //user is not logged in validate input if (!Auth::instance()->logged_in()) { $validation = $validation->rule('email', 'not_empty')->rule('email', 'email')->rule('name', 'not_empty')->rule('name', 'min_length', array(':value', 2))->rule('name', 'max_length', array(':value', 145)); } if ($validation->check()) { // User detection, if doesnt exists create if (!Auth::instance()->logged_in()) { $user = Model_User::create_email(core::post('email'), core::post('name')); } else { $user = Auth::instance()->get_user(); } //to make it backward compatible with older themes: UGLY!! if (isset($data['category']) and is_numeric($data['category'])) { $data['id_category'] = $data['category']; unset($data['category']); } if (isset($data['location']) and is_numeric($data['location'])) { $data['id_location'] = $data['location']; unset($data['location']); } //lets create!! $return = Model_Ad::new_ad($data, $user); //there was an error on the validation if (isset($return['validation_errors']) and is_array($return['validation_errors'])) { foreach ($return['validation_errors'] as $f => $err) { Alert::set(Alert::ALERT, $err); } } elseif (isset($return['error'])) { Alert::set($return['error_type'], $return['error']); } elseif (isset($return['message']) and isset($return['ad'])) { $new_ad = $return['ad']; // IMAGE UPLOAD $filename = NULL; for ($i = 0; $i < core::config('advertisement.num_images'); $i++) { if (isset($_FILES['image' . $i])) { $filename = $new_ad->save_image($_FILES['image' . $i]); } if ($filename) { $new_ad->has_images++; } } //since theres images save the ad again... if ($new_ad->has_images > 0) { try { $new_ad->save(); } catch (Exception $e) { throw HTTP_Exception::factory(500, $e->getMessage()); } } Alert::set(Alert::SUCCESS, $return['message']); //redirect user if (isset($return['checkout_url']) and !empty($return['checkout_url'])) { $this->redirect($return['checkout_url']); } else { $this->redirect(Route::url('default', array('action' => 'thanks', 'controller' => 'ad', 'id' => $new_ad->id_ad))); } } } else { $errors = $validation->errors('ad'); foreach ($errors as $f => $err) { Alert::set(Alert::ALERT, $err); } } } else { Alert::set(Alert::ALERT, __('Captcha is not correct')); } } }
public function action_import_tool() { $this->template->title = __('Import tool for locations and categories'); Breadcrumbs::add(Breadcrumb::factory()->set_title($this->template->title)); //sending a CSV if ($_POST) { foreach ($_FILES as $file => $path) { $csv = $path["tmp_name"]; $csv_2[] = $file; if ($path['size'] > 1048576) { Alert::set(Alert::ERROR, __('1 MB file')); $this->redirect(Route::url('oc-panel', array('controller' => 'tools', 'action' => 'import_tool'))); } if ($file == 'csv_file_categories' and $csv != FALSE) { $expected_header = array('name', 'category_parent', 'price'); $cat_array = Core::csv_to_array($csv, $expected_header); if (count($cat_array) > 10000) { Alert::set(Alert::ERROR, __('limited to 10.000 at a time')); $this->redirect(Route::url('oc-panel', array('controller' => 'tools', 'action' => 'import_tool'))); } if ($cat_array === FALSE) { Alert::set(Alert::ERROR, __('Something went wrong, please check format of the file! Remove single quotes or strange characters, in case you have any.')); } else { foreach ($cat_array as $cat) { //category parent was sent? if ($cat[1]) { $category_parent = new Model_Category(); $category_parent->where('name', '=', $cat[1])->limit(1)->find(); if ($category_parent->loaded()) { $cat[1] = $category_parent->id_category; } else { $cat[1] = 1; } } else { $cat[1] = 1; } Model_Category::create_name($cat[0], 0, $cat[1], 0, $cat[2]); } Core::delete_cache(); Alert::set(Alert::SUCCESS, __('Categories successfully imported.')); } } elseif ($file == 'csv_file_locations' and $csv != FALSE) { $expected_header = array('name', 'location_parent', 'latitude', 'longitude'); $loc_array = Core::csv_to_array($csv, $expected_header); if (count($loc_array) > 10000) { Alert::set(Alert::ERROR, __('limited to 10.000 at a time')); $this->redirect(Route::url('oc-panel', array('controller' => 'tools', 'action' => 'import_tool'))); } if ($loc_array === FALSE) { Alert::set(Alert::ERROR, __('Something went wrong, please check format of the file! Remove single quotes or strange characters, in case you have any.')); } else { foreach ($loc_array as $loc) { //location parent was sent? if ($loc[1]) { $location_parent = new Model_Location(); $location_parent->where('name', '=', $loc[1])->limit(1)->find(); if ($location_parent->loaded()) { $loc[1] = $location_parent->id_location; } else { $loc[1] = 1; } } else { $loc[1] = 1; } Model_Location::create_name($loc[0], 0, $loc[1], 0, $loc[2], $loc[3]); } Core::delete_cache(); Alert::set(Alert::SUCCESS, __('Locations successfully imported.')); } } } } $this->template->content = View::factory('oc-panel/pages/tools/import_tool'); }
/** * counts how many ads have each category * @param boolean $location_filter filters by location * @param Model_Location $location * @return array */ public static function get_category_count($location_filter = TRUE, $location = NULL) { //cache by location if ($location_filter === TRUE and $location and $location->loaded()) { $id_location = $location->id_location; } elseif ($location_filter === TRUE and Model_Location::current()->loaded()) { $id_location = Model_Location::current()->id_location; } else { $id_location = 'all'; } //name used in the cache for storage $cache_name = 'get_category_count_' . $id_location; if (($cats_count = Core::cache($cache_name)) === NULL) { $expr_date = is_numeric(core::config('advertisement.expire_date')) ? core::config('advertisement.expire_date') : 0; $db_prefix = Database::instance('default')->table_prefix(); //get the categories that have ads id_category->num ads $count_ads = DB::select('c.id_category', array(DB::expr('COUNT("a.id_ad")'), 'count'))->from(array('categories', 'c'))->join(array('ads', 'a'))->using('id_category')->where('a.id_category', '=', DB::expr($db_prefix . 'c.id_category'))->where(DB::expr('IF(' . $expr_date . ' <> 0, DATE_ADD( published, INTERVAL ' . $expr_date . ' DAY), DATE_ADD( NOW(), INTERVAL 1 DAY))'), '>', Date::unix2mysql())->where('a.status', '=', Model_Ad::STATUS_PUBLISHED); //filter the count by location if ($location_filter === TRUE and $location and $location->loaded()) { $count_ads = $count_ads->where('a.id_location', 'in', $location->get_siblings_ids()); } elseif ($location_filter === TRUE and Model_Location::current()->loaded()) { $count_ads = $count_ads->where('a.id_location', 'in', Model_Location::current()->get_siblings_ids()); } $count_ads = $count_ads->group_by('c.id_category')->order_by('c.order', 'asc')->cached()->execute(); $count_ads = $count_ads->as_array('id_category'); //getting the count of ads into the parents $parents_count = array(); foreach ($count_ads as $count_ad) { $id_category = $count_ad['id_category']; $count = $count_ad['count']; //adding himself if doesnt exists if (!isset($parents_count[$id_category])) { $parents_count[$id_category] = $count_ad; $parents_count[$id_category]['has_siblings'] = FALSE; } $category = new Model_Category($id_category); //for each parent of this category add the count $parents_ids = $category->get_parents_ids(); if (count($parents_ids) > 0) { foreach ($parents_ids as $id) { if (isset($parents_count[$id])) { $parents_count[$id]['count'] += $count_ads[$category->id_category]['count']; } else { $parents_count[$id]['count'] = $count_ads[$category->id_category]['count']; } $parents_count[$id]['has_siblings'] = TRUE; } } } //get all the categories with level 0 and 1 $categories = new self(); $categories = $categories->where('id_category', '!=', 1)->where('parent_deep', 'IN', array(0, 1))->order_by('order', 'asc')->cached()->find_all(); //generating the array $cats_count = array(); foreach ($categories as $category) { $has_siblings = isset($parents_count[$category->id_category]) ? $parents_count[$category->id_category]['has_siblings'] : FALSE; //they may not have counted the siblings since the count was 0 but he actually has siblings... if ($has_siblings === FALSE and $category->has_siblings()) { $has_siblings = TRUE; } $cats_count[$category->id_category] = $category->as_array(); $cats_count[$category->id_category] = array('id_category' => $category->id_category, 'seoname' => $category->seoname, 'name' => $category->name, 'id_category_parent' => $category->id_category_parent, 'parent_deep' => $category->parent_deep, 'order' => $category->order, 'price' => $category->price, 'has_siblings' => $has_siblings, 'count' => isset($parents_count[$category->id_category]) ? $parents_count[$category->id_category]['count'] : 0); } //cache the result is expensive! Core::cache($cache_name, $cats_count); } return $cats_count; }
/** * CRUD controller: DELETE */ public function action_delete() { $this->auto_render = FALSE; $locations = array(); if ($id_location = $this->request->param('id')) { $locations[] = $id_location; } elseif (core::post('locations')) { $locations = core::post('locations'); } if (count($locations) > 0) { foreach ($locations as $id_location) { $location = new Model_Location($id_location); //update the elements related to that ad if ($location->loaded()) { //check if the parent is loaded/exists avoiding errors, if doesnt exist to the root $parent_loc = new Model_Location($location->id_location_parent); if ($parent_loc->loaded()) { $id_location_parent = $location->id_location_parent; } else { $id_location_parent = 1; } //update all the siblings this location has and set the location parent $query = DB::update('locations')->set(array('id_location_parent' => $id_location_parent))->where('id_location_parent', '=', $location->id_location)->execute(); //update all the ads this location has and set the location parent $query = DB::update('ads')->set(array('id_location' => $id_location_parent))->where('id_location', '=', $location->id_location)->execute(); try { $location_name = $location->name; $location->delete(); $this->template->content = 'OK'; //recalculating the deep of all the categories $this->action_deep(); Core::delete_cache(); Alert::set(Alert::SUCCESS, sprintf(__('Location %s deleted'), $location_name)); } catch (Exception $e) { Alert::set(Alert::ERROR, $e->getMessage()); } } else { Alert::set(Alert::SUCCESS, __('Location not deleted')); } } } HTTP::redirect(Route::url('oc-panel', array('controller' => 'location', 'action' => 'index'))); }
/** * CRUD controller: DELETE */ public function action_delete() { $this->auto_render = FALSE; $location = new Model_Location($this->request->param('id')); //update the elements related to that ad if ($location->loaded()) { //check if the parent is loaded/exists avoiding errors, if doesnt exist to the root $parent_loc = new Model_Location($location->id_location_parent); if ($parent_loc->loaded()) { $id_location_parent = $location->id_location_parent; } else { $id_location_parent = 1; } //update all the siblings this location has and set the location parent $query = DB::update('locations')->set(array('id_location_parent' => $id_location_parent))->where('id_location_parent', '=', $location->id_location)->execute(); //update all the ads this location has and set the location parent $query = DB::update('ads')->set(array('id_location' => $id_location_parent))->where('id_location', '=', $location->id_location)->execute(); //delete icon_delete $root = DOCROOT . 'images/locations/'; //root folder if (is_dir($root)) { @unlink($root . $location->seoname . '.png'); // delete icon from Amazon S3 if (core::config('image.aws_s3_active')) { $s3->deleteObject(core::config('image.aws_s3_bucket'), 'images/locations/' . $location->seoname . '.png'); } // update location info $location->has_image = 0; $location->last_modified = Date::unix2mysql(); $location->save(); } try { $location->delete(); $this->template->content = 'OK'; //recalculating the deep of all the categories $this->action_deep(); Core::delete_cache(); Alert::set(Alert::SUCCESS, __('Location deleted')); } catch (Exception $e) { Alert::set(Alert::ERROR, $e->getMessage()); } } else { Alert::set(Alert::SUCCESS, __('Location not deleted')); } HTTP::redirect(Route::url('oc-panel', array('controller' => 'location', 'action' => 'index'))); }
/** * * NEW ADVERTISEMENT * */ public function action_index() { //advertisement.only_admin_post if (Core::config('advertisement.only_admin_post') == TRUE and (!Auth::instance()->logged_in() or Auth::instance()->logged_in() and !$this->user->is_admin())) { $this->redirect(Route::url('default')); } elseif ((Core::config('advertisement.login_to_post') == TRUE or Core::config('payment.stripe_connect') == TRUE or Core::config('general.subscriptions') == TRUE) and !Auth::instance()->logged_in()) { Alert::set(Alert::INFO, __('Please, login before posting advertisement!')); HTTP::redirect(Route::url('oc-panel', array('controller' => 'auth', 'action' => 'login')) . '?auth_redirect=' . URL::current()); } elseif (core::config('general.black_list') == TRUE and Model_User::is_spam(Core::post('email')) === TRUE) { Alert::set(Alert::ALERT, __('Your profile has been disable for posting, due to recent spam content! If you think this is a mistake please contact us.')); $this->redirect(Route::url('default')); } elseif (Core::config('payment.stripe_connect') == TRUE and empty($this->user->stripe_user_id)) { Alert::set(Alert::INFO, __('Please, connect with Stripe')); $this->redirect(Route::url('oc-panel', array('controller' => 'profile', 'action' => 'edit'))); } elseif (Core::config('general.subscriptions') == TRUE and Theme::get('premium') == TRUE) { $subscription = $this->user->subscription(); //if theres no subscription or expired or without free ads if (!$subscription->loaded() or $subscription->loaded() and (Date::mysql2unix($subscription->expire_date) < time() or $subscription->amount_ads_left == 0)) { Alert::set(Alert::INFO, __('Please, choose a plan first')); HTTP::redirect(Route::url('pricing')); } } //validates captcha if (Core::post('ajaxValidateCaptcha')) { $this->auto_render = FALSE; $this->template = View::factory('js'); if (captcha::check('publish_new', TRUE)) { $this->template->content = 'true'; } else { $this->template->content = 'false'; } return; } Controller::$full_width = TRUE; //template header $this->template->title = __('Publish new advertisement'); $this->template->meta_description = __('Publish new advertisement'); $this->template->styles = array('css/jquery.sceditor.default.theme.min.css' => 'screen', 'css/jasny-bootstrap.min.css' => 'screen', '//cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.1/css/selectize.bootstrap3.min.css' => 'screen', '//cdn.jsdelivr.net/sweetalert/1.1.3/sweetalert.css' => 'screen'); $this->template->scripts['footer'][] = 'js/jquery.sceditor.bbcode.min.js'; $this->template->scripts['footer'][] = 'js/jasny-bootstrap.min.js'; $this->template->scripts['footer'][] = '//cdn.jsdelivr.net/sweetalert/1.1.3/sweetalert.min.js'; $this->template->scripts['footer'][] = '//cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.1/js/standalone/selectize.min.js'; $this->template->scripts['footer'][] = '//cdnjs.cloudflare.com/ajax/libs/ouibounce/0.0.10/ouibounce.min.js'; $this->template->scripts['footer'][] = 'js/canvasResize.js'; if (core::config('advertisement.map_pub_new')) { $this->template->scripts['async_defer'][] = '//maps.google.com/maps/api/js?libraries=geometry&v=3&key=' . core::config("advertisement.gm_api_key") . '&callback=initLocationsGMap'; } $this->template->scripts['footer'][] = 'js/new.js?v=' . Core::VERSION; $categories = new Model_Category(); $categories = $categories->where('id_category_parent', '=', '1'); // NO categories redirect ADMIN to categories panel if ($categories->count_all() == 0) { if (Auth::instance()->logged_in() and Auth::instance()->get_user()->is_admin()) { Alert::set(Alert::INFO, __('Please, first create some categories.')); $this->redirect(Route::url('oc-panel', array('controller' => 'category', 'action' => 'index'))); } else { Alert::set(Alert::INFO, __('Posting advertisements is not yet available.')); $this->redirect(Route::url('default')); } } //get locations $locations = new Model_Location(); $locations = $locations->where('id_location', '!=', '1'); // bool values from DB, to show or hide this fields in view $form_show = array('captcha' => core::config('advertisement.captcha'), 'website' => core::config('advertisement.website'), 'phone' => core::config('advertisement.phone'), 'location' => core::config('advertisement.location'), 'description' => core::config('advertisement.description'), 'address' => core::config('advertisement.address'), 'price' => core::config('advertisement.price')); $id_category = NULL; $selected_category = new Model_Category(); //if theres a category by post or by get if (Core::request('category') !== NULL) { if (is_numeric(Core::request('category'))) { $selected_category->where('id_category', '=', core::request('category'))->limit(1)->find(); } else { $selected_category->where('seoname', '=', core::request('category'))->limit(1)->find(); } if ($selected_category->loaded()) { $id_category = $selected_category->id_category; } } $id_location = NULL; $selected_location = new Model_Location(); //if theres a location by post or by get if (Core::request('location') !== NULL) { if (is_numeric(Core::request('location'))) { $selected_location->where('id_location', '=', core::request('location'))->limit(1)->find(); } else { $selected_location->where('seoname', '=', core::request('location'))->limit(1)->find(); } if ($selected_location->loaded()) { $id_location = $selected_location->id_location; } } //render view publish new $this->template->content = View::factory('pages/ad/new', array('form_show' => $form_show, 'id_category' => $id_category, 'selected_category' => $selected_category, 'id_location' => $id_location, 'selected_location' => $selected_location, 'fields' => Model_Field::get_all())); if ($this->request->post()) { if (captcha::check('publish_new')) { $data = $this->request->post(); $validation = Validation::factory($data); //validate location since its optional if (core::config('advertisement.location')) { if ($locations->count_all() > 1) { $validation = $validation->rule('location', 'not_empty')->rule('location', 'digit'); } } //user is not logged in validate input if (!Auth::instance()->logged_in()) { $validation = $validation->rule('email', 'not_empty')->rule('email', 'email')->rule('email', 'email_domain')->rule('name', 'not_empty')->rule('name', 'min_length', array(':value', 2))->rule('name', 'max_length', array(':value', 145)); } // Optional banned words validation if (core::config('advertisement.validate_banned_words')) { $validation = $validation->rule('title', 'no_banned_words'); $validation = $validation->rule('description', 'no_banned_words'); } if ($validation->check()) { // User detection, if doesnt exists create if (!Auth::instance()->logged_in()) { $user = Model_User::create_email(core::post('email'), core::post('name')); } else { $user = Auth::instance()->get_user(); } //to make it backward compatible with older themes: UGLY!! if (isset($data['category']) and is_numeric($data['category'])) { $data['id_category'] = $data['category']; unset($data['category']); } if (isset($data['location']) and is_numeric($data['location'])) { $data['id_location'] = $data['location']; unset($data['location']); } //lets create!! $return = Model_Ad::new_ad($data, $user); //there was an error on the validation if (isset($return['validation_errors']) and is_array($return['validation_errors'])) { foreach ($return['validation_errors'] as $f => $err) { Alert::set(Alert::ALERT, $err); } } elseif (isset($return['error'])) { Alert::set($return['error_type'], $return['error']); } elseif (isset($return['message']) and isset($return['ad'])) { $new_ad = $return['ad']; // IMAGE UPLOAD $filename = NULL; for ($i = 0; $i < core::config('advertisement.num_images'); $i++) { if (Core::post('base64_image' . $i)) { $filename = $new_ad->save_base64_image(Core::post('base64_image' . $i)); } elseif (isset($_FILES['image' . $i])) { $filename = $new_ad->save_image($_FILES['image' . $i]); } } Alert::set(Alert::SUCCESS, $return['message']); //redirect user if (isset($return['checkout_url']) and !empty($return['checkout_url'])) { $this->redirect($return['checkout_url']); } else { $this->redirect(Route::url('default', array('action' => 'thanks', 'controller' => 'ad', 'id' => $new_ad->id_ad))); } } } else { $errors = $validation->errors('ad'); foreach ($errors as $f => $err) { Alert::set(Alert::ALERT, $err); } } } else { Alert::set(Alert::ALERT, __('Captcha is not correct')); } } }
public function action_index() { if (core::config('general.auto_locate')) { if ($user_location = Core::post('user_location')) { Cookie::set('user_location', $user_location); $this->auto_render = FALSE; $this->template = View::factory('js'); $this->template->content = TRUE; return; } elseif (Core::get('user_location') == '0') { Cookie::delete('user_location'); } Theme::$scripts['footer'][] = '//maps.google.com/maps/api/js?sensor=false&libraries=geometry&v=3.7'; Theme::$scripts['footer'][] = '//cdn.jsdelivr.net/gmaps/0.4.15/gmaps.min.js'; } //template header $this->template->title = ''; // $this->template->meta_keywords = 'keywords'; if (core::config('general.site_description') != '') { $this->template->meta_description = core::config('general.site_description'); } else { $this->template->meta_description = core::config('general.site_name') . ' ' . __('official homepage, get your post listed now.'); } //setting main view/template and render pages // get user location if any $user_location = NULL; if (is_numeric($user_id_location = Cookie::get('user_location'))) { $user_location = new Model_Location($user_id_location); if (!$user_location->loaded()) { $user_location = NULL; } } // swith to decide on ads_in_home $ads = new Model_Ad(); $ads->where('status', '=', Model_Ad::STATUS_PUBLISHED); if ($user_location) { $ads->where('id_location', 'in', $user_location->get_siblings_ids()); } $ads_in_home = core::config('advertisement.ads_in_home'); //in case we do not count visits we cant show popular if (core::config('advertisement.count_visits') == 0 and $ads_in_home == 2) { $ads_in_home = 0; } switch ($ads_in_home) { case 2: $id_ads = array_keys(Model_Visit::popular_ads()); if (count($id_ads) > 0) { $ads->where('id_ad', 'IN', $id_ads); } break; case 1: $ads->where('featured', 'IS NOT', NULL)->where('featured', '>=', Date::unix2mysql())->order_by('featured', 'desc'); break; case 4: $ads->where('featured', 'IS NOT', NULL)->where('featured', '>=', Date::unix2mysql())->order_by(DB::expr('RAND()')); break; case 0: default: $ads->order_by('published', 'desc'); break; } //if ad have passed expiration time dont show if (core::config('advertisement.expire_date') > 0) { $ads->where(DB::expr('DATE_ADD( published, INTERVAL ' . core::config('advertisement.expire_date') . ' DAY)'), '>', Date::unix2mysql()); } $ads = $ads->limit(Theme::get('num_home_latest_ads', 4))->cached()->find_all(); $categs = Model_Category::get_category_count(TRUE, $user_location); $locats = Model_Location::get_location_count(); $auto_locats = NULL; $auto_location_distance = Core::config('general.measurement') == 'imperial' ? Num::round(Core::config('advertisement.auto_locate_distance') * 1.60934) : Core::config('advertisement.auto_locate_distance'); if (core::config('general.auto_locate') and !isset($_COOKIE['cancel_auto_locate']) and Model_User::get_userlatlng()) { $auto_locats = new Model_Location(); $auto_locats = $auto_locats->select(array(DB::expr('degrees(acos(sin(radians(' . $_COOKIE['mylat'] . ')) * sin(radians(`latitude`)) + cos(radians(' . $_COOKIE['mylat'] . ')) * cos(radians(`latitude`)) * cos(radians(abs(' . $_COOKIE['mylng'] . ' - `longitude`))))) * 111.321'), 'distance'))->where('latitude', 'IS NOT', NULL)->where('longitude', 'IS NOT', NULL)->having('distance', '<=', $auto_location_distance)->order_by('distance', 'asc')->find_all()->as_array(); } $this->template->bind('content', $content); $this->template->content = View::factory('pages/home', compact('ads', 'categs', 'locats', 'auto_locats', 'user_location')); }