function __construct() { parent::__construct(); osc_run_hook('init_admin'); // check if exist a new version each day if (time() - osc_last_version_check() > 24 * 3600) { $data = osc_file_get_contents('http://osclass.org/latest_version.php?callback=?'); $data = preg_replace('|^\\?\\((.*?)\\);$|', '$01', $data); $json = json_decode($data); if ($json->version > osc_version()) { osc_set_preference('update_core_json', $data); } else { osc_set_preference('update_core_json', ''); } osc_set_preference('last_version_check', time()); osc_reset_preferences(); } $config_version = str_replace('.', '', OSCLASS_VERSION); $config_version = preg_replace('|-.*|', '', $config_version); if ($config_version > Preference::newInstance()->get('version')) { if (get_class($this) == 'CAdminTools') { } else { if (get_class($this) != 'CAdminUpgrade') { $this->redirectTo(osc_admin_base_url(true) . '?page=upgrade'); } } } }
function osc_latestTweets($num = 5) { require_once osc_lib_path() . 'osclass/classes/Cache.php'; $cache = new Cache('admin-twitter', 900); if ($cache->check()) { return $cache->retrieve(); } $list = array(); $content = osc_file_get_contents('https://twitter.com/statuses/user_timeline/osclass.rss'); if ($content) { $xml = simplexml_load_string($content); if (isset($xml->error)) { return $list; } $count = 0; foreach ($xml->channel->item as $item) { $list[] = array('link' => strval($item->link), 'title' => strval($item->title), 'pubDate' => strval($item->pubDate)); $count++; if ($count == $num) { break; } } } $cache->store($list); return $list; }
function __construct() { parent::__construct(); // check if is moderator and can enter to this page if ($this->isModerator()) { if (!in_array($this->page, array('items', 'comments', 'media', 'login', 'admins', 'ajax', 'stats', ''))) { osc_add_flash_error_message(_m("You don't have enough permissions"), 'admin'); $this->redirectTo(osc_admin_base_url()); } } osc_run_hook('init_admin'); // check if exist a new version each day if (time() - osc_last_version_check() > 24 * 3600) { $data = osc_file_get_contents('http://osclass.org/latest_version.php?callback=?'); $data = preg_replace('|^\\?\\((.*?)\\);$|', '$01', $data); $json = json_decode($data); if ($json->version > osc_version()) { osc_set_preference('update_core_json', $data); } else { osc_set_preference('update_core_json', ''); } osc_set_preference('last_version_check', time()); osc_reset_preferences(); } $config_version = str_replace('.', '', OSCLASS_VERSION); $config_version = preg_replace('|-.*|', '', $config_version); if ($config_version > Preference::newInstance()->get('version')) { if (get_class($this) == 'CAdminTools') { } else { if (get_class($this) != 'CAdminUpgrade') { $this->redirectTo(osc_admin_base_url(true) . '?page=upgrade'); } } } // show messages subscribed $status_subscribe = Params::getParam('subscribe_osclass'); if ($status_subscribe != '') { switch ($status_subscribe) { case -1: osc_add_flash_error_message(_m('Entered an invalid email'), 'admin'); break; case 0: osc_add_flash_warning_message(_m("You're already subscribed"), 'admin'); break; case 1: osc_add_flash_ok_message(_m('Subscribed correctly'), 'admin'); break; default: osc_add_flash_warning_message(_m("Error subscribing"), 'admin'); break; } } // show donation successful if (Params::getParam('donation') == 'successful') { osc_add_flash_ok_message(_m('Thank you very much for your donation'), 'admin'); } }
/** * Create and print a "Pay with Paypal" button * * @param float $amount * @param string $description * @param string $itemnumber (publish fee, premium, pack and which category) * @param string $extra custom variables */ public static function button($amount = '0.00', $description = '', $itemnumber = '101', $extra_array = null) { if (osc_get_preference('currency', 'payment') != 'BTC') { $amount = osc_file_get_contents("https://blockchain.info/tobtc?currency=" . osc_get_preference('currency', 'payment') . "&value=" . $amount); } $extra = payment_prepare_custom($extra_array); $extra .= 'concept,' . $description . '|'; $extra .= 'product,' . $itemnumber . '|'; $r = rand(0, 1000); $extra .= 'random,' . $r; $CALLBACK_URL = osc_base_url() . 'oc-content/plugins/' . osc_plugin_folder(__FILE__) . 'callback.php?extra=' . $extra; ?> <li class="payment bitcoin-btn"> <div class="blockchain-btn" data-address="<?php echo osc_get_preference('blockchain_btc_address', 'payment'); ?> " data-anonymous="false" data-callback="<?php echo $CALLBACK_URL; ?> "> <div class="blockchain stage-begin"> <img src="<?php echo osc_base_url() . 'oc-content/plugins/' . osc_plugin_folder(__FILE__); ?> pay_now_64.png"> </div> <div class="blockchain stage-loading" style="text-align:center"> <img src="<?php echo osc_base_url() . 'oc-content/plugins/' . osc_plugin_folder(__FILE__); ?> loading-large.gif"> </div> <div class="blockchain stage-ready"> <p align="center"><?php printf(__('Please send %f BTC to <br /> <b>[[address]]</b></p>', 'payment'), $amount); ?> <p align="center" class="qr-code"></p> </div> <div class="blockchain stage-paid"> <?php _e('Payment Received <b>[[value]] BTC</b>. Thank You.', 'payment'); ?> </div> <div class="blockchain stage-error"> <span color="red">[[error]]</span> </div> </div> </li> <?php }
function insert_geo_location($aItem) { $sAddress = isset($aItem['s_address']) ? $aItem['s_address'] : ''; $sRegion = isset($aItem['s_region']) ? $aItem['s_region'] : ''; $sCity = isset($aItem['s_city']) ? $aItem['s_city'] : ''; $address = sprintf('%s, %s %s', $sAddress, $sRegion, $sCity); $response = osc_file_get_contents(sprintf('http://maps.google.com/maps/geo?q=%s&output=json&sensor=false', urlencode($address))); $jsonResponse = json_decode($response); if (isset($jsonResponse->Placemark) && count($jsonResponse->Placemark[0]) > 0) { $coord = $jsonResponse->Placemark[0]->Point->coordinates; ItemLocation::newInstance()->update(array('d_coord_lat' => $coord[1], 'd_coord_long' => $coord[0]), array('fk_i_item_id' => $aItem['pk_i_id'])); } }
function __construct() { parent::__construct(); // check if is moderator and can enter to this page if( $this->isModerator() ) { if( !in_array($this->page, osc_apply_filter('moderator_access', array('items', 'comments', 'media', 'login', 'admins', 'ajax', 'stats',''))) ) { osc_add_flash_error_message(_m("You don't have enough permissions"), 'admin'); $this->redirectTo(osc_admin_base_url()); } } osc_run_hook( 'init_admin' ); // check if exist a new version each day if( (time() - osc_last_version_check()) > (24 * 3600) ) { $data = osc_file_get_contents('http://osclass.org/latest_version_v1.php?callback=?'); $data = preg_replace('|^\?\((.*?)\);$|', '$01', $data); $json = json_decode($data); if( $json->version > osc_version() ) { osc_set_preference( 'update_core_json', $data ); } else { osc_set_preference( 'update_core_json', '' ); } osc_set_preference( 'last_version_check', time() ); osc_reset_preferences(); } $config_version = str_replace('.', '', OSCLASS_VERSION); $config_version = preg_replace('|-.*|', '', $config_version); if( $config_version > osc_get_preference('version') ) { if(get_class($this) == 'CAdminTools') { } else { if(get_class($this) != 'CAdminUpgrade' ) $this->redirectTo(osc_admin_base_url(true) . '?page=upgrade'); } } // show donation successful if( Params::getParam('donation') == 'successful' ) { osc_add_flash_ok_message(_m('Thank you very much for your donation'), 'admin'); } // enqueue scripts osc_enqueue_script('jquery'); osc_enqueue_script('jquery-ui'); osc_enqueue_script('admin-osc'); osc_enqueue_script('admin-ui-osc'); }
function insert_geo_location($item) { $itemId = $item['pk_i_id']; $aItem = Item::newInstance()->findByPrimaryKey($itemId); $sAddress = isset($aItem['s_address']) ? $aItem['s_address'] : ''; $sCity = isset($aItem['s_city']) ? $aItem['s_city'] : ''; $sRegion = isset($aItem['s_region']) ? $aItem['s_region'] : ''; $sCountry = isset($aItem['s_country']) ? $aItem['s_country'] : ''; $address = sprintf('%s, %s, %s, %s', $sAddress, $sCity, $sRegion, $sCountry); $response = osc_file_get_contents(sprintf('https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false', urlencode($address))); $jsonResponse = json_decode($response); if (isset($jsonResponse->results[0]->geometry->location) && count($jsonResponse->results[0]->geometry->location) > 0) { $location = $jsonResponse->results[0]->geometry->location; $lat = $location->lat; $lng = $location->lng; ItemLocation::newInstance()->update(array('d_coord_lat' => $lat, 'd_coord_long' => $lng), array('fk_i_item_id' => $itemId)); } }
/** * This functions retrieves a news list from http://osclass.org. It uses the Cache services to speed up the process. */ function osc_listNews() { require_once LIB_PATH . 'osclass/classes/Cache.php'; $cache = new Cache('admin-blog_news', 900); if ($cache->check()) { return $cache->retrieve(); } else { $list = array(); $content = osc_file_get_contents('http://osclass.org/feed/'); if ($content) { $xml = simplexml_load_string($content); foreach ($xml->channel->item as $item) { $list[] = array('link' => strval($item->link), 'title' => strval($item->title), 'pubDate' => strval($item->pubDate)); } } $cache->store($list); } return $list; }
function listcloud_CloudDump() { require_once LIB_PATH . 'osclass/classes/Cache.php'; $cache = new Cache('listcloud_feeds', 900); if ($cache->check()) { return $cache->retrieve(); } else { $list = array(); $content = osc_file_get_contents(osc_base_url() . 'index.php?page=search&sFeed=rss'); if ($content) { $xml = simplexml_load_string($content); foreach ($xml->channel->item as $item) { $list[] = array('title' => strval($item->title)); } } $cache->store($list); } return $list; }
public static function button($products, $extra = null) { $items = array(); $amount = 0; foreach ($products as $p) { $amount += $p['amount'] * $p['quantity']; } if (osc_get_preference('currency', 'payment_pro') != 'BTC') { $amount = osc_file_get_contents("https://blockchain.info/tobtc?currency=" . osc_get_preference('currency', 'payment_pro') . "&value=" . $amount); $xrate = osc_file_get_contents("https://blockchain.info/tobtc?currency=" . osc_get_preference('currency', 'payment_pro') . "&value=1"); if (is_numeric($xrate)) { $extra['xrate'] = $xrate; osc_set_preference('blockchain_xrate', $xrate, 'payment_pro'); } else { osc_get_preference('blockchain_xrate', 'payment_pro'); } } else { $extra['xrate'] = 1; } $tx_id = ModelPaymentPro::newInstance()->pendingInvoice($products); $r = rand(0, 1000); $extra['random'] = $r; $extra['tx'] = $tx_id; $extra = payment_pro_set_custom($extra); ?> <li class="payment bitcoin-btn"> <div class="blockchain-btn" data-address="<?php echo osc_get_preference('blockchain_btc_address', 'payment_pro'); ?> " data-anonymous="false" data-callback="<?php echo osc_route_url('blockchain-notify', array('extra' => str_replace("+", "@", $extra))); ?> "> <div style="cursor:pointer;cursor:hand" class="blockchain stage-begin"> <img src="<?php echo PAYMENT_PRO_URL; ?> payments/blockchain/pay_now_64.png"> </div> <div class="blockchain stage-loading" style="text-align:center"> <img src="<?php echo PAYMENT_PRO_URL; ?> payments/blockchain/loading-large.gif"> </div> <div class="blockchain stage-ready"> <p align="center"><?php printf(__('Please send %f BTC to <br /> <b>[[address]]</b></p>', 'payment_pro'), $amount); ?> <p align="center" class="qr-code"></p> </div> <div class="blockchain stage-paid"> <p><?php _e('Payment Received <b>[[value]] BTC</b>. Thank You.', 'payment_pro'); ?> </p> <a href="<?php echo osc_route_url('payment-pro-done', array('tx' => $tx_id)); ?> "><?php _e('Click here to continue', 'payment_pro'); ?> </a> </div> <div class="blockchain stage-error"> <span color="red">[[error]]</span> </div> </div> </li> <?php }
function doModel() { parent::doModel(); if (time() - (int) osc_market_data_update() > 86400) { //84600 = 24*60*60 $json = osc_file_get_contents(osc_market_url() . 'categories/', array('api_key' => osc_market_api_connect())); $data = @json_decode($json, true); if (is_array($data)) { osc_set_preference('marketCategories', $json); osc_set_preference('marketDataUpdate', time()); osc_reset_preferences(); } } switch ($this->action) { case 'buy': osc_csrf_check(); $json = osc_file_get_contents(osc_market_url() . 'token/', array('api_key' => osc_market_api_connect())); $data = json_decode($json, true); osc_redirect_to(Params::getParam('url') . '?token=' . @$data['token']); break; case 'purchases': case 'plugins': case 'themes': case 'languages': $section = $this->action; $title = array('plugins' => __('Recommended plugins for You'), 'themes' => __('Recommended themes for You'), 'languages' => __('Languages for this version'), 'purchases' => __('My purchases')); // page number $marketPage = Params::getParam("mPage"); $url_actual = osc_admin_base_url(true) . '?page=market&action=' . $section . '&mPage=' . $marketPage; if ($marketPage >= 1) { $marketPage--; } // api $url = osc_market_url($section) . (Params::getParam('sCategory') != '' ? 'category/' . Params::getParam('sCategory') . '/' : '') . "page/" . $marketPage . '/length/9/'; // default sort $sort_actual = ''; $sort_download = $url_actual . '&sort=downloads&order=desc'; $sort_updated = $url_actual . '&sort=updated&order=desc'; // sorting options (default) $_order = 'desc'; $order_download = $_order; $order_updated = $_order; $sort = Params::getParam("sort"); $order = Params::getParam("order"); if ($sort == '') { $sort = 'updated'; } if ($order == '') { $order = $_order; } $aux = $order == 'desc' ? 'asc' : 'desc'; switch ($sort) { case 'downloads': $sort_actual = '&sort=downloads&order='; $sort_download = $url_actual . $sort_actual . $aux; $sort_actual .= $order; $order_download = $order; // market api call $url .= 'order/downloads/' . $order; break; case 'updated': $sort_actual = '&sort=updated&order='; $sort_updated = $url_actual . $sort_actual . $aux; $sort_actual .= $order; $order_updated = $order; // market api call $url .= 'order/updated/' . $order; break; default: break; } // pageSize or length attribute is hardcoded $out = osc_file_get_contents($url, array('api_key' => osc_market_api_connect())); $array = json_decode($out, true); $output_pagination = ''; if (is_numeric($array['total']) && $array['total'] > 0) { $totalPages = ceil($array['total'] / $array['sizePage']); $pageActual = $array['page']; $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => osc_admin_base_url(true) . '?page=market' . '&action=' . $section . '&mPage={PAGE}' . $sort_actual, 'sides' => 5); // set pagination $pagination = new Pagination($params); $output_pagination = $pagination->doPagination(); } else { $array['total'] = 0; } // export variable to view $this->_exportVariableToView("sort", $sort); $this->_exportVariableToView("title", $title); $this->_exportVariableToView("section", $section); $this->_exportVariableToView("array", $array); $this->_exportVariableToView("sort_download", $sort_download); $this->_exportVariableToView("sort_updated", $sort_updated); $this->_exportVariableToView("order_download", $order_download); $this->_exportVariableToView("order_updated", $order_updated); $this->_exportVariableToView("market_categories", json_decode(osc_market_categories(), true)); $this->_exportVariableToView('pagination', $output_pagination); $this->doView("market/section.php"); break; default: $aPlugins = array(); $aThemes = array(); $aLanguages = array(); $out_plugin = osc_file_get_contents(osc_market_featured_url('plugins', 6)); $array_plugins = json_decode($out_plugin, true); if (isset($array_plugins)) { $aPlugins = $array_plugins['plugins']; } $out_themes = osc_file_get_contents(osc_market_featured_url('themes', 6)); $array_themes = json_decode($out_themes, true); if (isset($array_themes)) { $aThemes = $array_themes['themes']; } $out_languages = osc_file_get_contents(osc_market_featured_url('languages', 6)); $array_languages = json_decode($out_languages, true); if (isset($array_languages)) { $aLanguages = $array_languages['languages']; } $count = json_decode(osc_file_get_contents(osc_market_count_url()), true); if (!isset($count['pluginsTotal'])) { $count['pluginsTotal'] = 0; } if (!isset($count['themesTotal'])) { $count['themesTotal'] = 0; } if (!isset($count['languagesTotal'])) { $count['languagesTotal'] = 0; } $this->_exportVariableToView("count", $count); $this->_exportVariableToView("aPlugins", $aPlugins); $this->_exportVariableToView("aThemes", $aThemes); $this->_exportVariableToView("aLanguages", $aLanguages); $this->_exportVariableToView("market_categories", json_decode(osc_market_categories(), true)); $this->doView("market/index.php"); break; } }
function install_location_by_region() { $countryParent = Params::getParam('country_c_parent'); $region = Params::getParam('region'); if ($countryParent == '') { return false; } if ($region == '') { return false; } $manager_country = new Country(); $country = $manager_country->findByCode($countryParent); $aCountry = array(); $aRegion = array(); $aCountry[] = $country['s_name']; $aRegion[] = $region; $manager_region = new Region(); $regions_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=region&country=' . urlencode(implode(',', $aCountry)) . '&term=' . urlencode(implode(',', $aRegion))); $regions = json_decode($regions_json); if (isset($regions->error)) { osc_add_flash_error_message(sprintf(_m("%s can't be added"), $region), 'admin'); return false; } foreach ($regions as $r) { $exists = $manager_region->findByName($r->name, $r->country_code); if (isset($exists['s_name'])) { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $exists['s_name']), 'admin'); return false; } $manager_region->insert(array("fk_c_country_code" => $r->country_code, "s_name" => $r->name)); } unset($regions); unset($regions_json); $manager_city = new City(); foreach ($country as $c) { $regions = $manager_region->findByName($region, $country['pk_c_code']); $cities_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=city&country=' . urlencode($c) . '®ion=' . urlencode($regions['s_name']) . '&term=all'); $cities = json_decode($cities_json); if (!isset($cities->error)) { foreach ($cities as $ci) { $manager_city->insert(array("fk_i_region_id" => $regions['pk_i_id'], "s_name" => $ci->name, "fk_c_country_code" => $ci->country_code)); } } unset($cities); unset($cities_json); } osc_add_flash_ok_message(sprintf(_m('%s has been added as a region of %s'), $region, $country['s_name']), 'admin'); }
function display_target() { $country_list = osc_file_get_contents('http://geo.osclass.org/newgeo.services.php?action=countries'); $country_list = json_decode(substr($country_list, 1, strlen($country_list) - 2), true); $region_list = array(); $country_ip = ''; if (preg_match('|([a-z]{2})-([A-Z]{2})|', Params::getServerParam('HTTP_ACCEPT_LANGUAGE'), $match)) { $country_ip = $match[2]; $region_list = osc_file_get_contents('http://geo.osclass.org/newgeo.services.php?action=regions&country=' . $match[2]); $region_list = json_decode(substr($region_list, 1, strlen($region_list) - 2), true); } if (!isset($country_list[0]) || !isset($country_list[0]['s_name'])) { $internet_error = true; } ?> <form id="target_form" name="target_form" action="#" method="post" onsubmit="return false;"> <h2 class="target"><?php _e('Information needed'); ?> </h2> <div class="form-table"> <h2 class="title"><?php _e('Admin user'); ?> </h2> <table class="admin-user"> <tbody> <tr> <th><label for="admin_user"><?php _e('Username'); ?> </label></th> <td> <input size="25" id="admin_user" name="s_name" type="text" value="admin" /> </td> <td> <span id="admin-user-error" class="error" aria-hidden="true" style="display:none;"><?php _e('Admin user is required'); ?> </span> </td> </tr> <tr> <th><label for="s_passwd"><?php _e('Password'); ?> </label></th> <td> <input size="25" class="password_test" name="s_passwd" id="s_passwd" type="password" value="" autocomplete="off" /> </td> <td></td> </tr> </tbody> </table> <div class="admin-user"> <?php _e('A password will be automatically generated for you if you leave this blank.'); ?> <img src="<?php echo get_absolute_url(); ?> oc-includes/images/question.png" class="question-skip vtip" title="<?php echo osc_esc_html(__('You can modify username and password if you like, just change the input value.')); ?> " alt="" /> </div> <h2 class="title"><?php _e('Contact information'); ?> </h2> <table class="contact-info"> <tbody> <tr> <th><label for="webtitle"><?php _e('Web title'); ?> </label></th> <td><input type="text" id="webtitle" name="webtitle" size="25" /></td> <td></td> </tr> <tr> <th><label for="email"><?php _e('Contact e-mail'); ?> </label></th> <td><input type="text" id="email" name="email" size="25" /></td> <td><span id="email-error" class="error" style="display:none;"><?php _e('Put your e-mail here'); ?> </span></td> </tr> </tbody> </table> <h2 class="title"><?php _e('Location'); ?> </h2> <p class="space-left-25 left no-bottom"><?php _e('Choose countries/cities where your target users are located'); ?> </p> <div id="location-question" class="left question"> <img class="vtip" src="<?php echo get_absolute_url(); ?> oc-includes/images/question.png" title="<?php echo osc_esc_html(__("Once you type a country, you'll be able to choose region and city as well. Therefore, the installation will be more specific.")); ?> " alt="" /> </div> <div class="clear"></div> <div id="location"> <?php if (!$internet_error) { ?> <input type="hidden" id="skip-location-input" name="skip-location-input" value="0" /> <input type="hidden" id="country-input" name="country-input" value="" /> <input type="hidden" id="region-input" name="region-input" value="" /> <input type="hidden" id="city-input" name="city-input" value="" /> <div id="country-box"> <select name="country_select" id="country_select" > <option value="skip"><?php _e("Skip location"); ?> </option> <!-- <option value="all"><?php _e("International"); ?> </option> --> <?php foreach ($country_list as $c) { ?> <option value="<?php echo $c['code']; ?> " <?php if ($c['code'] == $country_ip) { echo 'selected="selected"'; } ?> ><?php echo $c['s_name']; ?> </option> <?php } ?> </select> <select name="region_select" id="region_select" style="display: none;"> <option value="all"><?php _e("All regions"); ?> </option> </select> <select name="city_select" id="city_select" style="display: none;"> <option value="all"><?php _e("All cities"); ?> </option> </select> <div id="no_region_text" aria-hidden="true" style="display: none;"><?php _e("There are no regions available for this country"); ?> </div> <div id="no_city_text" aria-hidden="true" style="display: none;"><?php _e("There are no cities available for this region"); ?> </div> </div> <?php } else { ?> <div id="location-error"> <?php _e('No internet connection. You can continue the installation and insert countries later.'); ?> <input type="hidden" id="skip-location-input" name="skip-location-input" value="1" /> </div> <?php } ?> </div> </div> <div class="clear"></div> <p class="margin20"> <a href="#" class="button" onclick="validate_form();">Next</a> </p> <div class="clear"></div> </form> <div id="lightbox" style="display:none;"> <div class="center"> <img src="<?php echo get_absolute_url(); ?> oc-includes/images/loading.gif" alt="<?php echo osc_esc_html(__("Loading...")); ?> " title="" /> </div> </div> <?php }
/** * Add Items longitude and latitude, while adding or updating items for Google Maps */ function insert_longitude_latitude($aItemRef) { $iItemId = $aItemRef['pk_i_id']; $aItem = Item::newInstance()->findByPrimaryKey($iItemId); $sAddress = isset($aItem['s_address']) ? $aItem['s_address'] : ''; $sCity = isset($aItem['s_city']) ? $aItem['s_city'] : ''; $sRegion = isset($aItem['s_region']) ? $aItem['s_region'] : ''; $sCountry = isset($aItem['s_country']) ? $aItem['s_country'] : ''; $sAddress = sprintf('%s, %s, %s, %s', $sAddress, $sCity, $sRegion, $sCountry); $aResponse = osc_file_get_contents(sprintf('https://maps.googleapis.com/maps/api/geocode/json?address=%s', urlencode($sAddress))); $jsonResponse = json_decode($aResponse, true); $aLocation = $jsonResponse['results'][0]['geometry']['location']; if ($jsonResponse['status'] == "OK") { ItemLocation::newInstance()->update(array('d_coord_lat' => $aLocation['lat'], 'd_coord_long' => $aLocation['lng']), array('fk_i_item_id' => $iItemId)); } }
function doModel() { parent::doModel(); //specific things for this class switch ($this->action) { case('plugins'): case('themes'): case('languages'): $section = $this->action; $title = array( 'plugins' => __('Recommended plugins for You'), 'themes' => __('Recommended themes for You'), 'languages' => __('Languages for this version') ); // page number $marketPage = Params::getParam("mPage"); $url_actual = osc_admin_base_url(true) . '?page=market&action='.$section.'&mPage='.$marketPage; if($marketPage>=1) $marketPage--; // api $url = osc_market_url($section)."page/".$marketPage.'/length/9/'; // default sort $sort_actual = ''; $sort_download = $url_actual.'&sort=downloads&order=desc'; $sort_updated = $url_actual.'&sort=updated&order=desc'; // sorting options (default) $_order = 'desc'; $order_download = $_order; $order_updated = $_order; $sort = Params::getParam("sort"); $order = Params::getParam("order"); if($sort=='') { $sort = 'updated'; } if($order=='') { $order = $_order; } $aux = ($order=='desc')?'asc':'desc'; switch ($sort) { case 'downloads': $sort_actual = '&sort=downloads&order='; $sort_download = $url_actual.$sort_actual.$aux; $sort_actual .= $order; $order_download = $order; // market api call $url .= 'order/downloads/'.$order; break; case 'updated': $sort_actual = '&sort=updated&order='; $sort_updated = $url_actual.$sort_actual.$aux; $sort_actual .= $order; $order_updated = $order; // market api call $url .= 'order/updated/'.$order; break; default: break; } // pageSize or length attribute is hardcoded $out = osc_file_get_contents($url); $array = json_decode($out, true); $output_pagination = ''; if( is_numeric($array['total']) && $array['total']>0 ) { $totalPages = ceil( $array['total'] / $array['sizePage'] ); $pageActual = $array['page']; $params = array( 'total' => $totalPages, 'selected' => $pageActual, 'url' => osc_admin_base_url(true).'?page=market'.'&action='.$section.'&mPage={PAGE}'.$sort_actual, 'sides' => 5 ); // set pagination $pagination = new Pagination($params); $output_pagination = $pagination->doPagination(); } else { $array['total'] = 0; } // export variable to view $this->_exportVariableToView("sort" , $sort); $this->_exportVariableToView("title" , $title); $this->_exportVariableToView("section" , $section); $this->_exportVariableToView("array" , $array); $this->_exportVariableToView("sort_download" , $sort_download); $this->_exportVariableToView("sort_updated" , $sort_updated); $this->_exportVariableToView("order_download" , $order_download); $this->_exportVariableToView("order_updated" , $order_updated); $this->_exportVariableToView('pagination', $output_pagination); $this->doView("market/section.php"); break; default: $aPlugins = array(); $aThemes = array(); $aLanguages = array(); $out_plugin = osc_file_get_contents(osc_market_featured_url('plugins', 6) ); $array_plugins = json_decode($out_plugin, true); if(isset($array_plugins)) { $aPlugins = $array_plugins['plugins']; } $out_themes = osc_file_get_contents(osc_market_featured_url('themes', 6) ); $array_themes = json_decode($out_themes, true); if(isset($array_themes)) { $aThemes = $array_themes['themes']; } $out_languages = osc_file_get_contents(osc_market_featured_url('languages', 6) ); $array_languages = json_decode($out_languages, true); if(isset($array_languages)) { $aLanguages = $array_languages['languages']; } $count = json_decode( osc_file_get_contents(osc_market_count_url()), true); if( !isset($count['pluginsTotal']) ) { $count['pluginsTotal'] = 0; } if( !isset($count['themesTotal']) ) { $count['themesTotal'] = 0; } if( !isset($count['languagesTotal']) ) { $count['languagesTotal'] = 0; } $this->_exportVariableToView("count" , $count); $this->_exportVariableToView("aPlugins" , $aPlugins); $this->_exportVariableToView("aThemes" , $aThemes); $this->_exportVariableToView("aLanguages" , $aLanguages); $this->doView("market/index.php"); break; } }
function display_target() { $country_list = osc_file_get_contents('http://geo.osclass.org/newgeo.services.php?action=countries'); $country_list = json_decode(substr($country_list, 1, strlen($country_list) - 2), true); $region_list = array(); $country_ip = ''; if (preg_match('|([a-z]{2})-([A-Z]{2})|', @$_SERVER['HTTP_ACCEPT_LANGUAGE'], $match)) { $country_ip = $match[2]; $region_list = osc_file_get_contents('http://geo.osclass.org/newgeo.services.php?action=regions&country=' . $match[2]); $region_list = json_decode(substr($region_list, 1, strlen($region_list) - 2), true); } if (!isset($country_list[0]) || !isset($country_list[0]['s_name'])) { $internet_error = true; } ?> <form id="target_form" name="target_form" action="#" method="post" onsubmit="return false;"> <h2 class="target"><?php _e('Необходимая информация'); ?> </h2> <div class="form-table"> <h2 class="title"><?php _e('Администратор'); ?> </h2> <table class="admin-user"> <tbody> <tr> <th><label for="admin_user"><?php _e('Имя пользователя'); ?> </label></th> <td> <input size="25" id="admin_user" name="s_name" type="text" value="admin" /> </td> <td> <span id="admin-user-error" class="error" aria-hidden="true" style="display:none;"><?php _e('Пользователь админ обязательное поле'); ?> </span> </td> </tr> <tr> <th><label for="s_passwd"><?php _e('Пароль'); ?> </label></th> <td> <input size="25" class="password_test" name="s_passwd" id="s_passwd" type="password" value="" /> </td> <td></td> </tr> </tbody> </table> <div class="admin-user"> <?php _e('Пароль будет автоматически сгенерирован для Вас, если Вы оставите это поле пустым.'); ?> <img src="<?php echo get_absolute_url(); ?> oc-includes/images/question.png" class="question-skip vtip" title="<?php _e('Вы можете изменить имя пользователя и пароль, просто измените значение.'); ?> " alt="" /> </div> <h2 class="title"><?php _e('Контактная информация'); ?> </h2> <table class="contact-info"> <tbody> <tr> <th><label for="webtitle"><?php _e('Заголовок сайта'); ?> </label></th> <td><input type="text" id="webtitle" name="webtitle" size="25" /></td> <td></td> </tr> <tr> <th><label for="email"><?php _e('Контактный e-mail'); ?> </label></th> <td><input type="text" id="email" name="email" size="25" /></td> <td><span id="email-error" class="error" style="display:none;"><?php _e('Введите ваш e-mail'); ?> </span></td> </tr> </tbody> </table> <h2 class="title"><?php _e('Местонахождение'); ?> </h2> <p class="space-left-25 left no-bottom"><?php _e('Выберите страну/город, где находятся ваша целевая аудитория'); ?> </p> <div id="location-question" class="left question"> <img class="vtip" src="<?php echo get_absolute_url(); ?> oc-includes/images/question.png" title="<?php echo osc_esc_html(__("Как только вы введете страну, вы сможете выбрать регион и город. После установки Osclass вы сможете импортировать другие регионы.")); ?> " alt="" /> </div> <div class="clear"></div> <div id="location"> <?php if (!$internet_error) { ?> <input type="hidden" id="skip-location-input" name="skip-location-input" value="0" /> <input type="hidden" id="country-input" name="country-input" value="" /> <input type="hidden" id="region-input" name="region-input" value="" /> <input type="hidden" id="city-input" name="city-input" value="" /> <div id="country-box"> <select name="country_select" id="country_select" > <option value="skip"><?php _e("Skip location"); ?> </option> <!-- <option value="all"><?php _e("International"); ?> </option> --> <?php foreach ($country_list as $c) { ?> <option value="<?php echo $c['code']; ?> " <?php if ($c['code'] == $country_ip) { echo 'selected="selected"'; } ?> ><?php echo $c['s_name']; ?> </option> <?php } ?> </select> <select name="region_select" id="region_select" style="display: none;"> <option value="all"><?php _e("Все регионы"); ?> </option> </select> <select name="city_select" id="city_select" style="display: none;"> <option value="all"><?php _e("Все города"); ?> </option> </select> <div id="no_region_text" aria-hidden="true" style="display: none;"><?php _e("Нет регионов доступных для данной страны"); ?> </div> <div id="no_city_text" aria-hidden="true" style="display: none;"><?php _e("Нет городов доступных для данного региона"); ?> </div> </div> <?php } else { ?> <div id="location-error"> <?php _e('В данный момент нет подключения к интернету. Вы можете продолжить установку системы, стран и регионов позже.'); ?> <input type="hidden" id="skip-location-input" name="skip-location-input" value="1" /> </div> <?php } ?> </div> </div> <div class="clear"></div> <p class="margin20"> <a href="#" class="button" onclick="validate_form();">Далее</a> </p> <div class="clear"></div> </form> <div id="lightbox" style="display:none;"> <div class="center"> <img src="<?php echo get_absolute_url(); ?> oc-includes/images/loading.gif" alt="<?php echo osc_esc_html(__("Загрузка...")); ?> " title="" /> </div> </div> <?php }
static function checkUpdate($plugin) { $info = Plugins::getInfo($plugin); if ($info['plugin_update_uri'] != "") { if (false === ($str = @osc_file_get_contents($info['plugin_update_uri']))) { return false; } else { if (preg_match('|\\?\\(([^\\)]+)|', preg_replace('/,\\s*([\\]}])/m', '$1', $str), $data)) { $json = json_decode($data[1], true); if ($json['version'] > $info['version']) { return true; } } } } return false; }
function location_by_city() { $country = Params::getParam('country'); $city = Params::getParam('city'); if ($country == '') { return false; } if ($city == '') { return false; } $countries_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=country&term=' . urlencode(implode(',', $country)) . '&install=true&version=' . osc_version()); $countries = json_decode($countries_json); $manager_country = Country::newInstance(); if (count($countries) == 0 && reportToOsclass()) { LogOsclassInstaller::instance()->error('Cannot get countries - ' . implode(',', $country), __FILE__ . "::" . __LINE__); } foreach ($countries as $c) { $manager_country->insert(array("pk_c_code" => $c->id, "fk_c_locale_code" => $c->locale_code, "s_name" => $c->name)); } $manager_city = City::newInstance(); $manager_region = Region::newInstance(); foreach ($countries as $c) { $cities_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=city&country=' . urlencode($c->name) . '&term=' . urlencode(implode(',', $city))); $cities = json_decode($cities_json); if (!isset($cities->error)) { foreach ($cities as $ci) { $regions_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=region&country=&id=' . $ci->region_id); $regions = json_decode($regions_json); if (count($regions) == 0 && reportToOsclass()) { LogOsclassInstaller::instance()->error('Cannot get regions by - ' . $ci->region_id, __FILE__ . "::" . __LINE__); } foreach ($regions as $r) { $manager_region->insert(array("pk_i_id" => $r->id, "fk_c_country_code" => $r->country_code, "s_name" => $r->name)); } $manager_city->insert(array("pk_i_id" => $ci->id, "fk_i_region_id" => $ci->region_id, "s_name" => $ci->name, "fk_c_country_code" => $ci->country_code)); } } else { if (reportToOsclass()) { LogOsclassInstaller::instance()->error('Cannot get cities by - ' . $c->name . ' - term ' . implode(',', $city), __FILE__ . "::" . __LINE__); } return '300'; } unset($cities); unset($cities_json); } return '200'; }
function osc_market($section, $code) { $plugin = false; $re_enable = false; $message = ""; $data = array(); $download_post_data = array('api_key' => osc_market_api_connect()); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $url = osc_market_url($section, $code); $data = osc_file_get_contents($url, array('api_key' => osc_market_api_connect())); $data = json_decode(osc_file_get_contents($url, array('api_key' => osc_market_api_connect())), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $download_post_data = array(); $data = json_decode(osc_file_get_contents($code), true); } else { return array('error' => 9, 'message' => __('No external sources are allowed'), 'data' => $data); } } /*********************** **** DOWNLOAD FILE **** ***********************/ if (isset($data['s_update_url']) && isset($data['s_source_file']) && isset($data['e_type'])) { if ($data['e_type'] == 'THEME') { $folder = 'themes/'; } else { if ($data['e_type'] == 'LANGUAGE') { $folder = 'languages/'; } else { // PLUGINS $folder = 'plugins/'; $plugin = Plugins::findByUpdateURI($data['s_update_url']); if ($plugin != false) { if (Plugins::isEnabled($plugin)) { Plugins::runHook($plugin . '_disable'); Plugins::deactivate($plugin); $re_enable = true; } } } } $filename = date('YmdHis') . "_" . osc_sanitize_string($data['s_title']) . "_" . $data['s_version'] . ".zip"; $url_source_file = $data['s_source_file']; $result = osc_downloadFile($url_source_file, $filename, $download_post_data); if ($result) { // Everything is OK, continue /********************** ***** UNZIP FILE ***** **********************/ @mkdir(osc_content_path() . 'downloads/oc-temp/'); $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, osc_content_path() . 'downloads/oc-temp/'); if ($res == 1) { // Everything is OK, continue /********************** ***** COPY FILES ***** **********************/ $fail = -1; if ($handle = opendir(osc_content_path() . 'downloads/oc-temp')) { $folder_dest = ABS_PATH . "oc-content/" . $folder; if (function_exists('posix_getpwuid')) { $current_user = posix_getpwuid(posix_geteuid()); $ownerFolder = posix_getpwuid(fileowner($folder_dest)); } $fail = 0; while (false !== ($_file = readdir($handle))) { if ($_file != '.' && $_file != '..') { $copyprocess = osc_copy(osc_content_path() . "downloads/oc-temp/" . $_file, $folder_dest . $_file); if ($copyprocess == false) { $fail = 1; } } } closedir($handle); // Additional actions is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue // Also remove the zip package /**************************** ** REMOVE TEMPORARY FILES ** ****************************/ @unlink(osc_content_path() . 'downloads/' . $filename); $path = osc_content_path() . 'downloads/oc-temp'; $rm_errors = 0; $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); for ($dir->rewind(); $dir->valid(); $dir->next()) { if ($dir->isDir()) { if ($dir->getFilename() != '.' && $dir->getFilename() != '..') { if (!rmdir($dir->getPathname())) { $rm_errors++; } } } else { if (!unlink($dir->getPathname())) { $rm_errors++; } } } if (!rmdir($path)) { $rm_errors++; } if ($fail == 0) { // Everything is OK, continue if ($data['e_type'] != 'THEME' && $data['e_type'] != 'LANGUAGE') { if ($plugin != false && $re_enable) { $enabled = Plugins::activate($plugin); if ($enabled) { Plugins::runHook($plugin . '_enable'); } } } else { if ($data['e_type'] == 'LANGUAGE') { osc_checkLocales(); } } // recount plugins&themes for update if ($section == 'plugins') { osc_check_plugins_update(true); } else { if ($section == 'themes') { osc_check_themes_update(true); } else { if ($section == 'languages') { osc_check_languages_update(true); } } } if ($rm_errors == 0) { $message = __('Everything looks good!'); $error = 0; } else { $message = __('Nearly everything looks good! but there were some errors removing temporary files. Please manually remove the \\"oc-content/downloads/oc-temp\\" folder'); $error = 6; // Some errors removing files } } else { $message = __('Problems when copying files. Please check your permissions. '); if ($current_user['uid'] != $ownerFolder['uid']) { if (function_exists('posix_getgrgid')) { $current_group = posix_getgrgid($current_user['gid']); $message .= '<p><strong>' . sprintf(__('NOTE: Web user and destination folder user is not the same, you might have an issue there. <br/>Do this in your console:<br/>chown -R %s:%s %s'), $current_user['name'], $current_group['name'], $folder_dest) . '</strong></p>'; } } $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file! } } else { $message = __('Unzip failed'); $error = 3; // Unzip failed } } else { $message = __('Download failed'); $error = 2; // Download failed } } else { if (isset($data['s_buy_url']) && isset($data['b_paid']) && $data['s_buy_url'] != '' && $data['b_paid'] == 0) { $message = __('This is a paid item, you need to buy it before you are able to download it'); $error = 8; // Item not paid } else { $message = __('Input code not valid'); $error = 7; // Input code not valid } } } else { $message = __('Missing download URL'); $error = 1; // Missing download URL } return array('error' => $error, 'message' => $message, 'data' => $data); }
function doModel() { //specific things for this class switch ($this->action) { case 'bulk_actions': break; case 'regions': //Return regions given a countryId $regions = Region::newInstance()->findByCountry(Params::getParam("countryId")); echo json_encode($regions); break; case 'cities': //Returns cities given a regionId $cities = City::newInstance()->findByRegion(Params::getParam("regionId")); echo json_encode($cities); break; case 'location': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term")); echo json_encode($cities); break; case 'userajax': // This is the autocomplete AJAX $users = User::newInstance()->ajax(Params::getParam("term")); if (count($users) == 0) { echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results')))); } else { echo json_encode($users); } break; case 'date_format': echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date('Y-m-d H:i:s'), Params::getParam('format')))); break; case 'runhook': // run hooks $hook = Params::getParam('hook'); if ($hook == '') { echo json_encode(array('error' => 'hook parameter not defined')); break; } switch ($hook) { case 'item_form': osc_run_hook('item_form', Params::getParam('catId')); break; case 'item_edit': $catId = Params::getParam("catId"); $itemId = Params::getParam("itemId"); osc_run_hook("item_edit", $catId, $itemId); break; default: osc_run_hook('ajax_admin_' . $hook); break; } break; case 'categories_order': // Save the order of the categories osc_csrf_check(false); $aIds = Params::getParam('list'); $order = array(); $error = 0; $catManager = Category::newInstance(); $aRecountCat = array(); foreach ($aIds as $cat) { if (!isset($order[$cat['p']])) { $order[$cat['p']] = 0; } $res = $catManager->update(array('fk_i_parent_id' => $cat['p'] == 'root' ? NULL : $cat['p'], 'i_position' => $order[$cat['p']]), array('pk_i_id' => $cat['c'])); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { $aRecountCat[] = $cat['c']; } } $order[$cat['p']] = $order[$cat['p']] + 1; } // update category stats foreach ($aRecountCat as $rId) { osc_update_cat_stats_id($rId); } if ($error) { $result = array('error' => __("An error occurred")); } else { $result = array('ok' => __("Order saved")); } echo json_encode($result); break; case 'category_edit_iframe': $this->_exportVariableToView('category', Category::newInstance()->findByPrimaryKey(Params::getParam("id"), 'all')); if (count(Category::newInstance()->findSubcategories(Params::getParam("id"))) > 0) { $this->_exportVariableToView('has_subcategories', true); } else { $this->_exportVariableToView('has_subcategories', false); } $this->_exportVariableToView('languages', OSCLocale::newInstance()->listAllEnabled()); $this->doView("categories/iframe.php"); break; case 'field_categories_iframe': $selected = Field::newInstance()->categories(Params::getParam("id")); if ($selected == null) { $selected = array(); } $this->_exportVariableToView("selected", $selected); $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id"))); $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll()); $this->doView("fields/iframe.php"); break; case 'field_categories_post': osc_csrf_check(false); $error = 0; $field = Field::newInstance()->findByName(Params::getParam("s_name")); if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) { // remove categories from a field Field::newInstance()->cleanCategoriesFromField(Params::getParam("id")); // no error... continue updating fields if ($error == 0) { $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name"); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } // trim options $s_options = ''; $aux = Params::getParam('s_options'); $aAux = explode(',', $aux); foreach ($aAux as &$option) { $option = trim($option); } $s_options = implode(',', $aAux); $res = Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 'b_searchable' => Params::getParam("field_searchable") == "1" ? 1 : 0, 's_options' => $s_options), array('pk_i_id' => Params::getParam("id"))); if (is_bool($res) && !$res) { $error = 1; } } // no error... continue inserting categories-field if ($error == 0) { $aCategories = Params::getParam("categories"); if (is_array($aCategories) && count($aCategories) > 0) { $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories); if (!$res) { $error = 1; } } } // error while updating? if ($error == 1) { $message = __("An error occurred while updating."); } } else { $error = 1; $message = __("Sorry, you already have a field with that name"); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => Params::getParam("id")); } echo json_encode($result); break; case 'delete_field': osc_csrf_check(false); $res = Field::newInstance()->deleteByPrimaryKey(Params::getParam('id')); if ($res > 0) { $result = array('ok' => __('The custom field has been deleted')); } else { $result = array('error' => __('An error occurred while deleting')); } echo json_encode($result); break; case 'add_field': osc_csrf_check(false); $s_name = __('NEW custom field'); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $fieldManager = Field::newInstance(); $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array()); if ($result) { echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name)); } else { echo json_encode(array('error' => 1)); } break; case 'enable_category': osc_csrf_check(false); $id = strip_tags(Params::getParam('id')); $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0; $error = 0; $result = array(); $aUpdated = array(); $mCategory = Category::newInstance(); $aCategory = $mCategory->findByPrimaryKey($id); if ($aCategory == false) { $result = array('error' => sprintf(__("No category with id %d exists"), $id)); echo json_encode($result); break; } // root category if ($aCategory['fk_i_parent_id'] == '') { $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id)); $subCategories = $mCategory->findSubcategories($id); $aIds = array($id); $aUpdated[] = array('id' => $id); foreach ($subCategories as $subcategory) { $aIds[] = $subcategory['pk_i_id']; $aUpdated[] = array('id' => $subcategory['pk_i_id']); } Item::newInstance()->enableByCategory($enabled, $aIds); if ($enabled) { $result = array('ok' => __('The category as well as its subcategories have been enabled')); } else { $result = array('ok' => __('The category as well as its subcategories have been disabled')); } $result['affectedIds'] = $aUpdated; echo json_encode($result); break; } // subcategory $parentCategory = $mCategory->findRootCategory($id); if (!$parentCategory['b_enabled']) { $result = array('error' => __('Parent category is disabled, you can not enable that category')); echo json_encode($result); break; } $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); if ($enabled) { $result = array('ok' => __('The subcategory has been enabled')); } else { $result = array('ok' => __('The subcategory has been disabled')); } $result['affectedIds'] = array(array('id' => $id)); echo json_encode($result); break; case 'delete_category': osc_csrf_check(false); $id = Params::getParam("id"); $error = 0; $categoryManager = Category::newInstance(); $res = $categoryManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The categories have been deleted'); } else { $error = 1; $message = __('An error occurred while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'edit_category_post': osc_csrf_check(false); $id = Params::getParam("id"); $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0; $fields['b_price_enabled'] = Params::getParam('b_price_enabled') != '' ? 1 : 0; $apply_changes_to_subcategories = Params::getParam('apply_changes_to_subcategories') == 1 ? true : false; $error = 0; $has_one_title = 0; $postParams = Params::getParamsAsArray(); foreach ($postParams as $k => $v) { if (preg_match('|(.+?)#(.+)|', $k, $m)) { if ($m[2] == 's_name') { if ($v != "") { $has_one_title = 1; $aFieldsDescription[$m[1]][$m[2]] = $v; $s_text = $v; } else { $aFieldsDescription[$m[1]][$m[2]] = NULL; $error = 1; } } else { $aFieldsDescription[$m[1]][$m[2]] = $v; } } } $l = osc_language(); if ($error == 0 || $error == 1 && $has_one_title == 1) { $categoryManager = Category::newInstance(); $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id); $categoryManager->updateExpiration($id, $fields['i_expiration_days'], $apply_changes_to_subcategories); $categoryManager->updatePriceEnabled($id, $fields['b_price_enabled'], $apply_changes_to_subcategories); if (is_bool($res)) { $error = 2; } } if ($error == 0) { $msg = __("Category updated correctly"); } else { if ($error == 1) { if ($has_one_title == 1) { $error = 4; $msg = __('Category updated correctly, but some titles are empty'); } else { $msg = __('Sorry, including at least a title is mandatory'); } } else { if ($error == 2) { $msg = __('An error occurred while updating'); } } } echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name'])); break; case 'custom': // Execute via AJAX custom file if (Params::existParam('route')) { $routes = Rewrite::newInstance()->getRoutes(); $rid = Params::getParam('route'); $file = '../'; if (isset($routes[$rid]) && isset($routes[$rid]['file'])) { $file = $routes[$rid]['file']; } } else { $file = Params::getParam("ajaxfile"); } if ($file == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (stripos($file, '../') !== false || stripos($file, '..\\') !== false) { echo json_encode(array('error' => 'no valid file')); break; } if (!file_exists(osc_plugins_path() . $file)) { echo json_encode(array('error' => "file doesn't exist")); break; } require_once osc_plugins_path() . $file; break; case 'test_mail': $title = sprintf(__('Test email, %s'), osc_page_title()); $body = __("Test email") . "<br><br>" . osc_page_title(); $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body); $array = array(); if (osc_sendMail($emailParams)) { $array = array('status' => '1', 'html' => __('Email sent successfully')); } else { $array = array('status' => '0', 'html' => __('An error occurred while sending email')); } echo json_encode($array); break; case 'test_mail_template': // replace por valores por defecto $email = Params::getParam("email"); $title = Params::getParam("title"); $body = Params::getParam("body", false, false); $emailParams = array('subject' => $title, 'to' => $email, 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body); $array = array(); if (osc_sendMail($emailParams)) { $array = array('status' => '1', 'html' => __('Email sent successfully')); } else { $array = array('status' => '0', 'html' => __('An error occurred while sending email')); } echo json_encode($array); break; case 'order_pages': osc_csrf_check(false); $order = Params::getParam("order"); $id = Params::getParam("id"); if ($order != '' && $id != '') { $mPages = Page::newInstance(); $actual_page = $mPages->findByPrimaryKey($id); $actual_order = $actual_page['i_order']; $array = array(); $condition = array(); $new_order = $actual_order; if ($order == 'up') { $page = $mPages->findPrevPage($actual_order); } else { if ($order == 'down') { $page = $mPages->findNextPage($actual_order); } } if (isset($page['i_order'])) { $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id)); $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id'])); } } break; case 'check_version': $data = osc_file_get_contents('http://osclass.org/latest_version_v1.php?callback=?'); $data = preg_replace('|^\\?\\((.*?)\\);$|', '$01', $data); $json = json_decode($data); if (isset($json->version)) { if ($json->version > osc_version()) { osc_set_preference('update_core_json', $data); echo json_encode(array('error' => 0, 'msg' => __('Update available'))); } else { osc_set_preference('update_core_json', ''); echo json_encode(array('error' => 0, 'msg' => __('No update available'))); } osc_set_preference('last_version_check', time()); } else { // Latest version couldn't be checked (site down?) osc_set_preference('last_version_check', time() - 82800); // 82800 = 23 hours, so repeat check in one hour echo json_encode(array('error' => 1, 'msg' => __('Version could not be checked'))); } break; case 'check_languages': $total = _osc_check_languages_update(); echo json_encode(array('msg' => __('Checked updates'), 'total' => $total)); break; case 'check_themes': $total = _osc_check_themes_update(); echo json_encode(array('msg' => __('Checked updates'), 'total' => $total)); break; case 'check_plugins': $total = _osc_check_plugins_update(); echo json_encode(array('msg' => __('Checked updates'), 'total' => $total)); break; /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ case 'upgrade': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(); $result = osc_do_upgrade(); if (!defined('__FROM_CRON__') || !__FROM_CRON__) { if ($result['error'] == 0) { osc_add_flash_ok_message($result['message'], 'admin'); } else { if ($result['error'] == 6) { osc_add_flash_warning_message($result['message'], 'admin'); } } } echo json_encode($result); break; /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ case 'market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(false); $result = osc_market(Params::getParam('section'), Params::getParam('code')); echo json_encode($result); break; case 'check_market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT $section = Params::getParam('section'); $code = Params::getParam('code'); $data = array(); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $data = json_decode(osc_file_get_contents(osc_market_url($section, $code), array('api_key' => osc_market_api_connect())), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $data = json_decode(osc_file_get_contents($code), true); } else { echo json_encode(array('error' => 3, 'error_msg' => __('No external sources are allowed'))); break; } } if (!isset($data['s_source_file']) || !isset($data['s_update_url'])) { //$data = array('error' => 2, 'error_msg' => __('Invalid code')); } } else { $data = array('error' => 1, 'error_msg' => __('No code was submitted')); } echo json_encode($data); break; case 'market_data': $section = Params::getParam('section'); $page = Params::getParam("mPage"); $featured = Params::getParam("featured"); $sort = Params::getParam("sort"); $order = Params::getParam("order"); // for the moment this value is static $length = 9; if ($page >= 1) { $page--; } $url = osc_market_url($section) . "page/" . $page . '/'; if ($length != '' && is_numeric($length)) { $url .= 'length/' . $length . '/'; } if ($sort != '') { $url .= 'order/' . $sort; if ($order != '') { $url .= '/' . $order; } } if ($featured != '') { $url = osc_market_featured_url($section); } $data = array(); $data = json_decode(osc_file_get_contents($url, array('api_key' => osc_market_api_connect())), true); if (!isset($data[$section])) { $data = array('error' => 1, 'error_msg' => __('No market data')); } echo 'var market_data = window.market_data || {}; market_data.' . $section . ' = ' . json_encode($data) . ';'; break; case 'local_market': // AVOID CROSS DOMAIN PROBLEMS OF AJAX REQUEST $marketPage = Params::getParam("mPage"); if ($marketPage >= 1) { $marketPage--; } $out = osc_file_get_contents(osc_market_url(Params::getParam("section")) . "page/" . $marketPage, array('api_key' => osc_market_api_connect())); $array = json_decode($out, true); // do pagination $pageActual = $array['page']; $totalPages = ceil($array['total'] / $array['sizePage']); $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => '#{PAGE}', 'sides' => 5); // set pagination $pagination = new Pagination($params); $aux = $pagination->doPagination(); $array['pagination_content'] = $aux; // encode to json echo json_encode($array); break; case 'market_connect': $json = osc_file_get_contents(osc_market_url() . 'connect/', array('s_email' => Params::getParam('s_email'), 's_password' => Params::getParam('s_password'))); $data = json_decode($json, true); if ($data['error'] == 0) { osc_set_preference('marketAPIConnect', $data['api_key']); unset($data['api_key']); $json = json_encode($data); } echo $json; break; case 'dashboardbox_market': $error = 0; // make market call $url = osc_get_preference('marketURL') . 'dashboardbox/'; $content = ''; if (false === ($json = @osc_file_get_contents($url))) { $error = 1; } else { $content = $json; } if ($error == 1) { echo json_encode(array('error' => 1)); } else { // replace content with correct urls $content = str_replace('{URL_MARKET_THEMES}', osc_admin_base_url(true) . '?page=market&action=themes', $content); $content = str_replace('{URL_MARKET_PLUGINS}', osc_admin_base_url(true) . '?page=market&action=plugins', $content); echo json_encode(array('html' => $content)); } break; case 'market_header': $error = 0; // make market call $url = osc_get_preference('marketURL') . 'market_header/'; $content = ''; if (false === ($json = @osc_file_get_contents($url))) { $error = 1; } else { $content = $json; } if ($error == 1) { echo json_encode(array('error' => 1)); } else { echo json_encode(array('html' => $content)); } break; case 'location_stats': osc_csrf_check(false); $workToDo = osc_update_location_stats(); if ($workToDo > 0) { $array['status'] = 'more'; $array['pending'] = $workToDo; echo json_encode($array); } else { $array['status'] = 'done'; echo json_encode($array); } break; case 'country_slug': $exists = Country::newInstance()->findBySlug(Params::getParam('slug')); if (isset($exists['s_slug'])) { echo json_encode(array('error' => 1, 'country' => $exists)); } else { echo json_encode(array('error' => 0)); } break; case 'region_slug': $exists = Region::newInstance()->findBySlug(Params::getParam('slug')); if (isset($exists['s_slug'])) { echo json_encode(array('error' => 1, 'region' => $exists)); } else { echo json_encode(array('error' => 0)); } break; case 'city_slug': $exists = City::newInstance()->findBySlug(Params::getParam('slug')); if (isset($exists['s_slug'])) { echo json_encode(array('error' => 1, 'city' => $exists)); } else { echo json_encode(array('error' => 0)); } break; case 'error_permissions': echo json_encode(array('error' => __("You don't have the necessary permissions"))); break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
function doModel() { // calling the locations settings view $location_action = Params::getParam('type'); $mCountries = new Country(); switch ($location_action) { case('add_country'): // add country if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $countryCode = strtoupper(Params::getParam('c_country')); $countryName = Params::getParam('country'); $exists = $mCountries->findByCode($countryCode); if(isset($exists['s_name'])) { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $countryName), 'admin'); } else { if(Params::getParam('c_manual')==1) { $mCountries->insert(array('pk_c_code' => $countryCode, 's_name' => $countryName)); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin'); } else { if(!osc_validate_min($countryCode, 1) || !osc_validate_min($countryName, 1)) { osc_add_flash_error_message(_m('Country code and name should have at least two characters'), 'admin'); } else { $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?action=country&term=' . urlencode($countryCode) ); if($data_sql!='') { $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); } else { $mCountries->insert(array('pk_c_code' => $countryCode, 's_name' => $countryName)); } osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin'); } } } osc_calculate_location_slug(osc_subdomain_type()); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case('edit_country'): // edit country if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); if(!osc_validate_min(Params::getParam('e_country'), 1)) { osc_add_flash_error_message(_m('Country name cannot be blank'), 'admin'); } else { $name = Params::getParam('e_country'); $slug = Params::getParam('e_country_slug'); if($slug=='') { $slug_tmp = $slug = osc_sanitizeString($name); } else { $exists = $mCountries->findBySlug($slug); if(isset($exists['s_slug']) && $exists['pk_c_code']!=Params::getParam('country_code')) { $slug_tmp = $slug = osc_sanitizeString($name); } else { $slug_tmp = $slug = osc_sanitizeString($slug); } } $slug_unique = 1; while(true) { $location_slug = $mCountries->findBySlug($slug); if(isset($location_slug['s_slug']) && $location_slug['pk_c_code']!=Params::getParam('country_code')) { $slug = $slug_tmp . '-' . $slug_unique; $slug_unique++; } else { break; } } $ok = $mCountries->update(array('s_name'=> $name, 's_slug' => $slug), array('pk_c_code' => Params::getParam('country_code'))); if( $ok ) { osc_add_flash_ok_message(_m('Country has been edited'), 'admin'); } else { osc_add_flash_error_message(_m('There were some problems editing the country'), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case('delete_country'): // delete country if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $countryIds = Params::getParam('id'); if(is_array($countryIds)) { $locations = 0; $del_locations = 0; foreach($countryIds as $countryId) { $ok = $mCountries->deleteByPrimaryKey($countryId); } if($ok==0) { $del_locations++; } else { $locations += $ok; } if($locations==0) { osc_add_flash_ok_message(sprintf(_n('One location has been deleted', '%s locations have been deleted', $del_locations), $del_locations), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem deleting locations'), 'admin'); } } else { osc_add_flash_error_message(_m('No country was selected'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case('add_region'): // add region if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); if( !Params::getParam('r_manual') ) { $regionId = Params::getParam('region_id'); $regionName = Params::getParam('region'); if($regionId!='') { $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?action=region&term=' . urlencode($regionId) ); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m("%s can't be added"), $regionName), 'admin'); } } else { $mRegions = new Region(); $regionName = Params::getParam('region'); $countryCode = Params::getParam('country_c_parent'); $country = Country::newInstance()->findByCode($countryCode); if(!osc_validate_min($regionName, 1)) { osc_add_flash_error_message(_m('Region name cannot be blank'), 'admin'); } else { $exists = $mRegions->findByName($regionName, $countryCode); if(!isset($exists['s_name'])) { $data = array('fk_c_country_code' => $countryCode ,'s_name' => $regionName); $mRegions->insert($data); $id = $mRegions->dao->insertedId(); RegionStats::newInstance()->setNumItems($id, 0); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $regionName), 'admin'); } } } osc_calculate_location_slug(osc_subdomain_type()); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code='.@$countryCode."&country=".@$country['s_name']); break; case('edit_region'): // edit region if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $mRegions = new Region(); $newRegion = Params::getParam('e_region'); $regionId = Params::getParam('region_id'); if(!osc_validate_min($newRegion, 1)) { osc_add_flash_error_message(_m('Region name cannot be blank'), 'admin'); } else { $exists = $mRegions->findByName($newRegion); if(!isset($exists['pk_i_id']) || $exists['pk_i_id']==$regionId) { if($regionId != '') { $aRegion = $mRegions->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($aRegion['fk_c_country_code']); $name = $newRegion; $slug = Params::getParam('e_region_slug'); if($slug=='') { $slug_tmp = $slug = osc_sanitizeString($name); } else { $exists = $mRegions->findBySlug($slug); if(isset($exists['s_slug']) && $exists['pk_i_id']!=$regionId) { $slug_tmp = $slug = osc_sanitizeString($name); } else { $slug_tmp = $slug = osc_sanitizeString($slug); } } $slug_unique = 1; while(true) { $location_slug = $mRegions->findBySlug($slug); if(isset($location_slug['s_slug']) && $location_slug['pk_i_id']!=$regionId) { $slug = $slug_tmp . '-' . $slug_unique; $slug_unique++; } else { break; } } $mRegions->update(array('s_name' => $newRegion, 's_slug' => $slug) ,array('pk_i_id' => $regionId)); ItemLocation::newInstance()->update( array('s_region' => $newRegion), array('fk_i_region_id' => $regionId) ); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newRegion), 'admin'); } } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newRegion), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code='.@$country['pk_c_code']."&country=".@$country['s_name']); break; case('delete_region'): // delete region if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $mRegion = new Region(); $regionIds = Params::getParam('id'); if(is_array($regionIds)) { $locations = 0; $del_locations = 0; if(count($regionIds)>0) { $region = $mRegion->findByPrimaryKey($regionIds[0]); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); foreach($regionIds as $regionId) { if($regionId != '') { $ok = $mRegion->deleteByPrimaryKey($regionId); if($ok==0) { $del_locations++; } else { $locations += $ok; } } } } if($locations==0) { osc_add_flash_ok_message(sprintf(_n('One location has been deleted', '%s locations have been deleted', $del_locations), $del_locations), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem deleting locations'), 'admin'); } } else { osc_add_flash_error_message(_m('No region was selected'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code='.@$country['pk_c_code']."&country=".@$country['s_name']); break; case('add_city'): // add city if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $regionId = Params::getParam('region_parent'); $countryCode = Params::getParam('country_c_parent'); $mRegion = new Region(); $region = $mRegion->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); if( !Params::getParam('ci_manual') ) { $cityId = Params::getParam('city_id'); $cityName = Params::getParam('city'); if($cityId!='') { $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?action=city&term=' . urlencode($cityId) ); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $cityName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m("%s can't be added"), $cityName), 'admin'); } } else { $mCities = new City(); $newCity = Params::getParam('city'); if(!osc_validate_min($newCity, 1)) { osc_add_flash_error_message(_m('New city name cannot be blank'), 'admin'); } else { $exists = $mCities->findByName($newCity, $regionId); if(!isset($exists['s_name'])) { $mCities->insert(array('fk_i_region_id' => $regionId ,'s_name' => $newCity ,'fk_c_country_code' => $countryCode)); $id = $mCities->dao->insertedId(); CityStats::newInstance()->setNumItems($id, 0); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } } } osc_calculate_location_slug('city'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code='.@$country['pk_c_code']."&country=".@$country['s_name']."®ion=".$regionId); break; case('edit_city'): // edit city if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $mRegion = new Region(); $mCities = new City(); $newCity = Params::getParam('e_city'); $cityId = Params::getParam('city_id'); if(!osc_validate_min($newCity, 1)) { osc_add_flash_error_message(_m('City name cannot be blank'), 'admin'); } else { $exists = $mCities->findByName($newCity); if(!isset($exists['pk_i_id']) || $exists['pk_i_id']==$cityId) { $city = $mCities->findByPrimaryKey($cityId); $region = $mRegion->findByPrimaryKey($city['fk_i_region_id']); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); $name = $newCity; $slug = Params::getParam('e_country_slug'); if($slug=='') { $slug_tmp = $slug = osc_sanitizeString($name); } else { $exists = $mCities->findBySlug($slug); if(isset($exists['s_slug']) && $exists['pk_i_id']!=$cityId) { $slug_tmp = $slug = osc_sanitizeString($name); } else { $slug_tmp = $slug = osc_sanitizeString($slug); } } $slug_unique = 1; while(true) { $location_slug = $mCities->findBySlug($slug); if(isset($location_slug['s_slug']) && $location_slug['pk_i_id']!=$cityId) { $slug = $slug_tmp . '-' . $slug_unique; $slug_unique++; } else { break; } } $mCities->update(array('s_name' => $newCity, 's_slug' => $slug) ,array('pk_i_id' => $cityId)); ItemLocation::newInstance()->update( array('s_city' => $newCity), array('fk_i_city_id' => $cityId) ); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code='.@$country['pk_c_code']."&country=".@$country['s_name']."®ion=".@$region['pk_i_id']); break; case('delete_city'): // delete city if( defined('DEMO') ) { osc_add_flash_warning_message( _m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); } osc_csrf_check(); $mCities = new City(); $cityIds = Params::getParam('id'); if(is_array($cityIds)) { $locations = 0; $del_locations = 0; $cCity = end($cityIds); $cCity = $mCities->findByPrimaryKey($cCity); $region = Region::newInstance()->findByPrimaryKey($cCity['fk_i_region_id']); $country = Country::newInstance()->findByCode($cCity['fk_c_country_code']); foreach($cityIds as $cityId) { $ok = $mCities->deleteByPrimaryKey($cityId); if($ok==0) { $del_locations++; } else { $locations += $ok; } } if($locations==0) { osc_add_flash_ok_message(sprintf(_n('One location has been deleted', '%d locations have been deleted', $del_locations), $del_locations), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem deleting locations'), 'admin'); } } else { osc_add_flash_error_message(_m('No city was selected'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code='.@$country['pk_c_code']."&country=".@$country['s_name']."®ion=".@$region['pk_i_id']); break; } $aCountries = $mCountries->listAll(); $this->_exportVariableToView('aCountries', $aCountries); $this->doView('settings/locations.php'); }
function doModel() { //specific things for this class switch ($this->action) { case 'bulk_actions': break; case 'regions': //Return regions given a countryId $regions = Region::newInstance()->findByCountry(Params::getParam("countryId")); echo json_encode($regions); break; case 'cities': //Returns cities given a regionId $cities = City::newInstance()->findByRegion(Params::getParam("regionId")); echo json_encode($cities); break; case 'location': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term")); echo json_encode($cities); break; case 'userajax': // This is the autocomplete AJAX $users = User::newInstance()->ajax(Params::getParam("term")); if (count($users) == 0) { echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results')))); } else { echo json_encode($users); } break; case 'date_format': echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date('Y-m-d H:i:s'), Params::getParam('format')))); break; case 'runhook': // run hooks $hook = Params::getParam('hook'); if ($hook == '') { echo json_encode(array('error' => 'hook parameter not defined')); break; } switch ($hook) { case 'item_form': osc_run_hook('item_form', Params::getParam('catId')); break; case 'item_edit': $catId = Params::getParam("catId"); $itemId = Params::getParam("itemId"); osc_run_hook("item_edit", $catId, $itemId); break; default: osc_run_hook('ajax_admin_' . $hook); break; } break; case 'categories_order': // Save the order of the categories osc_csrf_check(false); $aIds = Params::getParam('list'); $orderParent = 0; $orderSub = 0; $catParent = 0; $error = 0; $catManager = Category::newInstance(); $aRecountCat = array(); foreach ($aIds as $id => $parent) { if ($parent == 'root') { $res = $catManager->updateOrder($id, $orderParent); if (is_bool($res) && !$res) { $error = 1; } // find category $auxCategory = Category::newInstance()->findByPrimaryKey($id); // set parent category $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = NULL; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok $parentId = $auxCategory['fk_i_parent_id']; if ($parentId) { // update parent category stats array_push($aRecountCat, $id); array_push($aRecountCat, $parentId); } } } $orderParent++; } else { if ($parent != $catParent) { $catParent = $parent; $orderSub = 0; } $res = $catManager->updateOrder($id, $orderSub); if (is_bool($res) && !$res) { $error = 1; } // set parent category $auxCategory = Category::newInstance()->findByPrimaryKey($id); $auxCategoryP = Category::newInstance()->findByPrimaryKey($catParent); $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = $catParent; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok // update category parent $prevParentId = $auxCategory['fk_i_parent_id']; $parentId = $auxCategoryP['pk_i_id']; array_push($aRecountCat, $prevParentId); array_push($aRecountCat, $parentId); } } $orderSub++; } } // update category stats foreach ($aRecountCat as $rId) { osc_update_cat_stats_id($rId); } if ($error) { $result = array('error' => __("An error occurred")); } else { $result = array('ok' => __("Order saved")); } echo json_encode($result); break; case 'category_edit_iframe': $this->_exportVariableToView('category', Category::newInstance()->findByPrimaryKey(Params::getParam("id"))); $this->_exportVariableToView('languages', OSCLocale::newInstance()->listAllEnabled()); $this->doView("categories/iframe.php"); break; case 'field_categories_iframe': $selected = Field::newInstance()->categories(Params::getParam("id")); if ($selected == null) { $selected = array(); } $this->_exportVariableToView("selected", $selected); $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id"))); $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll()); $this->doView("fields/iframe.php"); break; case 'field_categories_post': osc_csrf_check(false); $error = 0; $field = Field::newInstance()->findByName(Params::getParam("s_name")); if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) { // remove categories from a field Field::newInstance()->cleanCategoriesFromField(Params::getParam("id")); // no error... continue updating fields if ($error == 0) { $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name"); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } // trim options $s_options = ''; $aux = Params::getParam('s_options'); $aAux = explode(',', $aux); foreach ($aAux as &$option) { $option = trim($option); } $s_options = implode(',', $aAux); $res = Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 's_options' => $s_options), array('pk_i_id' => Params::getParam("id"))); if (is_bool($res) && !$res) { $error = 1; } } // no error... continue inserting categories-field if ($error == 0) { $aCategories = Params::getParam("categories"); if (is_array($aCategories) && count($aCategories) > 0) { $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories); if (!$res) { $error = 1; } } } // error while updating? if ($error == 1) { $message = __("An error occurred while updating."); } } else { $error = 1; $message = __("Sorry, you already have a field with that name"); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => Params::getParam("id")); } echo json_encode($result); break; case 'delete_field': osc_csrf_check(false); $res = Field::newInstance()->deleteByPrimaryKey(Params::getParam('id')); if ($res > 0) { $result = array('ok' => __('The custom field has been deleted')); } else { $result = array('error' => __('An error occurred while deleting')); } echo json_encode($result); break; case 'add_field': osc_csrf_check(false); $s_name = __('NEW custom field'); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $fieldManager = Field::newInstance(); $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array()); if ($result) { echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name)); } else { echo json_encode(array('error' => 1)); } break; case 'enable_category': osc_csrf_check(false); $id = strip_tags(Params::getParam('id')); $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0; $error = 0; $result = array(); $aUpdated = array(); $mCategory = Category::newInstance(); $aCategory = $mCategory->findByPrimaryKey($id); if ($aCategory == false) { $result = array('error' => sprintf(__("No category with id %d exists"), $id)); echo json_encode($result); break; } // root category if ($aCategory['fk_i_parent_id'] == '') { $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id)); $subCategories = $mCategory->findSubcategories($id); $aIds = array($id); $aUpdated[] = array('id' => $id); foreach ($subCategories as $subcategory) { $aIds[] = $subcategory['pk_i_id']; $aUpdated[] = array('id' => $subcategory['pk_i_id']); } Item::newInstance()->enableByCategory($enabled, $aIds); if ($enabled) { $result = array('ok' => __('The category as well as its subcategories have been enabled')); } else { $result = array('ok' => __('The category as well as its subcategories have been disabled')); } $result['affectedIds'] = $aUpdated; echo json_encode($result); break; } // subcategory $parentCategory = $mCategory->findRootCategory($id); if (!$parentCategory['b_enabled']) { $result = array('error' => __('Parent category is disabled, you can not enable that category')); echo json_encode($result); break; } $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); if ($enabled) { $result = array('ok' => __('The subcategory has been enabled')); } else { $result = array('ok' => __('The subcategory has been disabled')); } $result['affectedIds'] = array(array('id' => $id)); echo json_encode($result); break; case 'delete_category': osc_csrf_check(false); $id = Params::getParam("id"); $error = 0; $categoryManager = Category::newInstance(); $res = $categoryManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The categories have been deleted'); } else { $error = 1; $message = __('An error occurred while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'edit_category_post': osc_csrf_check(false); $id = Params::getParam("id"); $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0; $error = 0; $has_one_title = 0; $postParams = Params::getParamsAsArray(); foreach ($postParams as $k => $v) { if (preg_match('|(.+?)#(.+)|', $k, $m)) { if ($m[2] == 's_name') { if ($v != "") { $has_one_title = 1; $aFieldsDescription[$m[1]][$m[2]] = $v; $s_text = $v; } else { $aFieldsDescription[$m[1]][$m[2]] = NULL; $error = 1; } } else { $aFieldsDescription[$m[1]][$m[2]] = $v; } } } $l = osc_language(); if ($error == 0 || $error == 1 && $has_one_title == 1) { $categoryManager = Category::newInstance(); $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id); $categoryManager->updateExpiration($id, $fields['i_expiration_days']); if (is_bool($res)) { $error = 2; } } if (Params::getParam('apply_changes_to_subcategories') == 1) { $subcategories = $categoryManager->findSubcategories($id); foreach ($subcategories as $subc) { $categoryManager->updateExpiration($subc['pk_i_id'], $fields['i_expiration_days']); } } if ($error == 0) { $msg = __("Category updated correctly"); } else { if ($error == 1) { if ($has_one_title == 1) { $error = 4; $msg = __('Category updated correctly, but some titles are empty'); } else { $msg = __('Sorry, including at least a title is mandatory'); } } else { if ($error == 2) { $msg = __('An error occurred while updating'); } } } echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name'])); break; case 'custom': // Execute via AJAX custom file $ajaxFile = Params::getParam("ajaxfile"); if ($ajaxFile == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (stripos($ajaxFile, '../') !== false) { echo json_encode(array('error' => 'no valid ajaxFile')); break; } if (!file_exists(osc_plugins_path() . $ajaxFile)) { echo json_encode(array('error' => "ajaxFile doesn't exist")); break; } require_once osc_plugins_path() . $ajaxFile; break; case 'test_mail': $title = sprintf(__('Test email, %s'), osc_page_title()); $body = __("Test email") . "<br><br>" . osc_page_title(); $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body); $array = array(); if (osc_sendMail($emailParams)) { $array = array('status' => '1', 'html' => __('Email sent successfully')); } else { $array = array('status' => '0', 'html' => __('An error occurred while sending email')); } echo json_encode($array); break; case 'test_mail_template': // replace por valores por defecto $email = Params::getParam("email"); $title = Params::getParam("title"); $body = urldecode(Params::getParam("body")); $emailParams = array('subject' => $title, 'to' => $email, 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body); $array = array(); if (osc_sendMail($emailParams)) { $array = array('status' => '1', 'html' => __('Email sent successfully')); } else { $array = array('status' => '0', 'html' => __('An error occurred while sending email')); } echo json_encode($array); break; case 'order_pages': osc_csrf_check(false); $order = Params::getParam("order"); $id = Params::getParam("id"); if ($order != '' && $id != '') { $mPages = Page::newInstance(); $actual_page = $mPages->findByPrimaryKey($id); $actual_order = $actual_page['i_order']; $array = array(); $condition = array(); $new_order = $actual_order; if ($order == 'up') { $page = $mPages->findPrevPage($actual_order); } else { if ($order == 'down') { $page = $mPages->findNextPage($actual_order); } } if (isset($page['i_order'])) { $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id)); $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id'])); } } break; /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ case 'upgrade': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(false); $message = ""; $error = 0; $sql_error_msg = ""; $rm_errors = 0; $perms = osc_save_permissions(); osc_change_permissions(); $maintenance_file = ABS_PATH . '.maintenance'; $fileHandler = @fopen($maintenance_file, 'w'); fclose($fileHandler); /*********************** **** DOWNLOAD FILE **** ***********************/ $data = osc_file_get_contents("http://osclass.org/latest_version.php"); $data = json_decode(substr($data, 1, strlen($data) - 3), true); $source_file = $data['url']; if ($source_file != '') { $tmp = explode("/", $source_file); $filename = end($tmp); $result = osc_downloadFile($source_file, $filename); if ($result) { // Everything is OK, continue /********************** ***** UNZIP FILE ***** **********************/ @mkdir(ABS_PATH . 'oc-temp', 0777); $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/'); if ($res == 1) { // Everything is OK, continue /********************** ***** COPY FILES ***** **********************/ $fail = -1; if ($handle = opendir(ABS_PATH . 'oc-temp')) { $fail = 0; while (false !== ($_file = readdir($handle))) { if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') { $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file); if ($data == false) { $fail = 1; } } } closedir($handle); //TRY TO REMOVE THE ZIP PACKAGE @unlink(osc_content_path() . 'downloads/' . $filename); if ($fail == 0) { // Everything is OK, continue /************************ *** UPGRADE DATABASE *** ************************/ $error_queries = array(); if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) { $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql'); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $error_queries = $comm->updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql)); } if ($error_queries[0]) { // Everything is OK, continue /********************************** ** EXECUTING ADDITIONAL ACTIONS ** **********************************/ if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) { // There should be no errors here define('AUTO_UPGRADE', true); require_once osc_lib_path() . 'osclass/upgrade-funcs.php'; } // Additional actions is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue /**************************** ** REMOVE TEMPORARY FILES ** ****************************/ $path = ABS_PATH . 'oc-temp'; $rm_errors = 0; $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); for ($dir->rewind(); $dir->valid(); $dir->next()) { if ($dir->isDir()) { if ($dir->getFilename() != '.' && $dir->getFilename() != '..') { if (!rmdir($dir->getPathname())) { $rm_errors++; } } } else { if (!unlink($dir->getPathname())) { $rm_errors++; } } } if (!rmdir($path)) { $rm_errors++; } $deleted = @unlink(ABS_PATH . '.maintenance'); if ($rm_errors == 0) { $message = __('Everything looks good! Your Osclass installation is up-to-date'); } else { $message = __('Nearly everything looks good! Your Osclass installation is up-to-date, but there were some errors removing temporary files. Please manually remove the "oc-temp" folder'); $error = 6; // Some errors removing files } } else { $sql_error_msg = $error_queries[2]; $message = __('Problems when upgrading the database'); $error = 5; // Problems upgrading the database } } else { $message = __('Problems when copying files. Please check your permissions. '); $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file! } } else { $message = __('Unzip failed'); $error = 3; // Unzip failed } } else { $message = __('Download failed'); $error = 2; // Download failed } } else { $message = __('Missing download URL'); $error = 1; // Missing download URL } if ($error == 5) { $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed:') . implode("<br />", $sql_error_msg); } echo $message; foreach ($perms as $k => $v) { @chmod($k, $v); } break; /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ /******************************* ** COMPLETE MARKET PROCESS ** *******************************/ case 'market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT osc_csrf_check(false); $section = Params::getParam('section'); $code = Params::getParam('code'); $plugin = false; $re_enable = false; $message = ""; $error = 0; $data = array(); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $url = osc_market_url($section, $code); $data = json_decode(osc_file_get_contents($url), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $data = json_decode(osc_file_get_contents($code), true); } else { echo json_encode(array('error' => 8, 'error_msg' => __('No external sources are allowed'))); break; } } /*********************** **** DOWNLOAD FILE **** ***********************/ if (isset($data['s_update_url']) && isset($data['s_source_file']) && isset($data['e_type'])) { if ($data['e_type'] == 'THEME') { $folder = 'themes/'; } else { if ($data['e_type'] == 'LANGUAGE') { $folder = 'languages/'; } else { // PLUGINS $folder = 'plugins/'; $plugin = Plugins::findByUpdateURI($data['s_update_url']); if ($plugin != false) { if (Plugins::isEnabled($plugin)) { Plugins::runHook($plugin . '_disable'); Plugins::deactivate($plugin); $re_enable = true; } } } } $filename = $data['s_update_url'] . "_" . $data['s_version'] . ".zip"; $url_source_file = $data['s_source_file']; // error_log('Source file: ' . $url_source_file); // error_log('Filename: ' . $filename); $result = osc_downloadFile($url_source_file, $filename); if ($result) { // Everything is OK, continue /********************** ***** UNZIP FILE ***** **********************/ @mkdir(ABS_PATH . 'oc-temp', 0777); $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, osc_content_path() . 'downloads/oc-temp/'); if ($res == 1) { // Everything is OK, continue /********************** ***** COPY FILES ***** **********************/ $fail = -1; if ($handle = opendir(osc_content_path() . 'downloads/oc-temp')) { $folder_dest = ABS_PATH . "oc-content/" . $folder; if (function_exists('posix_getpwuid')) { $current_user = posix_getpwuid(posix_geteuid()); $ownerFolder = posix_getpwuid(fileowner($folder_dest)); } $fail = 0; while (false !== ($_file = readdir($handle))) { if ($_file != '.' && $_file != '..') { $copyprocess = osc_copy(osc_content_path() . "downloads/oc-temp/" . $_file, $folder_dest . $_file); if ($copyprocess == false) { $fail = 1; } } } closedir($handle); // Additional actions is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue // Also remove the zip package /**************************** ** REMOVE TEMPORARY FILES ** ****************************/ @unlink(osc_content_path() . 'downloads/' . $filename); $path = osc_content_path() . 'downloads/oc-temp'; $rm_errors = 0; $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); for ($dir->rewind(); $dir->valid(); $dir->next()) { if ($dir->isDir()) { if ($dir->getFilename() != '.' && $dir->getFilename() != '..') { if (!rmdir($dir->getPathname())) { $rm_errors++; } } } else { if (!unlink($dir->getPathname())) { $rm_errors++; } } } if (!rmdir($path)) { $rm_errors++; } if ($fail == 0) { // Everything is OK, continue if ($data['e_type'] != 'THEME' && $data['e_type'] != 'LANGUAGE') { if ($plugin != false && $re_enable) { $enabled = Plugins::activate($plugin); if ($enabled) { Plugins::runHook($plugin . '_enable'); } } } // recount plugins&themes for update if ($section == 'plugins') { osc_check_plugins_update(true); } else { if ($section == 'themes') { osc_check_themes_update(true); } else { if ($section == 'languages') { // load oc-content/ if (osc_checkLocales()) { $message .= __('The language has been installed correctly'); } else { $message .= __('There was a problem adding the language'); $error = 8; } osc_check_languages_update(true); } } } if ($rm_errors == 0) { $message = __('Everything looks good!'); $error = 0; } else { $message = __('Nearly everything looks good! but there were some errors removing temporary files. Please manually remove the \\"oc-temp\\" folder'); $error = 6; // Some errors removing files } } else { $message = __('Problems when copying files. Please check your permissions. '); if ($current_user['uid'] != $ownerFolder['uid']) { if (function_exists('posix_getgrgid')) { $current_group = posix_getgrgid($current_user['gid']); $message .= '<p><strong>' . sprintf(__('NOTE: Web user and destination folder user is not the same, you might have an issue there. <br/>Do this in your console:<br/>chown -R %s:%s %s'), $current_user['name'], $current_group['name'], $folder_dest) . '</strong></p>'; } } $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file! } } else { $message = __('Unzip failed'); $error = 3; // Unzip failed } } else { $message = __('Download failed'); $error = 2; // Download failed } } else { $message = __('Input code not valid'); $error = 7; // Input code not valid } } else { $message = __('Missing download URL'); $error = 1; // Missing download URL } echo json_encode(array('error' => $error, 'message' => $message, 'data' => $data)); break; case 'check_market': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT $section = Params::getParam('section'); $code = Params::getParam('code'); $data = array(); /************************ *** CHECK VALID CODE *** ************************/ if ($code != '' && $section != '') { if (stripos($code, "http://") === FALSE) { // OSCLASS OFFICIAL REPOSITORY $data = json_decode(osc_file_get_contents(osc_market_url($section, $code)), true); } else { // THIRD PARTY REPOSITORY if (osc_market_external_sources()) { $data = json_decode(osc_file_get_contents($code), true); } else { echo json_encode(array('error' => 3, 'error_msg' => __('No external sources are allowed'))); break; } } if (!isset($data['s_source_file']) || !isset($data['s_update_url'])) { $data = array('error' => 2, 'error_msg' => __('Invalid code')); } } else { $data = array('error' => 1, 'error_msg' => __('No code was submitted')); } echo json_encode($data); break; case 'market_data': $section = Params::getParam('section'); $page = Params::getParam("mPage"); $featured = Params::getParam("featured"); $sort = Params::getParam("sort"); $order = Params::getParam("order"); // for the moment this value is static $length = 9; if ($page >= 1) { $page--; } $url = osc_market_url($section) . "page/" . $page . '/'; if ($length != '' && is_numeric($length)) { $url .= 'length/' . $length . '/'; } if ($sort != '') { $url .= 'order/' . $sort; if ($order != '') { $url .= '/' . $order; } } if ($featured != '') { $url = osc_market_featured_url($section); } $data = array(); $data = json_decode(osc_file_get_contents($url), true); if (!isset($data[$section])) { $data = array('error' => 1, 'error_msg' => __('No market data')); } echo 'var market_data = window.market_data || {}; market_data.' . $section . ' = ' . json_encode($data) . ';'; break; case 'local_market': // AVOID CROSS DOMAIN PROBLEMS OF AJAX REQUEST $marketPage = Params::getParam("mPage"); if ($marketPage >= 1) { $marketPage--; } $out = osc_file_get_contents(osc_market_url(Params::getParam("section")) . "page/" . $marketPage); $array = json_decode($out, true); // do pagination $pageActual = $array['page']; $totalPages = ceil($array['total'] / $array['sizePage']); $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => '#{PAGE}', 'sides' => 5); // set pagination $pagination = new Pagination($params); $aux = $pagination->doPagination(); $array['pagination_content'] = $aux; // encode to json echo json_encode($array); break; case 'dashboardbox_market': $error = 0; // make market call $url = getPreference('marketURL') . 'dashboardbox/'; $content = ''; if (false === ($json = @osc_file_get_contents($url))) { $error = 1; } else { $content = $json; } if ($error == 1) { echo json_encode(array('error' => 1)); } else { // replace content with correct urls $content = str_replace('{URL_MARKET_THEMES}', osc_admin_base_url(true) . '?page=market&action=themes', $content); $content = str_replace('{URL_MARKET_PLUGINS}', osc_admin_base_url(true) . '?page=market&action=plugins', $content); echo json_encode(array('html' => $content)); } break; case 'location_stats': osc_csrf_check(false); $workToDo = osc_update_location_stats(); if ($workToDo > 0) { $array['status'] = 'more'; $array['pending'] = $workToDo; echo json_encode($array); } else { $array['status'] = 'done'; echo json_encode($array); } break; case 'error_permissions': echo json_encode(array('error' => __("You don't have the necessary permissions"))); break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
function _need_update($uri, $version) { if (false === ($json = @osc_file_get_contents($uri))) { return false; } else { $data = json_decode($json, true); if (isset($data['s_version']) && $data['s_version'] > $version) { return true; } } }
/** * Check if a package could be update or not * * @param string $update_uri * @since 2.4 * @return boolean */ function osc_check_update($update_uri, $version = null) { if ($update_uri != "" && $version != null) { if (stripos("http://", $update_uri) === FALSE) { // OSCLASS OFFICIAL REPOSITORY $uri = osc_market_url($update_uri); } else { // THIRD PARTY REPOSITORY if (!osc_market_external_sources()) { return false; } $uri = $update_uri; } if (false === ($json = @osc_file_get_contents($uri))) { return false; } else { $data = json_decode($json, true); if (isset($data['s_version']) && $data['s_version'] > $version) { return true; } } } return false; }
function location_by_city() { if (!isset($_POST['country'])) { return false; } if (!isset($_POST['city'])) { return false; } $country = $_POST['country']; $city = $_POST['city']; $countries_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=country&term=' . urlencode(implode(',', $country)) . "&install=true"); $countries = json_decode($countries_json); $manager_country = Country::newInstance(); foreach ($countries as $c) { $manager_country->insert(array("pk_c_code" => $c->id, "fk_c_locale_code" => $c->locale_code, "s_name" => $c->name)); } $manager_city = City::newInstance(); $manager_region = Region::newInstance(); foreach ($countries as $c) { $cities_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=city&country=' . urlencode($c->name) . '&term=' . urlencode(implode(',', $city))); $cities = json_decode($cities_json); if (!isset($cities->error)) { foreach ($cities as $ci) { $regions_json = osc_file_get_contents('http://geo.osclass.org/geo.download.php?action=region&country=&id=' . $ci->region_id); $regions = json_decode($regions_json); foreach ($regions as $r) { $manager_region->insert(array("pk_i_id" => $r->id, "fk_c_country_code" => $r->country_code, "s_name" => $r->name)); } $manager_city->insert(array("pk_i_id" => $ci->id, "fk_i_region_id" => $ci->region_id, "s_name" => $ci->name, "fk_c_country_code" => $ci->country_code)); } } unset($cities); unset($cities_json); } }
function install_locations() { $country = Params::getParam("country-input"); $region = Params::getParam("region-input"); $city = Params::getParam("city-input"); if ($country != 'all') { if ($region != 'all') { if ($city != 'all') { $sql = 'action=city&term=' . urlencode($city); } else { $sql = 'action=region&term=' . urlencode($region); } } else { $sql = 'action=country&term=' . urlencode($country); } } else { $sql = 'action=country&term=all'; } $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?' . $sql . '&install=true'); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $imported = $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); return $imported; }
function doModel() { //specific things for this class switch ($this->action) { case 'bulk_actions': break; case 'regions': //Return regions given a countryId $regions = Region::newInstance()->findByCountry(Params::getParam("countryId")); echo json_encode($regions); break; case 'cities': //Returns cities given a regionId $cities = City::newInstance()->findByRegion(Params::getParam("regionId")); echo json_encode($cities); break; case 'location': // This is the autocomplete AJAX $cities = City::newInstance()->ajax(Params::getParam("term")); echo json_encode($cities); break; case 'userajax': // This is the autocomplete AJAX $users = User::newInstance()->ajax(Params::getParam("term")); if (count($users) == 0) { echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results')))); } else { echo json_encode($users); } break; case 'date_format': echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date(Params::getParam('format'))))); break; case 'runhook': // run hooks $hook = Params::getParam('hook'); if ($hook == '') { echo json_encode(array('error' => 'hook parameter not defined')); break; } switch ($hook) { case 'item_form': osc_run_hook('item_form', Params::getParam('catId')); break; case 'item_edit': $catId = Params::getParam("catId"); $itemId = Params::getParam("itemId"); osc_run_hook("item_edit", $catId, $itemId); break; default: osc_run_hook('ajax_admin_' . $hook); break; } break; case 'items': // Return items (use external file oc-admin/ajax/item_processing.php) require_once osc_admin_base_path() . 'ajax/items_processing.php'; $items_processing = new ItemsProcessingAjax(Params::getParamsAsArray("get")); break; case 'users': // Return items (use external file oc-admin/ajax/item_processing.php) require_once osc_admin_base_path() . 'ajax/users_processing.php'; $users_processing = new UsersProcessingAjax(Params::getParamsAsArray("get")); break; case 'media': // Return items (use external file oc-admin/ajax/media_processing.php) require_once osc_admin_base_path() . 'ajax/media_processing.php'; $media_processing = new MediaProcessingAjax(Params::getParamsAsArray("get")); break; case 'categories_order': // Save the order of the categories $aIds = Params::getParam('list'); $orderParent = 0; $orderSub = 0; $catParent = 0; $error = 0; $catManager = Category::newInstance(); $aRecountCat = array(); foreach ($aIds as $id => $parent) { if ($parent == 'root') { $res = $catManager->updateOrder($id, $orderParent); if (is_bool($res) && !$res) { $error = 1; } // find category $auxCategory = Category::newInstance()->findByPrimaryKey($id); // set parent category $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = NULL; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok $parentId = $auxCategory['fk_i_parent_id']; if ($parentId) { // update parent category stats array_push($aRecountCat, $id); array_push($aRecountCat, $parentId); } } } $orderParent++; } else { if ($parent != $catParent) { $catParent = $parent; $orderSub = 0; } $res = $catManager->updateOrder($id, $orderSub); if (is_bool($res) && !$res) { $error = 1; } // set parent category $auxCategory = Category::newInstance()->findByPrimaryKey($id); $auxCategoryP = Category::newInstance()->findByPrimaryKey($catParent); $conditions = array('pk_i_id' => $id); $array['fk_i_parent_id'] = $catParent; $res = $catManager->update($array, $conditions); if (is_bool($res) && !$res) { $error = 1; } else { if ($res == 1) { // updated ok // update category parent $prevParentId = $auxCategory['fk_i_parent_id']; $parentId = $auxCategoryP['pk_i_id']; array_push($aRecountCat, $prevParentId); array_push($aRecountCat, $parentId); } } $orderSub++; } } // update category stats foreach ($aRecountCat as $rId) { osc_update_cat_stats_id($rId); } if ($error) { $result = array('error' => __("Some error ocurred")); } else { $result = array('ok' => __("Order saved")); } echo json_encode($result); break; case 'category_edit_iframe': $this->_exportVariableToView('category', Category::newInstance()->findByPrimaryKey(Params::getParam("id"))); $this->_exportVariableToView('languages', OSCLocale::newInstance()->listAllEnabled()); $this->doView("categories/iframe.php"); break; case 'field_categories_iframe': $selected = Field::newInstance()->categories(Params::getParam("id")); if ($selected == null) { $selected = array(); } $this->_exportVariableToView("selected", $selected); $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id"))); $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll()); $this->doView("fields/iframe.php"); break; case 'field_categories_post': $error = 0; $field = Field::newInstance()->findByName(Params::getParam("s_name")); if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) { // remove categories from a field Field::newInstance()->cleanCategoriesFromField(Params::getParam("id")); // no error... continue updating fields if ($error == 0) { $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name"); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $res = Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 's_options' => Params::getParam('s_options')), array('pk_i_id' => Params::getParam("id"))); if (is_bool($res) && !$res) { $error = 1; } } // no error... continue inserting categories-field if ($error == 0) { $aCategories = Params::getParam("categories"); if (is_array($aCategories) && count($aCategories) > 0) { $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories); if (!$res) { $error = 1; } } } // error while updating? if ($error == 1) { $message = __("Error while updating."); } } else { $error = 1; $message = __("Sorry, you already have one field with that name"); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => $field['pk_i_id']); } echo json_encode($result); break; case 'delete_field': $id = Params::getParam("id"); $error = 0; $fieldManager = Field::newInstance(); $res = $fieldManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The custom field have been deleted'); } else { $error = 1; $message = __('Error while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'add_field': $s_name = __('NEW custom field'); $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name))); $slug_k = 0; while (true) { $field = Field::newInstance()->findBySlug($slug); if (!$field || $field['pk_i_id'] == Params::getParam("id")) { break; } else { $slug_k++; $slug = $slug_tmp . "_" . $slug_k; } } $fieldManager = Field::newInstance(); $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array()); if ($result) { echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name)); } else { echo json_encode(array('error' => 1)); } break; case 'enable_category': $id = strip_tags(Params::getParam('id')); $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0; $error = 0; $result = array(); $aUpdated = array(); $mCategory = Category::newInstance(); $aCategory = $mCategory->findByPrimaryKey($id); if ($aCategory == false) { $result = array('error' => sprintf(__("It doesn't exist a category with this id: %d"), $id)); echo json_encode($result); break; } // root category if ($aCategory['fk_i_parent_id'] == '') { $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id)); $subCategories = $mCategory->findSubcategories($id); $aIds = array($id); $aUpdated[] = array('id' => $id); foreach ($subCategories as $subcategory) { $aIds[] = $subcategory['pk_i_id']; $aUpdated[] = array('id' => $subcategory['pk_i_id']); } Item::newInstance()->enableByCategory($enabled, $aIds); if ($enabled) { $result = array('ok' => __('The category and its subcategories have been enabled')); } else { $result = array('ok' => __('The category and its subcategories have been disabled')); } $result['affectedIds'] = $aUpdated; echo json_encode($result); break; } // subcategory $parentCategory = $mCategory->findRootCategory($id); if (!$parentCategory['b_enabled']) { $result = array('error' => __('Parent category is disabled, you can not enable that category')); echo json_encode($result); break; } $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id)); if ($enabled) { $result = array('ok' => __('The subcategory has been enabled')); } else { $result = array('ok' => __('The subcategory has been disabled')); } $result['affectedIds'] = array(array('id' => $id)); echo json_encode($result); break; case 'delete_category': $id = Params::getParam("id"); $error = 0; $categoryManager = Category::newInstance(); $res = $categoryManager->deleteByPrimaryKey($id); if ($res > 0) { $message = __('The categories have been deleted'); } else { $error = 1; $message = __('Error while deleting'); } if ($error) { $result = array('error' => $message); } else { $result = array('ok' => __("Saved")); } echo json_encode($result); break; case 'edit_category_post': $id = Params::getParam("id"); $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0; $error = 0; $has_one_title = 0; $postParams = Params::getParamsAsArray(); foreach ($postParams as $k => $v) { if (preg_match('|(.+?)#(.+)|', $k, $m)) { if ($m[2] == 's_name') { if ($v != "") { $has_one_title = 1; $aFieldsDescription[$m[1]][$m[2]] = $v; $s_text = $v; } else { $aFieldsDescription[$m[1]][$m[2]] = ' '; $error = 1; } } else { $aFieldsDescription[$m[1]][$m[2]] = $v; } } } $l = osc_language(); if ($error == 0 || $error == 1 && $has_one_title == 1) { $categoryManager = Category::newInstance(); $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id); if (is_bool($res)) { $error = 2; } } if ($error == 0) { $msg = __("Category updated correctly"); } else { if ($error == 1) { if ($has_one_title == 1) { $error = 4; $msg = __('Category updated correctly, but some titles were empty'); } else { $msg = __('Sorry, at least a title is needed'); } } else { if ($error == 2) { $msg = __('Error while updating'); } } } echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name'])); break; case 'custom': // Execute via AJAX custom file $ajaxFile = Params::getParam("ajaxfile"); if ($ajaxFile == '') { echo json_encode(array('error' => 'no action defined')); break; } // valid file? if (stripos($ajaxFile, '../') !== false) { echo json_encode(array('error' => 'no valid ajaxFile')); break; } if (!file_exists(osc_plugins_path() . $ajaxFile)) { echo json_encode(array('error' => "ajaxFile doesn't exist")); break; } require_once osc_plugins_path() . $ajaxFile; break; case 'test_mail': $title = sprintf(__('Test email, %s'), osc_page_title()); $body = __("Test email") . "<br><br>" . osc_page_title(); $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body); $array = array(); if (osc_sendMail($emailParams)) { $array = array('status' => '1', 'html' => __('Email sent successfully')); } else { $array = array('status' => '0', 'html' => __('An error has occurred while sending email')); } echo json_encode($array); break; case 'order_pages': $order = Params::getParam("order"); $id = Params::getParam("id"); if ($order != '' && $id != '') { $mPages = Page::newInstance(); $actual_page = $mPages->findByPrimaryKey($id); $actual_order = $actual_page['i_order']; $array = array(); $condition = array(); $new_order = $actual_order; if ($order == 'up') { $page = $mPages->findPrevPage($actual_order); } else { if ($order == 'down') { $page = $mPages->findNextPage($actual_order); } } if (isset($page['i_order'])) { $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id)); $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id'])); } // TO BE IMPROVED // json for datatables $prefLocale = osc_current_user_locale(); $this->_exportVariableToView('pages', $mPages->listAll(0)); $o_json = array(); while (osc_has_static_pages()) { $row = array(); $page = osc_static_page(); $content = array(); if (isset($page['locale'][$prefLocale]) && !empty($page['locale'][$prefLocale]['s_title'])) { $content = $page['locale'][$prefLocale]; } else { $content = current($page['locale']); } $options = array(); $options[] = '<a href="' . osc_static_page_url() . '">' . __('View page') . '</a>'; $options[] = '<a href="' . osc_admin_base_url(true) . '?page=pages&action=edit&id=' . osc_static_page_id() . '">' . __('Edit') . '</a>'; if (!$page['b_indelible']) { $options[] = '<a onclick="javascript:return confirm(\'' . osc_esc_js("This action can't be undone. Are you sure you want to continue?") . '\')" href="' . osc_admin_base_url(true) . '?page=pages&action=delete&id=' . osc_static_page_id() . '">' . __('Delete') . '</a>'; } $row[] = '<input type="checkbox" name="id[]"" value="' . osc_static_page_id() . '"" />'; $row[] = $page['s_internal_name'] . '<div id="datatables_quick_edit" style="display: none;">' . implode(' · ', $options) . '</div>'; $row[] = $content['s_title']; $row[] = osc_static_page_order() . ' <img id="up" onclick="order_up(' . osc_static_page_id() . ');" style="cursor:pointer; width:15px; height:15px;" src="' . osc_current_admin_theme_url('images/arrow_up.png') . '"/> <br/><img id="down" onclick="order_down(' . osc_static_page_id() . ');" style="cursor:pointer; width:15px; height:15px; margin-left: 10px;" src="' . osc_current_admin_theme_url('images/arrow_down.png') . '"/>'; $o_json[] = $row; } echo json_encode($o_json); } break; /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ /****************************** ** COMPLETE UPGRADE PROCESS ** ******************************/ case 'upgrade': // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT $message = ""; $error = 0; $sql_error_msg = ""; $rm_errors = 0; $perms = osc_save_permissions(); osc_change_permissions(); $maintenance_file = ABS_PATH . '.maintenance'; $fileHandler = @fopen($maintenance_file, 'w'); fclose($fileHandler); /*********************** **** DOWNLOAD FILE **** ***********************/ $data = osc_file_get_contents("http://osclass.org/latest_version.php"); $data = json_decode(substr($data, 1, strlen($data) - 3), true); $source_file = $data['url']; if ($source_file != '') { $tmp = explode("/", $source_file); $filename = end($tmp); $result = osc_downloadFile($source_file, $filename); if ($result) { // Everything is OK, continue /********************** ***** UNZIP FILE ***** **********************/ @mkdir(ABS_PATH . 'oc-temp', 0777); $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/'); if ($res == 1) { // Everything is OK, continue /********************** ***** COPY FILES ***** **********************/ $fail = -1; if ($handle = opendir(ABS_PATH . 'oc-temp')) { $fail = 0; while (false !== ($_file = readdir($handle))) { if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') { $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file); if ($data == false) { $fail = 1; } } } closedir($handle); if ($fail == 0) { // Everything is OK, continue /************************ *** UPGRADE DATABASE *** ************************/ $error_queries = array(); if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) { $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql'); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $error_queries = $comm->updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql)); } if ($error_queries[0]) { // Everything is OK, continue /********************************** ** EXECUTING ADDITIONAL ACTIONS ** **********************************/ if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) { // There should be no errors here define('AUTO_UPGRADE', true); require_once osc_lib_path() . 'osclass/upgrade-funcs.php'; } // Additional actions is not important for the rest of the proccess // We will inform the user of the problems but the upgrade could continue /**************************** ** REMOVE TEMPORARY FILES ** ****************************/ $path = ABS_PATH . 'oc-temp'; $rm_errors = 0; $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); for ($dir->rewind(); $dir->valid(); $dir->next()) { if ($dir->isDir()) { if ($dir->getFilename() != '.' && $dir->getFilename() != '..') { if (!rmdir($dir->getPathname())) { $rm_errors++; } } } else { if (!unlink($dir->getPathname())) { $rm_errors++; } } } if (!rmdir($path)) { $rm_errors++; } $deleted = @unlink(ABS_PATH . '.maintenance'); if ($rm_errors == 0) { $message = __('Everything was OK! Your OSClass installation is updated'); } else { $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder'); $error = 6; // Some errors removing files } } else { $sql_error_msg = $error_queries[2]; $message = __('Problems upgrading the database'); $error = 5; // Problems upgrading the database } } else { $message = __('Problems copying files. Maybe permissions are not correct'); $error = 4; // Problems copying files. Maybe permissions are not correct } } else { $message = __('Nothing to copy'); $error = 99; // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file! } } else { $message = __('Unzip failed'); $error = 3; // Unzip failed } } else { $message = __('Download failed'); $error = 2; // Download failed } } else { $message = __('Missing download URL'); $error = 1; // Missing download URL } if ($error == 5) { $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed') . implode("<br />", $sql_error_msg); } echo $message; foreach ($perms as $k => $v) { @chmod($k, $v); } break; case 'location_stats': $workToDo = LocationsTmp::newInstance()->count(); if ($workToDo > 0) { // there are wotk to do $aLocations = LocationsTmp::newInstance()->getLocations(1000); foreach ($aLocations as $location) { $id = $location['id_location']; $type = $location['e_type']; $data = 0; // update locations stats switch ($type) { case 'COUNTRY': $numItems = CountryStats::newInstance()->calculateNumItems($id); $data = CountryStats::newInstance()->setNumItems($id, $numItems); unset($numItems); break; case 'REGION': $numItems = RegionStats::newInstance()->calculateNumItems($id); $data = RegionStats::newInstance()->setNumItems($id, $numItems); unset($numItems); break; case 'CITY': $numItems = CityStats::newInstance()->calculateNumItems($id); $data = CityStats::newInstance()->setNumItems($id, $numItems); unset($numItems); break; default: break; } if ($data >= 0) { LocationsTmp::newInstance()->delete(array('e_type' => $location['e_type'], 'id_location' => $location['id_location'])); } } $array['status'] = 'more'; $array['pending'] = $workToDo = LocationsTmp::newInstance()->count(); echo json_encode($array); } else { $array['status'] = 'done'; echo json_encode($array); } break; default: echo json_encode(array('error' => __('no action defined'))); break; } // clear all keep variables into session Session::newInstance()->_dropKeepForm(); Session::newInstance()->_clearVariables(); }
function doModel() { switch ($this->action) { case 'comments': //calling the comments settings view $this->doView('settings/comments.php'); break; case 'comments_post': // updating comment osc_csrf_check(); $iUpdated = 0; $enabledComments = Params::getParam('enabled_comments'); $enabledComments = $enabledComments != '' ? true : false; $moderateComments = Params::getParam('moderate_comments'); $moderateComments = $moderateComments != '' ? true : false; $numModerateComments = Params::getParam('num_moderate_comments'); $commentsPerPage = Params::getParam('comments_per_page'); $notifyNewComment = Params::getParam('notify_new_comment'); $notifyNewComment = $notifyNewComment != '' ? true : false; $notifyNewCommentUser = Params::getParam('notify_new_comment_user'); $notifyNewCommentUser = $notifyNewCommentUser != '' ? true : false; $regUserPostComments = Params::getParam('reg_user_post_comments'); $regUserPostComments = $regUserPostComments != '' ? true : false; $msg = ''; if (!osc_validate_int(Params::getParam("num_moderate_comments"))) { $msg .= _m("Number of moderate comments must only contain numeric characters") . "<br/>"; } if (!osc_validate_int(Params::getParam("comments_per_page"))) { $msg .= _m("Comments per page must only contain numeric characters") . "<br/>"; } if ($msg != '') { osc_add_flash_error_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledComments), array('s_name' => 'enabled_comments')); if ($moderateComments) { $iUpdated += Preference::newInstance()->update(array('s_value' => $numModerateComments), array('s_name' => 'moderate_comments')); } else { $iUpdated += Preference::newInstance()->update(array('s_value' => '-1'), array('s_name' => 'moderate_comments')); } $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewComment), array('s_name' => 'notify_new_comment')); $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewCommentUser), array('s_name' => 'notify_new_comment_user')); $iUpdated += Preference::newInstance()->update(array('s_value' => $commentsPerPage), array('s_name' => 'comments_per_page')); $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPostComments), array('s_name' => 'reg_user_post_comments')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m("Comment settings have been updated"), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments'); break; case 'locations': // calling the locations settings view $location_action = Params::getParam('type'); $mCountries = new Country(); switch ($location_action) { case 'add_country': // add country osc_csrf_check(); $countryCode = strtoupper(Params::getParam('c_country')); $countryName = Params::getParam('country'); $exists = $mCountries->findByCode($countryCode); if (isset($exists['s_name'])) { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $countryName), 'admin'); } else { if (Params::getParam('c_manual') == 1) { $mCountries->insert(array('pk_c_code' => $countryCode, 's_name' => $countryName)); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin'); } else { if (!osc_validate_min($countryCode, 1) || !osc_validate_min($countryName, 1)) { osc_add_flash_error_message(_m('Country code and name should have at least two characters'), 'admin'); } else { $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?action=country&term=' . urlencode($countryCode)); if ($data_sql != '') { $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); } else { $mCountries->insert(array('pk_c_code' => $countryCode, 's_name' => $countryName)); } osc_add_flash_ok_message(sprintf(_m('%s has been added as a new country'), $countryName), 'admin'); } } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'edit_country': // edit country osc_csrf_check(); if (!osc_validate_min(Params::getParam('e_country'), 1)) { osc_add_flash_error_message(_m('Country name cannot be blank'), 'admin'); } else { $ok = $mCountries->update(array('s_name' => Params::getParam('e_country')), array('pk_c_code' => Params::getParam('country_code'))); if ($ok) { osc_add_flash_ok_message(_m('Country has been edited'), 'admin'); } else { osc_add_flash_error_message(_m('There were some problems editing the country'), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'delete_country': // delete country osc_csrf_check(); $countryIds = Params::getParam('id'); if (is_array($countryIds)) { $locations = 0; $del_locations = 0; foreach ($countryIds as $countryId) { $ok = $mCountries->deleteByPrimaryKey($countryId); } if ($ok == 0) { $del_locations++; } else { $locations += $ok; } if ($locations == 0) { osc_add_flash_ok_message(sprintf(_n('One location has been deleted', '%s locations have been deleted', $del_locations), $del_locations), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem deleting locations'), 'admin'); } } else { osc_add_flash_error_message(_m('No country was selected'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations'); break; case 'add_region': // add region osc_csrf_check(); if (!Params::getParam('r_manual')) { $regionId = Params::getParam('region_id'); $regionName = Params::getParam('region'); if ($regionId != '') { $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?action=region&term=' . urlencode($regionId)); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m("%s can't be added"), $regionName), 'admin'); } } else { $mRegions = new Region(); $regionName = Params::getParam('region'); $countryCode = Params::getParam('country_c_parent'); $country = Country::newInstance()->findByCode($countryCode); if (!osc_validate_min($regionName, 1)) { osc_add_flash_error_message(_m('Region name cannot be blank'), 'admin'); } else { $exists = $mRegions->findByName($regionName, $countryCode); if (!isset($exists['s_name'])) { $data = array('fk_c_country_code' => $countryCode, 's_name' => $regionName); $mRegions->insert($data); $id = $mRegions->dao->insertedId(); RegionStats::newInstance()->setNumItems($id, 0); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new region'), $regionName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $regionName), 'admin'); } } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$countryCode . "&country=" . @$country['s_name']); break; case 'edit_region': // edit region osc_csrf_check(); $mRegions = new Region(); $newRegion = Params::getParam('e_region'); $regionId = Params::getParam('region_id'); if (!osc_validate_min($newRegion, 1)) { osc_add_flash_error_message(_m('Region name cannot be blank'), 'admin'); } else { $exists = $mRegions->findByName($newRegion); if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $regionId) { if ($regionId != '') { $aRegion = $mRegions->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($aRegion['fk_c_country_code']); $mRegions->update(array('s_name' => $newRegion), array('pk_i_id' => $regionId)); ItemLocation::newInstance()->update(array('s_region' => $newRegion), array('fk_i_region_id' => $regionId)); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newRegion), 'admin'); } } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newRegion), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name']); break; case 'delete_region': // delete region osc_csrf_check(); $mRegion = new Region(); $regionIds = Params::getParam('id'); if (is_array($regionIds)) { $locations = 0; $del_locations = 0; if (count($regionIds) > 0) { $region = $mRegion->findByPrimaryKey($regionIds[0]); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); foreach ($regionIds as $regionId) { if ($regionId != '') { $ok = $mRegion->deleteByPrimaryKey($regionId); if ($ok == 0) { $del_locations++; } else { $locations += $ok; } } } } if ($locations == 0) { osc_add_flash_ok_message(sprintf(_n('One location has been deleted', '%s locations have been deleted', $del_locations), $del_locations), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem deleting locations'), 'admin'); } } else { osc_add_flash_error_message(_m('No region was selected'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name']); break; case 'add_city': // add city osc_csrf_check(); if (!Params::getParam('ci_manual')) { $cityId = Params::getParam('city_id'); $cityName = Params::getParam('city'); if ($cityId != '') { $data_sql = osc_file_get_contents('http://geo.osclass.org/newgeo.download.php?action=city&term=' . urlencode($cityId)); $conn = DBConnectionClass::newInstance(); $c_db = $conn->getOsclassDb(); $comm = new DBCommandClass($c_db); $comm->query("SET FOREIGN_KEY_CHECKS = 0"); $comm->importSQL($data_sql); $comm->query("SET FOREIGN_KEY_CHECKS = 1"); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $cityName), 'admin'); } else { osc_add_flash_error_message(sprintf(_m("%s can't be added"), $cityName), 'admin'); } } else { $mRegion = new Region(); $mCities = new City(); $regionId = Params::getParam('region_parent'); $countryCode = Params::getParam('country_c_parent'); $newCity = Params::getParam('city'); if (!osc_validate_min($newCity, 1)) { osc_add_flash_error_message(_m('New city name cannot be blank'), 'admin'); } else { $exists = $mCities->findByName($newCity, $regionId); $region = $mRegion->findByPrimaryKey($regionId); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); if (!isset($exists['s_name'])) { $mCities->insert(array('fk_i_region_id' => $regionId, 's_name' => $newCity, 'fk_c_country_code' => $countryCode)); $id = $mCities->dao->insertedId(); CityStats::newInstance()->setNumItems($id, 0); osc_add_flash_ok_message(sprintf(_m('%s has been added as a new city'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "®ion=" . $regionId); break; case 'edit_city': // edit city osc_csrf_check(); $mRegion = new Region(); $mCities = new City(); $newCity = Params::getParam('e_city'); $cityId = Params::getParam('city_id'); if (!osc_validate_min($newCity, 1)) { osc_add_flash_error_message(_m('City name cannot be blank'), 'admin'); } else { $exists = $mCities->findByName($newCity); if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $cityId) { $city = $mCities->findByPrimaryKey($cityId); $region = $mRegion->findByPrimaryKey($city['fk_i_region_id']); $country = Country::newInstance()->findByCode($region['fk_c_country_code']); $mCities->update(array('s_name' => $newCity), array('pk_i_id' => $cityId)); ItemLocation::newInstance()->update(array('s_city' => $newCity), array('fk_i_city_id' => $cityId)); osc_add_flash_ok_message(sprintf(_m('%s has been edited'), $newCity), 'admin'); } else { osc_add_flash_error_message(sprintf(_m('%s already was in the database'), $newCity), 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "®ion=" . @$region['pk_i_id']); break; case 'delete_city': // delete city osc_csrf_check(); $mCities = new City(); $cityIds = Params::getParam('id'); if (is_array($cityIds)) { $locations = 0; $del_locations = 0; $cCity = end($cityIds); $cCity = $mCities->findByPrimaryKey($cCity); $region = Region::newInstance()->findByPrimaryKey($cCity['fk_i_region_id']); $country = Country::newInstance()->findByCode($cCity['fk_c_country_code']); foreach ($cityIds as $cityId) { $ok = $mCities->deleteByPrimaryKey($cityId); if ($ok == 0) { $del_locations++; } else { $locations += $ok; } } if ($locations == 0) { osc_add_flash_ok_message(sprintf(_n('One location has been deleted', '%d locations have been deleted', $del_locations), $del_locations), 'admin'); } else { osc_add_flash_error_message(_m('There was a problem deleting locations'), 'admin'); } } else { osc_add_flash_error_message(_m('No city was selected'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations&country_code=' . @$country['pk_c_code'] . "&country=" . @$country['s_name'] . "®ion=" . @$region['pk_i_id']); break; } $aCountries = $mCountries->listAll(); $this->_exportVariableToView('aCountries', $aCountries); $this->doView('settings/locations.php'); break; case 'permalinks': // calling the permalinks view $htaccess = Params::getParam('htaccess_status'); $file = Params::getParam('file_status'); $this->_exportVariableToView('htaccess', $htaccess); $this->_exportVariableToView('file', $file); $this->doView('settings/permalinks.php'); break; case 'permalinks_post': // updating permalinks option osc_csrf_check(); $htaccess_file = osc_base_path() . '.htaccess'; $rewriteEnabled = Params::getParam('rewrite_enabled') ? true : false; if ($rewriteEnabled) { Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'rewriteEnabled')); $rewrite_base = REL_WEB_URL; $htaccess = <<<HTACCESS <IfModule mod_rewrite.c> RewriteEngine On RewriteBase {$rewrite_base} RewriteRule ^index\\.php\$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . {$rewrite_base}index.php [L] </IfModule> HTACCESS; // 1. OK (ok) // 2. OK no apache module detected (warning) // 3. No se puede crear + apache // 4. No se puede crear + no apache $status = 3; if (file_exists($htaccess_file)) { if (is_writable($htaccess_file) && file_put_contents($htaccess_file, $htaccess)) { $status = 1; } } else { if (is_writable(osc_base_path()) && file_put_contents($htaccess_file, $htaccess)) { $status = 1; } } if (!@apache_mod_loaded('mod_rewrite')) { $status++; } $errors = 0; $item_url = substr(str_replace('//', '/', Params::getParam('rewrite_item_url') . '/'), 0, -1); if (!osc_validate_text($item_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $item_url), array('s_name' => 'rewrite_item_url')); } $page_url = substr(str_replace('//', '/', Params::getParam('rewrite_page_url') . '/'), 0, -1); if (!osc_validate_text($page_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $page_url), array('s_name' => 'rewrite_page_url')); } $cat_url = substr(str_replace('//', '/', Params::getParam('rewrite_cat_url') . '/'), 0, -1); if (!osc_validate_text($cat_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $cat_url), array('s_name' => 'rewrite_cat_url')); } $search_url = substr(str_replace('//', '/', Params::getParam('rewrite_search_url') . '/'), 0, -1); if (!osc_validate_text($search_url)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $search_url), array('s_name' => 'rewrite_search_url')); } if (!osc_validate_text(Params::getParam('rewrite_search_country'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_country')), array('s_name' => 'rewrite_search_country')); } if (!osc_validate_text(Params::getParam('rewrite_search_region'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_region')), array('s_name' => 'rewrite_search_region')); } if (!osc_validate_text(Params::getParam('rewrite_search_city'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_city')), array('s_name' => 'rewrite_search_city')); } if (!osc_validate_text(Params::getParam('rewrite_search_city_area'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_city_area')), array('s_name' => 'rewrite_search_city_area')); } if (!osc_validate_text(Params::getParam('rewrite_search_category'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_category')), array('s_name' => 'rewrite_search_category')); } if (!osc_validate_text(Params::getParam('rewrite_search_user'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_user')), array('s_name' => 'rewrite_search_user')); } if (!osc_validate_text(Params::getParam('rewrite_search_pattern'))) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => Params::getParam('rewrite_search_pattern')), array('s_name' => 'rewrite_search_pattern')); } $rewrite_contact = substr(str_replace('//', '/', Params::getParam('rewrite_contact') . '/'), 0, -1); if (!osc_validate_text($rewrite_contact)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_contact), array('s_name' => 'rewrite_contact')); } $rewrite_feed = substr(str_replace('//', '/', Params::getParam('rewrite_feed') . '/'), 0, -1); if (!osc_validate_text($rewrite_feed)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_feed), array('s_name' => 'rewrite_feed')); } $rewrite_language = substr(str_replace('//', '/', Params::getParam('rewrite_language') . '/'), 0, -1); if (!osc_validate_text($rewrite_language)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_language), array('s_name' => 'rewrite_language')); } $rewrite_item_mark = substr(str_replace('//', '/', Params::getParam('rewrite_item_mark') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_mark)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_mark), array('s_name' => 'rewrite_item_mark')); } $rewrite_item_send_friend = substr(str_replace('//', '/', Params::getParam('rewrite_item_send_friend') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_send_friend)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_send_friend), array('s_name' => 'rewrite_item_send_friend')); } $rewrite_item_contact = substr(str_replace('//', '/', Params::getParam('rewrite_item_contact') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_contact)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_contact), array('s_name' => 'rewrite_item_contact')); } $rewrite_item_new = substr(str_replace('//', '/', Params::getParam('rewrite_item_new') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_new)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_new), array('s_name' => 'rewrite_item_new')); } $rewrite_item_activate = substr(str_replace('//', '/', Params::getParam('rewrite_item_activate') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_activate)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_activate), array('s_name' => 'rewrite_item_activate')); } $rewrite_item_edit = substr(str_replace('//', '/', Params::getParam('rewrite_item_edit') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_edit)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_edit), array('s_name' => 'rewrite_item_edit')); } $rewrite_item_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_delete') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_delete)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_delete), array('s_name' => 'rewrite_item_delete')); } $rewrite_item_resource_delete = substr(str_replace('//', '/', Params::getParam('rewrite_item_resource_delete') . '/'), 0, -1); if (!osc_validate_text($rewrite_item_resource_delete)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_item_resource_delete), array('s_name' => 'rewrite_item_resource_delete')); } $rewrite_user_login = substr(str_replace('//', '/', Params::getParam('rewrite_user_login') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_login)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_login), array('s_name' => 'rewrite_user_login')); } $rewrite_user_dashboard = substr(str_replace('//', '/', Params::getParam('rewrite_user_dashboard') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_dashboard)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_dashboard), array('s_name' => 'rewrite_user_dashboard')); } $rewrite_user_logout = substr(str_replace('//', '/', Params::getParam('rewrite_user_logout') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_logout)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_logout), array('s_name' => 'rewrite_user_logout')); } $rewrite_user_register = substr(str_replace('//', '/', Params::getParam('rewrite_user_register') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_register)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_register), array('s_name' => 'rewrite_user_register')); } $rewrite_user_activate = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_activate)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_activate), array('s_name' => 'rewrite_user_activate')); } $rewrite_user_activate_alert = substr(str_replace('//', '/', Params::getParam('rewrite_user_activate_alert') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_activate_alert)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_activate_alert), array('s_name' => 'rewrite_user_activate_alert')); } $rewrite_user_profile = substr(str_replace('//', '/', Params::getParam('rewrite_user_profile') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_profile)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_profile), array('s_name' => 'rewrite_user_profile')); } $rewrite_user_items = substr(str_replace('//', '/', Params::getParam('rewrite_user_items') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_items)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_items), array('s_name' => 'rewrite_user_items')); } $rewrite_user_alerts = substr(str_replace('//', '/', Params::getParam('rewrite_user_alerts') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_alerts)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_alerts), array('s_name' => 'rewrite_user_alerts')); } $rewrite_user_recover = substr(str_replace('//', '/', Params::getParam('rewrite_user_recover') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_recover)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_recover), array('s_name' => 'rewrite_user_recover')); } $rewrite_user_forgot = substr(str_replace('//', '/', Params::getParam('rewrite_user_forgot') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_forgot)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_forgot), array('s_name' => 'rewrite_user_forgot')); } $rewrite_user_change_password = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_password') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_password)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_password), array('s_name' => 'rewrite_user_change_password')); } $rewrite_user_change_email = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_email)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_email), array('s_name' => 'rewrite_user_change_email')); } $rewrite_user_change_username = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_username') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_username)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_username), array('s_name' => 'rewrite_user_change_username')); } $rewrite_user_change_email_confirm = substr(str_replace('//', '/', Params::getParam('rewrite_user_change_email_confirm') . '/'), 0, -1); if (!osc_validate_text($rewrite_user_change_email_confirm)) { $errors += 1; } else { Preference::newInstance()->update(array('s_value' => $rewrite_user_change_email_confirm), array('s_name' => 'rewrite_user_change_email_confirm')); } osc_reset_preferences(); $rewrite = Rewrite::newInstance(); osc_run_hook("before_rewrite_rules", array(&$rewrite)); $rewrite->clearRules(); /***************************** ********* Add rules ********* *****************************/ // Contact rules $rewrite->addRule('^' . osc_get_preference('rewrite_contact') . '/?$', 'index.php?page=contact'); // Feed rules $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/?$', 'index.php?page=search&sFeed=rss'); $rewrite->addRule('^' . osc_get_preference('rewrite_feed') . '/(.+)/?$', 'index.php?page=search&sFeed=$1'); // Language rules $rewrite->addRule('^' . osc_get_preference('rewrite_language') . '/(.*?)/?$', 'index.php?page=language&locale=$1'); // Search rules $rewrite->addRule('^' . $search_url . '$', 'index.php?page=search'); $rewrite->addRule('^' . $search_url . '/(.*)$', 'index.php?page=search&sParams=$1'); // Item rules $rewrite->addRule('^' . osc_get_preference('rewrite_item_mark') . '/(.*?)/([0-9]+)/?$', 'index.php?page=item&action=mark&as=$1&id=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_send_friend') . '/([0-9]+)/?$', 'index.php?page=item&action=send_friend&id=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_contact') . '/([0-9]+)/?$', 'index.php?page=item&action=contact&id=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/?$', 'index.php?page=item&action=item_add'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_new') . '/([0-9]+)/?$', 'index.php?page=item&action=item_add&catId=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=activate&id=$1&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_edit') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_edit&id=$1&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_delete') . '/([0-9]+)/(.*?)/?$', 'index.php?page=item&action=item_delete&id=$1&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_item_resource_delete') . '/([0-9]+)/([0-9]+)/([0-9A-Za-z]+)/?(.*?)/?$', 'index.php?page=item&action=deleteResource&id=$1&item=$2&code=$3&secret=$4'); // Item rules $id_pos = stripos($item_url, '{ITEM_ID}'); $title_pos = stripos($item_url, '{ITEM_TITLE}'); $cat_pos = stripos($item_url, '{CATEGORIES'); $param_pos = 1; if ($title_pos !== false && $id_pos > $title_pos) { $param_pos++; } if ($cat_pos !== false && $id_pos > $cat_pos) { $param_pos++; } $comments_pos = 1; if ($id_pos !== false) { $comments_pos++; } if ($title_pos !== false) { $comments_pos++; } if ($cat_pos !== false) { $comments_pos++; } $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$3&lang=$1_$2&comments-page=$4'); $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url . '\\?comments-page=([0-9al]*)')))) . '$', 'index.php?page=item&id=$1&comments-page=$2'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$3&lang=$1_$2'); $rewrite->addRule('^' . str_replace('{ITEM_CITY}', '.*', str_replace('{CATEGORIES}', '.*', str_replace('{ITEM_TITLE}', '.*', str_replace('{ITEM_ID}', '([0-9]+)', $item_url)))) . '$', 'index.php?page=item&id=$1'); // User rules $rewrite->addRule('^' . osc_get_preference('rewrite_user_login') . '/?$', 'index.php?page=login'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_dashboard') . '/?$', 'index.php?page=user&action=dashboard'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_logout') . '/?$', 'index.php?page=main&action=logout'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_register') . '/?$', 'index.php?page=register&action=register'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate') . '/([0-9]+)/(.*?)/?$', 'index.php?page=register&action=validate&id=$1&code=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_activate_alert') . '/([0-9]+)/([a-zA-Z0-9]+)/(.+)$', 'index.php?page=user&action=activate_alert&id=$1&email=$3&secret=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/?$', 'index.php?page=user&action=profile'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/([0-9]+)/?$', 'index.php?page=user&action=pub_profile&id=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_profile') . '/(.+)/?$', 'index.php?page=user&action=pub_profile&username=$1'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_items') . '/?$', 'index.php?page=user&action=items'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_alerts') . '/?$', 'index.php?page=user&action=alerts'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_recover') . '/?$', 'index.php?page=login&action=recover'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_forgot') . '/([0-9]+)/(.*)/?$', 'index.php?page=login&action=forgot&userId=$1&code=$2'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_password') . '/?$', 'index.php?page=user&action=change_password'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email') . '/?$', 'index.php?page=user&action=change_email'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_username') . '/?$', 'index.php?page=user&action=change_username'); $rewrite->addRule('^' . osc_get_preference('rewrite_user_change_email_confirm') . '/([0-9]+)/(.*?)/?$', 'index.php?page=user&action=change_email_confirm&userId=$1&code=$2'); // Page rules $pos_pID = stripos($page_url, '{PAGE_ID}'); $pos_pSlug = stripos($page_url, '{PAGE_SLUG}'); $pID_pos = 1; $pSlug_pos = 1; if (is_numeric($pos_pID) && is_numeric($pos_pSlug)) { // set the order of the parameters if ($pos_pID > $pos_pSlug) { $pID_pos++; } else { $pSlug_pos++; } $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&id=$' . $pID_pos . "&slug=\$" . $pSlug_pos); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', str_replace('{PAGE_ID}', '([0-9]+)', $page_url)) . '/?$', 'index.php?page=page&lang=$1_$2&id=$' . ($pID_pos + 2) . '&slug=$' . ($pSlug_pos + 2)); } else { if (is_numeric($pos_pID)) { $rewrite->addRule('^' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&id=$1'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_ID}', '([0-9]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&id=$3'); } else { $rewrite->addRule('^' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&slug=$1'); $rewrite->addRule('^([a-z]{2})_([A-Z]{2})/' . str_replace('{PAGE_SLUG}', '([\\p{L}\\p{N}_\\-,]+)', $page_url) . '/?$', 'index.php?page=page&lang=$1_$2&slug=$3'); } } // Clean archive files $rewrite->addRule('^(.+?)\\.php(.*)$', '$1.php$2'); // Category rules $id_pos = stripos($item_url, '{CATEGORY_ID}'); $title_pos = stripos($item_url, '{CATEGORY_SLUG}'); $cat_pos = stripos($item_url, '{CATEGORIES'); $param_pos = 1; if ($title_pos !== false && $id_pos > $title_pos) { $param_pos++; } if ($cat_pos !== false && $id_pos > $cat_pos) { $param_pos++; } $rewrite->addRule('^' . str_replace('{CATEGORIES}', '(.+)', str_replace('{CATEGORY_SLUG}', '([^/]+)', str_replace('{CATEGORY_ID}', '([0-9]+)', $cat_url))) . '/([0-9]+)$', 'index.php?page=search&sCategory=$' . $param_pos . '&iPage=$' . ($param_pos + 1)); $rewrite->addRule('^' . str_replace('{CATEGORIES}', '(.+)', str_replace('{CATEGORY_SLUG}', '([^/]+)', str_replace('{CATEGORY_ID}', '([0-9]+)', $cat_url))) . '$', 'index.php?page=search&sCategory=$' . $param_pos); osc_run_hook("after_rewrite_rules", array(&$rewrite)); //Write rule to DB $rewrite->setRules(); $msg_error = '<br/>' . _m('All fields are required.') . " " . sprintf(_mn('One field was not updated', '%s fields were not updated', $errors), $errors); switch ($status) { case 1: $msg = _m("Permalinks structure updated"); if ($errors > 0) { $msg .= $msg_error; osc_add_flash_warning_message($msg, 'admin'); } else { osc_add_flash_ok_message($msg, 'admin'); } break; case 2: $msg = _m("Permalinks structure updated."); $msg .= " "; $msg .= _m("However, we can't check if Apache module <b>mod_rewrite</b> is loaded. If you experience some problems with the URLs, you should deactivate <em>Friendly URLs</em>"); if ($errors > 0) { $msg .= $msg_error; } osc_add_flash_warning_message($msg, 'admin'); break; case 3: $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content."); $msg .= " "; $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file, please deactivate the <em>Friendly URLs</em> option."); $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>'; if ($errors > 0) { $msg .= $msg_error; } osc_add_flash_error_message($msg, 'admin'); break; case 4: $msg = _m("File <b>.htaccess</b> couldn't be filled out with the right content."); $msg .= " "; $msg .= _m("Here's the content you have to add to the <b>.htaccess</b> file. If you can't create the file or experience some problems with the URLs, please deactivate the <em>Friendly URLs</em> option."); $msg .= "</p><pre>" . htmlentities($htaccess, ENT_COMPAT, "UTF-8") . '</pre><p>'; if ($errors > 0) { $msg .= $msg_error; } osc_add_flash_error_message($msg, 'admin'); break; } } else { Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'rewriteEnabled')); Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded')); osc_add_flash_ok_message(_m('Friendly URLs successfully deactivated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=permalinks'); break; case 'spamNbots': // calling the spam and bots view $akismet_key = osc_akismet_key(); $akismet_status = 3; if ($akismet_key != '') { require_once osc_lib_path() . 'Akismet.class.php'; $akismet_obj = new Akismet(osc_base_url(), $akismet_key); $akismet_status = 2; if ($akismet_obj->isKeyValid()) { $akismet_status = 1; } } View::newInstance()->_exportVariableToView('akismet_status', $akismet_status); $this->doView('settings/spamNbots.php'); break; case 'akismet_post': // updating spam and bots option osc_csrf_check(); $updated = 0; $akismetKey = Params::getParam('akismetKey'); $akismetKey = trim($akismetKey); $updated = Preference::newInstance()->update(array('s_value' => $akismetKey), array('s_name' => 'akismetKey')); if ($akismetKey == '') { osc_add_flash_info_message(_m('Your Akismet key has been cleared'), 'admin'); } else { osc_add_flash_ok_message(_m('Your Akismet key has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots'); break; case 'recaptcha_post': // updating spam and bots option osc_csrf_check(); $iUpdated = 0; $recaptchaPrivKey = Params::getParam('recaptchaPrivKey'); $recaptchaPrivKey = trim($recaptchaPrivKey); $recaptchaPubKey = Params::getParam('recaptchaPubKey'); $recaptchaPubKey = trim($recaptchaPubKey); $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPrivKey), array('s_name' => 'recaptchaPrivKey')); $iUpdated += Preference::newInstance()->update(array('s_value' => $recaptchaPubKey), array('s_name' => 'recaptchaPubKey')); if ($recaptchaPubKey == '') { osc_add_flash_info_message(_m('Your reCAPTCHA key has been cleared'), 'admin'); } else { osc_add_flash_ok_message(_m('Your reCAPTCHA key has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=spamNbots'); break; case 'currencies': // currencies settings $currencies_action = Params::getParam('type'); switch ($currencies_action) { case 'add': // calling add currency view $aCurrency = array('pk_c_code' => '', 's_name' => '', 's_description' => ''); $this->_exportVariableToView('aCurrency', $aCurrency); $this->_exportVariableToView('typeForm', 'add_post'); $this->doView('settings/currency_form.php'); break; case 'add_post': // adding a new currency osc_csrf_check(); $currencyCode = Params::getParam('pk_c_code'); $currencyName = Params::getParam('s_name'); $currencyDescription = Params::getParam('s_description'); // cleaning parameters $currencyName = strip_tags($currencyName); $currencyDescription = strip_tags($currencyDescription); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if (!preg_match('/^.{1,3}$/', $currencyCode)) { osc_add_flash_error_message(_m('The currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $fields = array('pk_c_code' => $currencyCode, 's_name' => $currencyName, 's_description' => $currencyDescription); $isInserted = Currency::newInstance()->insert($fields); if ($isInserted) { osc_add_flash_ok_message(_m('Currency added'), 'admin'); } else { osc_add_flash_error_message(_m("Currency couldn't be added"), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; case 'edit': // calling edit currency view $currencyCode = Params::getParam('code'); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if ($currencyCode == '') { osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $aCurrency = Currency::newInstance()->findByPrimaryKey($currencyCode); if (!$aCurrency) { osc_add_flash_warning_message(sprintf(_m("The currency code '%s' doesn't exist"), $currencyCode), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $this->_exportVariableToView('aCurrency', $aCurrency); $this->_exportVariableToView('typeForm', 'edit_post'); $this->doView('settings/currency_form.php'); break; case 'edit_post': // updating currency osc_csrf_check(); $currencyName = Params::getParam('s_name'); $currencyDescription = Params::getParam('s_description'); $currencyCode = Params::getParam('pk_c_code'); // cleaning parameters $currencyName = strip_tags($currencyName); $currencyDescription = strip_tags($currencyDescription); $currencyCode = strip_tags($currencyCode); $currencyCode = trim($currencyCode); if (!preg_match('/.{1,3}/', $currencyCode)) { osc_add_flash_error_message(_m('Error: the currency code is not in the correct format'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); } $updated = Currency::newInstance()->update(array('s_name' => $currencyName, 's_description' => $currencyDescription), array('pk_c_code' => $currencyCode)); if ($updated == 1) { osc_add_flash_ok_message(_m('Currency updated'), 'admin'); } else { osc_add_flash_info_message(_m('No changes were made'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; case 'delete': // deleting a currency osc_csrf_check(); $rowChanged = 0; $aCurrencyCode = Params::getParam('code'); if (!is_array($aCurrencyCode)) { $aCurrencyCode = array($aCurrencyCode); } $msg_current = ''; foreach ($aCurrencyCode as $currencyCode) { if (preg_match('/.{1,3}/', $currencyCode) && $currencyCode != osc_currency()) { $rowChanged += Currency::newInstance()->delete(array('pk_c_code' => $currencyCode)); } // foreign key error if (Currency::newInstance()->getErrorLevel() == '1451') { $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it has listings associated to it"), $currencyCode); } else { if ($currencyCode == osc_currency()) { $msg_current .= sprintf('</p><p>' . _m("%s couldn't be deleted because it's the default currency"), $currencyCode); } } } $msg = ''; $status = ''; switch ($rowChanged) { case '0': $msg = _m('No currencies have been deleted'); $status = 'error'; break; case '1': $msg = _m('One currency has been deleted'); $status = 'ok'; break; default: $msg = sprintf(_m('%s currencies have been deleted'), $rowChanged); $status = 'ok'; break; } if ($status == 'ok' && $msg_current != '') { $status = 'warning'; } switch ($status) { case 'error': osc_add_flash_error_message($msg . $msg_current, 'admin'); break; case 'warning': osc_add_flash_warning_message($msg . $msg_current, 'admin'); break; case 'ok': osc_add_flash_ok_message($msg, 'admin'); break; } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies'); break; default: // calling the currencies view $aCurrencies = Currency::newInstance()->listAll(); $this->_exportVariableToView('aCurrencies', $aCurrencies); $this->doView('settings/currencies.php'); break; } break; case 'mailserver': // calling the mailserver view $this->doView('settings/mailserver.php'); break; case 'mailserver_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); } osc_csrf_check(); // updating mailserver $iUpdated = 0; $mailserverAuth = Params::getParam('mailserver_auth'); $mailserverAuth = $mailserverAuth != '' ? true : false; $mailserverPop = Params::getParam('mailserver_pop'); $mailserverPop = $mailserverPop != '' ? true : false; $mailserverType = Params::getParam('mailserver_type'); $mailserverHost = Params::getParam('mailserver_host'); $mailserverPort = Params::getParam('mailserver_port'); $mailserverUsername = Params::getParam('mailserver_username'); $mailserverPassword = Params::getParam('mailserver_password'); $mailserverSsl = Params::getParam('mailserver_ssl'); if (!in_array($mailserverType, array('custom', 'gmail'))) { osc_add_flash_error_message(_m('Mail server type is incorrect'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverAuth), array('s_name' => 'mailserver_auth')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPop), array('s_name' => 'mailserver_pop')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverType), array('s_name' => 'mailserver_type')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverHost), array('s_name' => 'mailserver_host')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPort), array('s_name' => 'mailserver_port')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverUsername), array('s_name' => 'mailserver_username')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverPassword), array('s_name' => 'mailserver_password')); $iUpdated += Preference::newInstance()->update(array('s_value' => $mailserverSsl), array('s_name' => 'mailserver_ssl')); if ($iUpdated > 0) { osc_add_flash_ok_message(_m('Mail server configuration has changed'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=mailserver'); break; case 'media': // calling the media view $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $memory_limit = (int) ini_get('memory_limit'); $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024; $this->_exportVariableToView('max_size_upload', $upload_mb); $this->doView('settings/media.php'); break; case 'media_post': // updating the media config osc_csrf_check(); $status = 'ok'; $error = ''; $iUpdated = 0; $maxSizeKb = Params::getParam('maxSizeKb'); $dimThumbnail = Params::getParam('dimThumbnail'); $dimPreview = Params::getParam('dimPreview'); $dimNormal = Params::getParam('dimNormal'); $keepOriginalImage = Params::getParam('keep_original_image'); $use_imagick = Params::getParam('use_imagick'); $type_watermark = Params::getParam('watermark_type'); $watermark_color = Params::getParam('watermark_text_color'); $watermark_text = Params::getParam('watermark_text'); switch ($type_watermark) { case 'none': $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); break; case 'text': $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_color), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => $watermark_text), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_image')); $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_text_place')), array('s_name' => 'watermark_place')); break; case 'image': // upload image & move to path if ($_FILES['watermark_image']['error'] == UPLOAD_ERR_OK) { if ($_FILES['watermark_image']['type'] == 'image/png') { $tmpName = $_FILES['watermark_image']['tmp_name']; $path = osc_content_path() . 'uploads/watermark.png'; if (move_uploaded_file($tmpName, $path)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $path), array('s_name' => 'watermark_image')); } else { $error .= _m('There was a problem uploading the watermark image') . "<br />"; } } else { $error .= _m('The watermark image has to be a .PNG file') . "<br />"; } } else { $error .= _m('There was a problem uploading the watermark image') . "<br />"; } $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text_color')); $iUpdated += Preference::newInstance()->update(array('s_value' => ''), array('s_name' => 'watermark_text')); $iUpdated += Preference::newInstance()->update(array('s_value' => Params::getParam('watermark_image_place')), array('s_name' => 'watermark_place')); break; default: break; } // format parameters $maxSizeKb = strip_tags($maxSizeKb); $dimThumbnail = strip_tags($dimThumbnail); $dimPreview = strip_tags($dimPreview); $dimNormal = strip_tags($dimNormal); $keepOriginalImage = $keepOriginalImage != '' ? true : false; $use_imagick = $use_imagick != '' ? true : false; // is imagick extension loaded? if (!@extension_loaded('imagick')) { $use_imagick = false; } // max size allowed by PHP configuration? $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $memory_limit = (int) ini_get('memory_limit'); $upload_mb = min($max_upload, $max_post, $memory_limit) * 1024; // set maxSizeKB equals to PHP configuration if it's bigger if ($maxSizeKb > $upload_mb) { $status = 'warning'; $maxSizeKb = $upload_mb; // flash message text warning $error .= sprintf(_m("You cannot set a maximum file size higher than the one allowed in the PHP configuration: <b>%d KB</b>"), $upload_mb); } $iUpdated += Preference::newInstance()->update(array('s_value' => $maxSizeKb), array('s_name' => 'maxSizeKb')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimThumbnail), array('s_name' => 'dimThumbnail')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimPreview), array('s_name' => 'dimPreview')); $iUpdated += Preference::newInstance()->update(array('s_value' => $dimNormal), array('s_name' => 'dimNormal')); $iUpdated += Preference::newInstance()->update(array('s_value' => $keepOriginalImage), array('s_name' => 'keep_original_image')); $iUpdated += Preference::newInstance()->update(array('s_value' => $use_imagick), array('s_name' => 'use_imagick')); if ($error != '') { switch ($status) { case 'error': osc_add_flash_error_message($error, 'admin'); break; case 'warning': osc_add_flash_warning_message($error, 'admin'); break; default: osc_add_flash_ok_message($error, 'admin'); break; } } else { osc_add_flash_ok_message(_m('Media config has been updated'), 'admin'); } $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; case 'images_post': if (defined('DEMO')) { osc_add_flash_warning_message(_m("This action can't be done because it's a demo site"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); } osc_csrf_check(); $wat = new Watermark(); $aResources = ItemResource::newInstance()->getAllResources(); foreach ($aResources as $resource) { osc_run_hook('regenerate_image', $resource); $path = osc_content_path() . 'uploads/'; // comprobar que no haya original $img_original = $path . $resource['pk_i_id'] . "_original*"; $aImages = glob($img_original); // there is original image if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_normal = $path . $resource['pk_i_id'] . ".*"; $aImages = glob($img_normal); if (count($aImages) == 1) { $image_tmp = $aImages[0]; } else { $img_thumbnail = $path . $resource['pk_i_id'] . "_thumbnail*"; $aImages = glob($img_thumbnail); $image_tmp = $aImages[0]; } } // extension preg_match('/\\.(.*)$/', $image_tmp, $matches); if (isset($matches[1])) { $extension = $matches[1]; // Create normal size $path_normal = $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '.jpg'; $size = explode('x', osc_normal_dimensions()); ImageResizer::fromFile($image_tmp)->resizeTo($size[0], $size[1])->saveToFile($path); if (osc_is_watermark_text()) { $wat->doWatermarkText($path, osc_watermark_text_color(), osc_watermark_text(), 'image/jpeg'); } elseif (osc_is_watermark_image()) { $wat->doWatermarkImage($path, 'image/jpeg'); } // Create preview $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_preview.jpg'; $size = explode('x', osc_preview_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // Create thumbnail $path = osc_content_path() . 'uploads/' . $resource['pk_i_id'] . '_thumbnail.jpg'; $size = explode('x', osc_thumbnail_dimensions()); ImageResizer::fromFile($path_normal)->resizeTo($size[0], $size[1])->saveToFile($path); // update resource info ItemResource::newInstance()->update(array('s_path' => 'oc-content/uploads/', 's_name' => osc_genRandomPassword(), 's_extension' => 'jpg', 's_content_type' => 'image/jpeg'), array('pk_i_id' => $resource['pk_i_id'])); osc_run_hook('regenerated_image', ItemResource::newInstance()->findByPrimaryKey($resource['pk_i_id'])); // si extension es direfente a jpg, eliminar las imagenes con $extension si hay if ($extension != 'jpg') { @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "." . $extension); @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_original." . $extension); @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_preview." . $extension); @unlink(osc_content_path() . 'uploads/' . $resource['pk_i_id'] . "_thumbnail." . $extension); } // .... } else { // no es imagen o imagen sin extesión } } osc_add_flash_ok_message(_m('Re-generation complete'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media'); break; case 'update': // update index view osc_csrf_check(); $iUpdated = 0; $sPageTitle = Params::getParam('pageTitle'); $sPageDesc = Params::getParam('pageDesc'); $sContactEmail = Params::getParam('contactEmail'); $sLanguage = Params::getParam('language'); $sDateFormat = Params::getParam('dateFormat'); $sCurrency = Params::getParam('currency'); $sWeekStart = Params::getParam('weekStart'); $sTimeFormat = Params::getParam('timeFormat'); $sTimezone = Params::getParam('timezone'); $sNumRssItems = Params::getParam('num_rss_items'); $maxLatestItems = Params::getParam('max_latest_items_at_home'); $numItemsSearch = Params::getParam('default_results_per_page'); $contactAttachment = Params::getParam('enabled_attachment'); $selectableParent = Params::getParam('selectable_parent_categories'); $bAutoCron = Params::getParam('auto_cron'); $bMarketSources = Params::getParam('market_external_sources') == 1 ? 1 : 0; // preparing parameters $sPageTitle = strip_tags($sPageTitle); $sPageDesc = strip_tags($sPageDesc); $sContactEmail = strip_tags($sContactEmail); $sLanguage = strip_tags($sLanguage); $sDateFormat = strip_tags($sDateFormat); $sCurrency = strip_tags($sCurrency); $sWeekStart = strip_tags($sWeekStart); $sTimeFormat = strip_tags($sTimeFormat); $sNumRssItems = (int) strip_tags($sNumRssItems); $maxLatestItems = (int) strip_tags($maxLatestItems); $numItemsSearch = (int) $numItemsSearch; $contactAttachment = $contactAttachment != '' ? true : false; $bAutoCron = $bAutoCron != '' ? true : false; $error = ""; $msg = ''; if (!osc_validate_text($sPageTitle)) { $msg .= _m("Page title field is required") . "<br/>"; } if (!osc_validate_text($sContactEmail)) { $msg .= _m("Contact email field is required") . "<br/>"; } if (!osc_validate_int($sNumRssItems)) { $msg .= _m("Number of listings in the RSS has to be a numeric value") . "<br/>"; } if (!osc_validate_int($maxLatestItems)) { $msg .= _m("Max latest listings has to be a numeric value") . "<br/>"; } if (!osc_validate_int($numItemsSearch)) { $msg .= _m("Number of listings on search has to be a numeric value") . "<br/>"; } if ($msg != '') { osc_add_flash_error_message($msg, 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageTitle), array('s_section' => 'osclass', 's_name' => 'pageTitle')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sPageDesc), array('s_section' => 'osclass', 's_name' => 'pageDesc')); if (!defined('DEMO')) { $iUpdated += Preference::newInstance()->update(array('s_value' => $sContactEmail), array('s_section' => 'osclass', 's_name' => 'contactEmail')); } $iUpdated += Preference::newInstance()->update(array('s_value' => $sLanguage), array('s_section' => 'osclass', 's_name' => 'language')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sDateFormat), array('s_section' => 'osclass', 's_name' => 'dateFormat')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sCurrency), array('s_section' => 'osclass', 's_name' => 'currency')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sWeekStart), array('s_section' => 'osclass', 's_name' => 'weekStart')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimeFormat), array('s_section' => 'osclass', 's_name' => 'timeFormat')); $iUpdated += Preference::newInstance()->update(array('s_value' => $sTimezone), array('s_section' => 'osclass', 's_name' => 'timezone')); $iUpdated += Preference::newInstance()->update(array('s_value' => $bMarketSources), array('s_section' => 'osclass', 's_name' => 'marketAllowExternalSources')); if (is_int($sNumRssItems)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $sNumRssItems), array('s_section' => 'osclass', 's_name' => 'num_rss_items')); } else { if ($error != '') { $error .= "</p><p>"; } $error .= _m('Number of listings in the RSS must be an integer'); } if (is_int($maxLatestItems)) { $iUpdated += Preference::newInstance()->update(array('s_value' => $maxLatestItems), array('s_section' => 'osclass', 's_name' => 'maxLatestItems@home')); } else { if ($error != '') { $error .= "</p><p>"; } $error .= _m('Number of recent listings displayed at home must be an integer'); } $iUpdated += Preference::newInstance()->update(array('s_value' => $numItemsSearch), array('s_section' => 'osclass', 's_name' => 'defaultResultsPerPage@search')); $iUpdated += Preference::newInstance()->update(array('s_value' => $contactAttachment), array('s_name' => 'contact_attachment')); $iUpdated += Preference::newInstance()->update(array('s_value' => $bAutoCron), array('s_name' => 'auto_cron')); $iUpdated += Preference::newInstance()->update(array('s_value' => $selectableParent), array('s_name' => 'selectable_parent_categories')); if ($iUpdated > 0) { if ($error != '') { osc_add_flash_error_message($error . "</p><p>" . _m('General settings have been updated'), 'admin'); } else { osc_add_flash_ok_message(_m('General settings have been updated'), 'admin'); } } else { if ($error != '') { osc_add_flash_error_message($error, 'admin'); } } $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); break; case 'check_updates': osc_admin_toolbar_update_themes(true); osc_admin_toolbar_update_plugins(true); osc_add_flash_ok_message(_m('Last check') . ': ' . date("Y-m-d H:i"), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings'); break; case 'latestsearches': //calling the comments settings view $this->doView('settings/searches.php'); break; case 'latestsearches_post': // updating comment osc_csrf_check(); if (Params::getParam('save_latest_searches') == 'on') { Preference::newInstance()->update(array('s_value' => 1), array('s_name' => 'save_latest_searches')); } else { Preference::newInstance()->update(array('s_value' => 0), array('s_name' => 'save_latest_searches')); } if (Params::getParam('customPurge') == '') { osc_add_flash_error_message(_m('Custom number could not be left empty'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches'); } else { Preference::newInstance()->update(array('s_value' => Params::getParam('customPurge')), array('s_name' => 'purge_latest_searches')); osc_add_flash_ok_message(_m('Last search settings have been updated'), 'admin'); $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=latestsearches'); } break; default: // calling the view $aLanguages = OSCLocale::newInstance()->listAllEnabled(); $aCurrencies = Currency::newInstance()->listAll(); $this->_exportVariableToView('aLanguages', $aLanguages); $this->_exportVariableToView('aCurrencies', $aCurrencies); $this->doView('settings/index.php'); break; } }
function _need_update($uri, $version, $operator = '>') { if (false === ($json = @osc_file_get_contents($uri))) { return false; } else { $data = json_decode($json, true); if (isset($data['s_version'])) { $result = version_compare2($data['s_version'], $version); if ($result == -1) { return true; } } } }