Пример #1
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add_post_default':
             // add default category and reorder parent categories
             $fields['fk_i_parent_id'] = NULL;
             $fields['i_expiration_days'] = 0;
             $fields['i_position'] = 0;
             $fields['b_enabled'] = 1;
             $default_locale = osc_language();
             $aFieldsDescription[$default_locale]['s_name'] = "NEW CATEGORY, EDIT ME!";
             $categoryId = $this->categoryManager->insert($fields, $aFieldsDescription);
             // reorder parent categories. NEW category first
             $rootCategories = $this->categoryManager->findRootCategories();
             foreach ($rootCategories as $cat) {
                 $order = $cat['i_position'];
                 $order++;
                 $this->categoryManager->updateOrder($cat['pk_i_id'], $order);
             }
             $this->categoryManager->updateOrder($categoryId, '0');
             $this->redirectTo(osc_admin_base_url(true) . '?page=categories');
             break;
         default:
             //
             $this->_exportVariableToView("categories", $this->categoryManager->toTreeAll());
             $this->doView("categories/index.php");
     }
 }
Пример #2
0
 /**
  * Install plugin moreedit
  */
 public function install()
 {
     $array = array('s_internal_name' => 'email_moreedit_notify_edit', 'b_indelible' => 1, 'dt_pub_date' => date('Y-m-d H:i:s'));
     $this->dao->insert(DB_TABLE_PREFIX . 't_pages', $array);
     $id = $this->dao->insertedId();
     $array_description = array('fk_i_pages_id' => $id, 'fk_c_locale_code' => osc_language(), 's_title' => '{WEB_TITLE} - Notification of ad: {ITEM_TITLE}', 's_text' => '<p>Hi Admin!</p>\\r\\n<p> </p>\\r\\n<p>We just published an item ({ITEM_TITLE}) on {WEB_TITLE} from user {USER_NAME} ( {ITEM_URL} ).</p>\\r\\n<p>Edit it here : {EDIT_LINK}</p>\\r\\n<p> </p>\\r\\n<p>Thanks</p>');
     $this->dao->insert(DB_TABLE_PREFIX . 't_pages_description', $array_description);
 }
Пример #3
0
 function doModel()
 {
     parent::doModel();
     //specific things for this class
     switch ($this->action) {
         case 'add_post_default':
             // add default category and reorder parent categories
             $fields['fk_i_parent_id'] = NULL;
             $fields['i_expiration_days'] = 0;
             $fields['i_position'] = 0;
             $fields['b_enabled'] = 1;
             $default_locale = osc_language();
             $aFieldsDescription[$default_locale]['s_name'] = "NEW CATEGORY, EDIT ME!";
             $categoryId = $this->categoryManager->insert($fields, $aFieldsDescription);
             // reorder parent categories. NEW category first
             $rootCategories = $this->categoryManager->findRootCategories();
             foreach ($rootCategories as $cat) {
                 $order = $cat['i_position'];
                 $order++;
                 $this->categoryManager->updateOrder($cat['pk_i_id'], $order);
             }
             $this->categoryManager->updateOrder($categoryId, '0');
             $this->redirectTo(osc_admin_base_url(true) . '?page=categories');
             break;
         case 'settings':
             // calling the categories settings view
             $this->doView('categories/settings.php');
             break;
         case 'settings_post':
             // updating categories option
             $selectableParent = Params::getParam('selectable_parent_categories');
             $updated = Preference::newInstance()->update(array('s_value' => $selectableParent), array('s_name' => 'selectable_parent_categories'));
             if ($updated > 0) {
                 osc_add_flash_ok_message(_m("Categories' settings have been updated"), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=categories&action=settings');
             break;
         default:
             //
             $this->_exportVariableToView("categories", $this->categoryManager->toTreeAll());
             $this->doView("categories/index.php");
     }
 }
Пример #4
0
function adManage_install()
{
    $conn = getConnection();
    $path = osc_plugin_resource('advanced_ad_management/struct.sql');
    $sql = file_get_contents($path);
    $conn->osc_dbImportSQL($sql);
    osc_set_preference('adManageed_expire', '4', 'plugin-item_adManage', 'INTEGER');
    osc_set_preference('adManageed_payperpost', '1', 'plugin-item_adManage', 'INTEGER');
    osc_set_preference('adManageed_repubTimes', '5', 'plugin-item_adManage', 'INTEGER');
    osc_set_preference('adManageed_installed', '0', 'plugin-item_adManage', 'INTEGER');
    osc_set_preference('adManageed_freeRepubs', '0', 'plugin-item_adManage', 'INTEGER');
    osc_set_preference('adManageed_expireEmail', '1', 'plugin-item_adManage', 'INTEGER');
    osc_set_preference('adManageed_deleteDays', '0', 'plugin-item_adManage', 'INTEGER');
    //used for email template
    $conn->osc_dbExec("INSERT IGNORE INTO %st_pages (s_internal_name, b_indelible, dt_pub_date) VALUES ('email_ad_expire', 1, NOW() )", DB_TABLE_PREFIX);
    $conn->osc_dbExec("INSERT IGNORE INTO %st_pages_description (fk_i_pages_id, fk_c_locale_code, s_title, s_text) VALUES (%d, '%s', '{WEB_TITLE} - Your ad {ITEM_TITLE} is about to expire.', '<p>Hi {CONTACT_NAME}!</p>\r\n<p> </p>\r\n<p>Your ad is about to expire, click on the link if you would like to extend your ad {REPUBLISH_URL}</p><p> </p>\r\n<p>This is an automatic email, Please do not respond to this email.</p>\r\n<p> </p>\r\n<p>Thanks</p>\r\n<p>{WEB_TITLE}</p>')", DB_TABLE_PREFIX, $conn->get_last_id(), osc_language());
    $conn->osc_dbExec("INSERT IGNORE INTO %st_pages (s_internal_name, b_indelible, dt_pub_date) VALUES ('email_ad_expired', 1, NOW() )", DB_TABLE_PREFIX);
    $conn->osc_dbExec("INSERT IGNORE INTO %st_pages_description (fk_i_pages_id, fk_c_locale_code, s_title, s_text) VALUES (%d, '%s', '{WEB_TITLE} - Your ad {ITEM_TITLE} has expired.', '<p>Hi {CONTACT_NAME}!</p>\r\n<p> </p>\r\n<p>Your ad has expired. You may renew your ad by clicking on the link {REPUBLISH_URL}. Otherwise your ad will be permanently deleted in {PERM_DELETED} days</p><p> </p>\r\n<p>This is an automatic email, Please do not respond to this email.</p>\r\n<p> </p>\r\n<p>Thanks</p>\r\n<p>{WEB_TITLE}</p>')", DB_TABLE_PREFIX, $conn->get_last_id(), osc_language());
}
Пример #5
0
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
$locales = __get('locales');
$last = end($locales);
$last_id = $last['pk_c_code'];
$default_lang = osc_language();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
    <head>
        <?php 
osc_current_admin_theme_path('head.php');
?>
    </head>
    <body>
        <?php 
osc_current_admin_theme_path('header.php');
?>
        <div id="update_version" style="display:none;"></div>
        <script type="text/javascript">
            $(function() {
Пример #6
0
 function doModel()
 {
     switch ($this->action) {
         case 'items':
             // calling the items settings view
             $this->doView('settings/items.php');
             break;
         case 'items_post':
             // update item settings
             $iUpdated = 0;
             $enabledRecaptchaItems = Params::getParam('enabled_recaptcha_items');
             $enabledRecaptchaItems = $enabledRecaptchaItems != '' ? true : false;
             $enabledItemValidation = Params::getParam('enabled_item_validation');
             $enabledItemValidation = $enabledItemValidation != '' ? true : false;
             $loggedUserItemValidation = Params::getParam('logged_user_item_validation');
             $loggedUserItemValidation = $loggedUserItemValidation != '' ? true : false;
             $regUserPost = Params::getParam('reg_user_post');
             $regUserPost = $regUserPost != '' ? true : false;
             $notifyNewItem = Params::getParam('notify_new_item');
             $notifyNewItem = $notifyNewItem != '' ? true : false;
             $notifyContactItem = Params::getParam('notify_contact_item');
             $notifyContactItem = $notifyContactItem != '' ? true : false;
             $notifyContactFriends = Params::getParam('notify_contact_friends');
             $notifyContactFriends = $notifyContactFriends != '' ? true : false;
             $enabledFieldPriceItems = Params::getParam('enableField#f_price@items');
             $enabledFieldPriceItems = $enabledFieldPriceItems != '' ? true : false;
             $enabledFieldImagesItems = Params::getParam('enableField#images@items');
             $enabledFieldImagesItems = $enabledFieldImagesItems != '' ? true : false;
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledRecaptchaItems), array('s_name' => 'enabled_recaptcha_items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledItemValidation), array('s_name' => 'enabled_item_validation'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $loggedUserItemValidation), array('s_name' => 'logged_user_item_validation'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $regUserPost), array('s_name' => 'reg_user_post'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyNewItem), array('s_name' => 'notify_new_item'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyContactItem), array('s_name' => 'notify_contact_item'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $notifyContactFriends), array('s_name' => 'notify_contact_friends'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledFieldPriceItems), array('s_name' => 'enableField#f_price@items'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledFieldImagesItems), array('s_name' => 'enableField#images@items'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('Items\' settings have been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=items');
             break;
         case 'comments':
             //calling the comments settings view
             $this->doView('settings/comments.php');
             break;
         case 'comments_post':
             // updating comment
             $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');
             $notifyNewComment = Params::getParam('notify_new_comment');
             $notifyNewComment = $notifyNewComment != '' ? true : false;
             $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'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('Comments\' settings have been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=comments');
             break;
         case 'users':
             // calling the users settings view
             $this->doView('settings/users.php');
             break;
         case 'users_post':
             // updating users
             $iUpdated = 0;
             $enabledUserValidation = Params::getParam('enabled_user_validation');
             $enabledUserValidation = $enabledUserValidation != '' ? true : false;
             $enabledUserRegistration = Params::getParam('enabled_user_registration');
             $enabledUserRegistration = $enabledUserRegistration != '' ? true : false;
             $enabledUsers = Params::getParam('enabled_users');
             $enabledUsers = $enabledUsers != '' ? true : false;
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledUserValidation), array('s_name' => 'enabled_user_validation'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledUserRegistration), array('s_name' => 'enabled_user_registration'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $enabledUsers), array('s_name' => 'enabled_users'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('Users\' settings have been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=users');
             break;
         case 'locations':
             // calling the locations settings view
             $location_action = Params::getParam('type');
             $mCountries = new Country();
             switch ($location_action) {
                 case 'add_country':
                     // add country
                     if (!Params::getParam('c_manual')) {
                         $this->install_location_by_country();
                     } else {
                         $countryCode = Params::getParam('c_country');
                         $countryName = Params::getParam('country');
                         $countryLanguage = osc_language();
                         $exists = $mCountries->findByCode($countryCode);
                         if (!isset($exists['s_name'])) {
                             $data = array('pk_c_code' => $countryCode, 'fk_c_locale_code' => $countryLanguage, 's_name' => $countryName);
                             $mCountries->insert($data);
                             osc_add_flash_message(sprintf(__('%s has been added as a new country'), $countryName), 'admin');
                         } else {
                             osc_add_flash_message(sprintf(__('%s already was in the database'), $countryName), 'admin');
                         }
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'edit_country':
                     // edit country
                     $newCountry = Params::getParam('e_country');
                     $oldCountry = Params::getParam('country_old');
                     $exists = $mCountries->findByName($newCountry);
                     $old_exists = $mCountries->findByName($oldCountry);
                     if (!isset($exists['pk_c_code']) || $exists['pk_c_code'] == $old_exists['pk_c_code']) {
                         $mCountries->update(array('s_name' => $newCountry), array('s_name' => $oldCountry));
                         osc_add_flash_message(sprintf(__('%s has been edited'), $newCountry), 'admin');
                     } else {
                         osc_add_flash_message(sprintf(__('%s already was in the database'), $newCountry), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'delete_country':
                     // delete country
                     $countryId = Params::getParam('id');
                     // HAS ITEMS?
                     $has_items = Item::newInstance()->listWhere('l.fk_c_country_code = \'%s\' LIMIT 1', $countryId);
                     if (!$has_items) {
                         $mRegions = new Region();
                         $mCities = new City();
                         $aCountries = $mCountries->findByCode($countryId);
                         $aRegions = $mRegions->listWhere('fk_c_country_code =  \'' . $aCountries['pk_c_code'] . '\'');
                         foreach ($aRegions as $region) {
                             $mCities->delete(array('fk_i_region_id' => $region['pk_i_id']));
                             $mRegions->delete(array('pk_i_id' => $region['pk_i_id']));
                         }
                         $mCountries->delete(array('pk_c_code' => $aCountries['pk_c_code']));
                         osc_add_flash_message(sprintf(__('%s has been deleted'), $aCountries['s_name']), 'admin');
                     } else {
                         osc_add_flash_message(sprintf(__('%s can not be deleted, some items are located in it'), $aCountries['s_name']), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'add_region':
                     // add region
                     if (!Params::getParam('r_manual')) {
                         $this->install_location_by_region();
                     } else {
                         $mRegions = new Region();
                         $regionName = Params::getParam('region');
                         $countryCode = Params::getParam('country_c_parent');
                         $exists = $mRegions->findByNameAndCode($regionName, $countryCode);
                         if (!isset($exists['s_name'])) {
                             $data = array('fk_c_country_code' => $countryCode, 's_name' => $regionName);
                             $mRegions->insert($data);
                             osc_add_flash_message(sprintf(__('%s has been added as a new region'), $regionName), 'admin');
                         } else {
                             osc_add_flash_message(sprintf(__('%s already was in the database'), $regionName), 'admin');
                         }
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'edit_region':
                     // edit region
                     $mRegions = new Region();
                     $newRegion = Params::getParam('e_region');
                     $regionId = Params::getParam('region_id');
                     $exists = $mRegions->findByName($newRegion);
                     if (!$exists['pk_i_id'] || $exists['pk_i_id'] == $regionId) {
                         if ($regionId != '') {
                             $mRegions->update(array('s_name' => $newRegion), array('pk_i_id' => $regionId));
                             osc_add_flash_message(sprintf(__('%s has been edited'), $newRegion), 'admin');
                         }
                     } else {
                         osc_add_flash_message(sprintf(__('%s already was in the database'), $newRegion), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'delete_region':
                     // delete region
                     $mRegion = new Region();
                     $mCities = new City();
                     $regionId = Params::getParam('id');
                     if ($regionId != '') {
                         $aRegion = $mRegion->findByPrimaryKey($regionId);
                         $mCities->delete(array('fk_i_region_id' => $regionId));
                         $mRegion->delete(array('pk_i_id' => $regionId));
                         osc_add_flash_message(sprintf(__('%s has been deleted'), $aRegion['s_name']), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'add_city':
                     // add city
                     $mCities = new City();
                     $regionId = Params::getParam('region_parent');
                     $countryCode = Params::getParam('country_c_parent');
                     $newCity = Params::getParam('city');
                     $exists = $mCities->findByNameAndRegion($newCity, $regionId);
                     if (!isset($exists['s_name'])) {
                         $mCities->insert(array('fk_i_region_id' => $regionId, 's_name' => $newCity, 'fk_c_country_code' => $countryCode));
                         osc_add_flash_message(sprintf(__('%s has been added as a new city'), $newCity), 'admin');
                     } else {
                         osc_add_flash_message(sprintf(__('%s already was in the database'), $newCity), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'edit_city':
                     // edit city
                     $mCities = new City();
                     $newCity = Params::getParam('e_city');
                     $cityId = Params::getParam('city_id');
                     $exists = $mCities->findByName($newCity);
                     if (!isset($exists['pk_i_id']) || $exists['pk_i_id'] == $cityId) {
                         $mCities->update(array('s_name' => $newCity), array('pk_i_id' => $cityId));
                         osc_add_flash_message(sprintf(__('%s has been edited'), $newCity), 'admin');
                     } else {
                         osc_add_flash_message(sprintf(__('%s already was in the database'), $newCity), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     break;
                 case 'delete_city':
                     // delete city
                     $mCities = new City();
                     $cityId = Params::getParam('id');
                     $aCity = $mCities->findByPrimaryKey($cityId);
                     $mCities->delete(array('pk_i_id' => $cityId));
                     osc_add_flash_message(sprintf(__('%s has been deleted'), $aCity['s_name']), 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=locations');
                     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
             $htaccess_status = 0;
             $file_status = 0;
             $rewriteEnabled = Params::getParam('rewrite_enabled');
             $rewriteEnabled = $rewriteEnabled ? true : false;
             if ($rewriteEnabled) {
                 Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'rewriteEnabled'));
                 require_once ABS_PATH . 'generate_rules.php';
                 $htaccess = '
 <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteBase ' . REL_WEB_URL . '
     RewriteRule ^index\\.php$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . ' . REL_WEB_URL . 'index.php [L]
 </IfModule>';
                 if (file_exists(osc_base_path() . '.htaccess')) {
                     $file_status = 1;
                 } else {
                     if (file_put_contents(osc_base_path() . '.htaccess', $htaccess)) {
                         $file_status = 2;
                     } else {
                         $file_status = 3;
                     }
                 }
                 if (apache_mod_loaded('mod_rewrite')) {
                     $htaccess_status = 1;
                     Preference::newInstance()->update(array('s_value' => '1'), array('s_name' => 'mod_rewrite_loaded'));
                 } else {
                     $htaccess_status = 2;
                     Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded'));
                 }
             } else {
                 $modRewrite = apache_mod_loaded('mod_rewrite');
                 Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'rewriteEnabled'));
                 Preference::newInstance()->update(array('s_value' => '0'), array('s_name' => 'mod_rewrite_loaded'));
             }
             $redirectUrl = osc_admin_base_url(true) . '?page=settings&action=permalinks&htaccess_status=';
             $redirectUrl .= $htaccess_status . '&file_status=' . $file_status;
             $this->redirectTo($redirectUrl);
             break;
         case 'spamNbots':
             // calling the spam and bots view
             $this->doView('settings/spamNbots.php');
             break;
         case 'spamNbots_post':
             // updating spam and bots option
             $iUpdated = 0;
             $akismetKey = Params::getParam('akismetKey');
             $akismetKey = trim($akismetKey);
             $recaptchaPrivKey = Params::getParam('recaptchaPrivKey');
             $recaptchaPrivKey = trim($recaptchaPrivKey);
             $recaptchaPubKey = Params::getParam('recaptchaPubKey');
             $recaptchaPubKey = trim($recaptchaPubKey);
             $iUpdated += Preference::newInstance()->update(array('s_value' => $akismetKey), array('s_name' => 'akismetKey'));
             $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 ($iUpdated > 0) {
                 osc_add_flash_message(_m('Akismet and reCAPTCHA have 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
                     $this->doView('settings/add_currency.php');
                     break;
                 case 'add_post':
                     // adding a new currency
                     $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_message(_m('Error: 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_message(_m('New currency has been added'), 'admin');
                     } else {
                         osc_add_flash_message(_m('Error: 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_message(_m('Error: the currency code is not in the correct format'), 'admin');
                         $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                     }
                     $aCurrency = Currency::newInstance()->findByCode($currencyCode);
                     if (count($aCurrency) == 0) {
                         osc_add_flash_message(_m('Error: the currency doesn\'t exist'), 'admin');
                         $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                     }
                     $this->_exportVariableToView('aCurrency', $aCurrency);
                     $this->doView('settings/edit_currency.php');
                     break;
                 case 'edit_post':
                     // updating currency
                     $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_message(_m('Error: the currency code is not in the correct format'), 'admin');
                         $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                     }
                     $iUpdated = Currency::newInstance()->update(array('s_name' => $currencyName, 's_description' => $currencyDescription), array('pk_c_code' => $currencyCode));
                     if ($iUpdated == 1) {
                         osc_add_flash_message(_m('Currency has been updated'), 'admin');
                     }
                     $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                     break;
                 case 'delete':
                     // deleting a currency
                     $rowChanged = 0;
                     $aCurrencyCode = Params::getParam('code');
                     if (!is_array($aCurrencyCode)) {
                         osc_add_flash_message(_m('Error: the currency code is not in the correct format'), 'admin');
                         $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=currencies');
                     }
                     foreach ($aCurrencyCode as $currencyCode) {
                         if (preg_match('/.{1,3}/', $currencyCode) && $currencyCode != osc_currency()) {
                             $rowChanged += Currency::newInstance()->delete(array('pk_c_code' => $currencyCode));
                         }
                     }
                     $msg = '';
                     switch ($rowChanged) {
                         case '0':
                             $msg = __('No currencies have been deleted');
                             break;
                         case '1':
                             $msg = __('One currency has been deleted');
                             break;
                         default:
                             $msg = sprintf(__('%s currencies have been deleted'), $rowChanged);
                             break;
                     }
                     osc_add_flash_message($msg, 'admin');
                     $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':
             // updating mailserver
             $iUpdated = 0;
             $mailserverAuth = Params::getParam('mailserver_auth');
             $mailserverAuth = $mailserverAuth != '' ? 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_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' => $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_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
             $this->doView('settings/media.php');
             break;
         case 'media_post':
             // updating the media config
             $iUpdated = 0;
             $maxSizeKb = Params::getParam('maxSizeKb');
             $allowedExt = Params::getParam('allowedExt');
             $dimThumbnail = Params::getParam('dimThumbnail');
             $dimPreview = Params::getParam('dimPreview');
             $dimNormal = Params::getParam('dimNormal');
             $keepOriginalImage = Params::getParam('keep_original_image');
             // format parameters
             $maxSizeKb = strip_tags($maxSizeKb);
             $allowedExt = strip_tags($allowedExt);
             $dimThumbnail = strip_tags($dimThumbnail);
             $dimPreview = strip_tags($dimPreview);
             $dimNormal = strip_tags($dimNormal);
             $keepOriginalImage = $keepOriginalImage != '' ? true : false;
             $iUpdated += Preference::newInstance()->update(array('s_value' => $maxSizeKb), array('s_name' => 'maxSizeKb'));
             $iUpdated += Preference::newInstance()->update(array('s_value' => $allowedExt), array('s_name' => 'allowedExt'));
             $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'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('Media config has been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=media');
             break;
         case 'contact':
             // calling the media view
             $this->doView('settings/contact.php');
             break;
         case 'contact_post':
             // updating the media config
             $enabled_attachment = Params::getParam('enabled_attachment');
             if ($enabled_attachment == '') {
                 $enabled_attachment = 0;
             } else {
                 $enabled_attachment = 1;
             }
             // format parameters
             $iUpdated = Preference::newInstance()->update(array('s_value' => $enabled_attachment), array('s_name' => 'contact_attachment'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('Contact configuration has been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=contact');
             break;
         case 'cron':
             // viewing the cron view
             $this->doView('settings/cron.php');
             break;
         case 'cron_post':
             // updating cron config
             $iUpdated = 0;
             $bAutoCron = Params::getParam('auto_cron');
             $bAutoCron = $bAutoCron != '' ? true : false;
             $iUpdated += Preference::newInstance()->update(array('s_value' => $bAutoCron), array('s_name' => 'auto_cron'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('Cron config has been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings&action=cron');
             break;
         case 'update':
             // update index view
             $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');
             $sNumRssItems = Params::getParam('num_rss_items');
             // 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 = strip_tags($sNumRssItems);
             $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'));
             $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' => $sNumRssItems), array('s_section' => 'osclass', 's_name' => 'num_rss_items'));
             if ($iUpdated > 0) {
                 osc_add_flash_message(_m('General settings have been updated'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=settings');
             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;
     }
 }
Пример #7
0
 public function install()
 {
     $this->import('payment/struct.sql');
     osc_set_preference('version', '200', 'payment', 'INTEGER');
     osc_set_preference('default_premium_cost', '1.0', 'payment', 'STRING');
     osc_set_preference('allow_premium', '0', 'payment', 'BOOLEAN');
     osc_set_preference('default_publish_cost', '1.0', 'payment', 'STRING');
     osc_set_preference('pay_per_post', '0', 'payment', 'BOOLEAN');
     osc_set_preference('premium_days', '7', 'payment', 'INTEGER');
     osc_set_preference('currency', 'USD', 'payment', 'STRING');
     osc_set_preference('pack_price_1', '', 'payment', 'STRING');
     osc_set_preference('pack_price_2', '', 'payment', 'STRING');
     osc_set_preference('pack_price_3', '', 'payment', 'STRING');
     osc_set_preference('paypal_api_username', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('paypal_api_password', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('paypal_api_signature', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('paypal_email', '', 'payment', 'STRING');
     osc_set_preference('paypal_standard', '1', 'payment', 'BOOLEAN');
     osc_set_preference('paypal_sandbox', '1', 'payment', 'BOOLEAN');
     osc_set_preference('paypal_enabled', '0', 'payment', 'BOOLEAN');
     osc_set_preference('blockchain_btc_address', '', 'payment', 'STRING');
     osc_set_preference('blockchain_enabled', '0', 'payment', 'BOOLEAN');
     osc_set_preference('braintree_merchant_id', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('braintree_public_key', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('braintree_private_key', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('braintree_encryption_key', payment_crypt(''), 'payment', 'STRING');
     osc_set_preference('braintree_sandbox', 'sandbox', 'payment', 'STRING');
     osc_set_preference('braintree_enabled', '0', 'payment', 'BOOLEAN');
     $this->dao->select('pk_i_id');
     $this->dao->from(DB_TABLE_PREFIX . 't_item');
     $result = $this->dao->get();
     if ($result) {
         $items = $result->result();
         $date = date("Y-m-d H:i:s");
         foreach ($items as $item) {
             $this->createItem($item['pk_i_id'], 1, $date);
         }
     }
     $description[osc_language()]['s_title'] = '{WEB_TITLE} - Publish option for your ad: {ITEM_TITLE}';
     $description[osc_language()]['s_text'] = '<p>Hi {CONTACT_NAME}!</p><p>We just published your item ({ITEM_TITLE}) on {WEB_TITLE}.</p><p>{START_PUBLISH_FEE}</p><p>In order to make your ad available to anyone on {WEB_TITLE}, you should complete the process and pay the publish fee. You could do that on the following link: {PUBLISH_LINK}</p><p>{END_PUBLISH_FEE}</p><p>{START_PREMIUM_FEE}</p><p>You could make your ad premium and make it to appear on top result of the searches made on {WEB_TITLE}. You could do that on the following link: {PREMIUM_LINK}</p><p>{END_PREMIUM_FEE}</p><p>This is an automatic email, if you already did that, please ignore this email.</p><p>Thanks</p>';
     $res = Page::newInstance()->insert(array('s_internal_name' => 'email_payment', 'b_indelible' => '1'), $description);
 }
Пример #8
0
 public function add_comment()
 {
     $aItem = $this->prepareDataForFunction('add_comment');
     $authorName = trim($aItem['authorName']);
     $authorName = strip_tags($authorName);
     $authorEmail = trim($aItem['authorEmail']);
     $authorEmail = strip_tags($authorEmail);
     $body = trim($aItem['body']);
     $body = strip_tags($body);
     $title = $aItem['title'];
     $itemId = $aItem['id'];
     $userId = $aItem['userId'];
     $status_num = -1;
     $item = $this->manager->findByPrimaryKey($itemId);
     $itemURL = osc_item_url();
     Params::setParam('itemURL', $itemURL);
     if ($authorName == '' || !preg_match('|^.*?@.{2,}\\..{2,3}$|', $authorEmail)) {
         return 3;
     }
     if ($body == '') {
         return 4;
     }
     $num_moderate_comments = osc_moderate_comments();
     if ($userId == null) {
         $num_comments = 0;
     } else {
         $num_comments = count(ItemComment::newInstance()->findByAuthorID($userId));
     }
     if ($num_moderate_comments == -1 || $num_moderate_comments != 0 && $num_comments >= $num_moderate_comments) {
         $status = 'ACTIVE';
         $status_num = 2;
     } else {
         $status = 'INACTIVE';
         $status_num = 1;
     }
     if (osc_akismet_key()) {
         require_once LIB_PATH . 'Akismet.class.php';
         $akismet = new Akismet(osc_base_url(), osc_akismet_key());
         $akismet->setCommentAuthor($authorName);
         $akismet->setCommentAuthorEmail($authorEmail);
         $akismet->setCommentContent($body);
         $akismet->setPermalink($itemURL);
         $status = $akismet->isCommentSpam() ? 'SPAM' : $status;
         if ($status == 'SPAM') {
             $status_num = 5;
         }
     }
     $mComments = ItemComment::newInstance();
     $aComment = array('dt_pub_date' => DB_FUNC_NOW, 'fk_i_item_id' => $itemId, 's_author_name' => $authorName, 's_author_email' => $authorEmail, 's_title' => $title, 's_body' => $body, 'e_status' => $status, 'fk_i_user_id' => $userId);
     if ($mComments->insert($aComment)) {
         $notify = osc_notify_new_comment();
         $admin_email = osc_contact_email();
         $prefLocale = osc_language();
         //Notify admin
         if ($notify) {
             $mPages = new Page();
             $aPage = $mPages->findByInternalName('email_new_comment_admin');
             $locale = osc_current_user_locale();
             $content = array();
             if (isset($aPage['locale'][$locale]['s_title'])) {
                 $content = $aPage['locale'][$locale];
             } else {
                 $content = current($aPage['locale']);
             }
             $words = array();
             $words[] = array('{COMMENT_AUTHOR}', '{COMMENT_EMAIL}', '{COMMENT_TITLE}', '{COMMENT_TEXT}', '{ITEM_TITLE}', '{ITEM_ID}', '{ITEM_URL}');
             $words[] = array($authorName, $authorEmail, $title, $body, $item['s_title'], $itemId, $itemURL);
             $title_email = osc_mailBeauty($content['s_title'], $words);
             $body_email = osc_mailBeauty($content['s_text'], $words);
             $from = osc_contact_email();
             $from_name = osc_page_title();
             if (osc_notify_contact_item()) {
                 $add_bbc = osc_contact_email();
             }
             $emailParams = array('from' => $admin_email, 'from_name' => __('Admin mail system'), 'subject' => $title_email, 'to' => $admin_email, 'to_name' => __('Admin mail system'), 'body' => $body_email, 'alt_body' => $body_email);
             osc_sendMail($emailParams);
         }
         osc_run_hook('add_comment', $item);
         return $status_num;
     }
     return -1;
 }
Пример #9
0
/**
 * Get the actual locale of the user.
 *
 * You get the right locale code. If an user is using the website in another language different of the default one, or
 * the user uses the default one, you'll get it.
 *
 * @return string Locale Code
 */
function osc_current_user_locale()
{
    if (Session::newInstance()->_get('userLocale') != '') {
        return Session::newInstance()->_get('userLocale');
    }
    return osc_language();
}
Пример #10
0
 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();
 }
Пример #11
0
     convertAlert($hourly);
 }
 unset($aAlerts);
 $aAlerts = Alerts::newInstance()->findByType('DAILY');
 foreach ($aAlerts as $daily) {
     convertAlert($daily);
 }
 unset($aAlerts);
 $aAlerts = Alerts::newInstance()->findByType('WEEKLY');
 foreach ($aAlerts as $weekly) {
     convertAlert($weekly);
 }
 unset($aAlerts);
 // UPDATE COUNTRY PROCESS (remove fk_c_locale)
 $comm->query("CREATE TABLE " . DB_TABLE_PREFIX . "t_country_aux (\n    pk_c_code CHAR(2) NOT NULL,\n    s_name VARCHAR(80) NOT NULL,\n\n        PRIMARY KEY (pk_c_code),\n        INDEX idx_s_name (s_name)\n) ENGINE=InnoDB DEFAULT CHARACTER SET 'UTF8' COLLATE 'UTF8_GENERAL_CI';");
 $rs = $comm->query("SELECT * FROM " . DB_TABLE_PREFIX . "t_country WHERE fk_c_locale_code = '" . osc_language() . "'");
 $countries = $rs->result();
 foreach ($countries as $c) {
     $comm->insert(DB_TABLE_PREFIX . "t_country_aux", array('pk_c_code' => $c['pk_c_code'], 's_name' => $c['s_name']));
 }
 $rs = $comm->query("SHOW CREATE TABLE " . DB_TABLE_PREFIX . "t_city");
 $rs = $rs->result();
 foreach ($rs[0] as $r) {
     if (preg_match_all('|CONSTRAINT `([^`]+)` FOREIGN KEY \\(`fk_c_country_code`\\) REFERENCES `' . DB_TABLE_PREFIX . 't_country` \\(`pk_c_code`\\)|', $r, $matches)) {
         foreach ($matches[1] as $m) {
             $comm->query("ALTER TABLE  `" . DB_TABLE_PREFIX . "t_city` DROP FOREIGN KEY  `" . $m . "`");
         }
     }
 }
 $rs = $comm->query("SHOW CREATE TABLE " . DB_TABLE_PREFIX . "t_region");
 $rs = $rs->result();
 public function install()
 {
     $confPath = PAYMENT_PRO_PATH . 'payments/';
     $dir = opendir($confPath);
     while ($file = readdir($dir)) {
         if (is_dir($confPath . $file) && $file != '.' && $file != '..') {
             if (file_exists($confPath . $file . '/load.php')) {
                 include_once $confPath . $file . '/load.php';
             }
         }
     }
     closedir($dir);
     unset($dir);
     $this->import(PAYMENT_PRO_PATH . 'struct.sql');
     osc_set_preference('version', '200', 'payment_pro', 'INTEGER');
     osc_set_preference('default_premium_cost', '1.0', 'payment_pro', 'STRING');
     osc_set_preference('allow_premium', '0', 'payment_pro', 'BOOLEAN');
     osc_set_preference('default_publish_cost', '1.0', 'payment_pro', 'STRING');
     osc_set_preference('pay_per_post', '0', 'payment_pro', 'BOOLEAN');
     osc_set_preference('premium_days', '7', 'payment_pro', 'INTEGER');
     osc_set_preference('currency', 'USD', 'payment_pro', 'STRING');
     osc_set_preference('pack_price_1', '', 'payment_pro', 'STRING');
     osc_set_preference('pack_price_2', '', 'payment_pro', 'STRING');
     osc_set_preference('pack_price_3', '', 'payment_pro', 'STRING');
     osc_set_preference('last_purge', time(), 'payment_pro', 'INTEGER');
     osc_run_hook('payment_pro_install');
     $limit = 20000;
     $this->dao->select('COUNT(*) as total');
     $this->dao->from(DB_TABLE_PREFIX . 't_item');
     $result = $this->dao->get();
     $total = $result->row();
     $total = (int) $total['total'];
     $steps = ceil($total / $limit);
     for ($step = 0; $step < $steps; $step++) {
         $this->dao->select('pk_i_id, b_enabled');
         $this->dao->from(DB_TABLE_PREFIX . 't_item');
         $this->dao->orderBy('pk_i_id', 'ASC');
         $this->dao->limit($limit, $limit * $step);
         $result = $this->dao->get();
         $query = 'INSERT INTO ' . $this->getTable_publish() . ' (fk_i_item_id, b_paid, b_enabled, dt_date) VALUES ';
         if ($result) {
             $items = $result->result();
             $date = date("Y-m-d H:i:s");
             $values = array();
             $k = 0;
             foreach ($items as $key => $item) {
                 $values[] = '(' . $item['pk_i_id'] . ', 1, ' . $item['b_enabled'] . ', "' . $date . '")';
                 $k++;
                 if ($k >= 500) {
                     $this->dao->query($query . implode(",", $values) . ";");
                     $k = 0;
                     $values = array();
                 }
                 unset($items[$key]);
             }
             $this->dao->query($query . implode(",", $values) . ";");
         }
     }
     $description[osc_language()]['s_title'] = '{WEB_TITLE} - Publish option for your ad: {ITEM_TITLE}';
     $description[osc_language()]['s_text'] = '<p>Hi {CONTACT_NAME}!</p><p>We just published your item ({ITEM_TITLE}) on {WEB_TITLE}.</p><p>{START_PUBLISH_FEE}</p><p>In order to make your ad available to anyone on {WEB_TITLE}, you should complete the process and pay the publish fee. You could do that on the following link: {PUBLISH_LINK}</p><p>{END_PUBLISH_FEE}</p><p>{START_PREMIUM_FEE}</p><p>You could make your ad premium and make it to appear on top result of the searches made on {WEB_TITLE}. You could do that on the following link: {PREMIUM_LINK}</p><p>{END_PREMIUM_FEE}</p><p>This is an automatic email, if you already did that, please ignore this email.</p><p>Thanks</p>';
     $res = Page::newInstance()->insert(array('s_internal_name' => 'payment_pro_email_payment', 'b_indelible' => '1'), $description);
 }
Пример #13
0
 <div class="form-row">
     <div class="form-label"><?php _e('Page title'); ?></div>
     <div class="form-controls"><input type="text" class="xlarge" name="pageTitle" value="<?php echo osc_esc_html( osc_page_title() ); ?>" /></div>
 </div>
 <div class="form-row">
     <div class="form-label"><?php _e('Page description'); ?></div>
     <div class="form-controls"><input type="text" class="xlarge" name="pageDesc" value="<?php echo osc_esc_html( osc_page_description() ); ?>" /></div></div>
 <div class="form-row">
     <div class="form-label"><?php _e('Admin e-mail'); ?></div>
     <div class="form-controls"><input type="text" class="large" name="contactEmail" value="<?php echo osc_esc_html( osc_contact_email() ); ?>" /></div></div>
 <div class="form-row">
     <div class="form-label"><?php _e('Default language'); ?></div>
     <div class="form-controls">
         <select name="language">
         <?php foreach( $aLanguages as $lang ) { ?>
         <option value="<?php echo $lang['pk_c_code']; ?>" <?php echo ((osc_language() == $lang['pk_c_code']) ? 'selected="selected"' : ''); ?>><?php echo $lang['s_name']; ?></option>
         <?php } ?>
         </select>
     </div>
 </div>
 <div class="form-row">
     <div class="form-label"><?php _e('Default currency'); ?></div>
     <div class="form-controls">
         <select name="currency" id="currency_admin">
         <?php foreach($aCurrencies as $currency) { ?>
         <option value="<?php echo osc_esc_html($currency['pk_c_code']); ?>" <?php echo ((osc_currency() == $currency['pk_c_code']) ? 'selected="selected"' : ''); ?>><?php echo $currency['pk_c_code'] ?></option>
         <?php } ?>
         </select>
     </div>
 </div>
 <div class="form-row">
Пример #14
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->getByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->getByRegion(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 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 Alerts::newInstance()->insert(array('fk_i_user_id' => $userid, 's_email' => $email, 's_search' => $alert, 'e_type' => 'DAILY'));
                 echo "1";
                 return true;
             }
             echo '0';
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($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 items_processing_ajax(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 media_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'categories_order':
             // Save the order of the categories
             $aIds = Params::getParam('list');
             $orderParent = 0;
             $orderSub = 0;
             $catParent = 0;
             $catManager = Category::newInstance();
             foreach ($aIds as $id => $parent) {
                 if ($parent == 'root') {
                     if (!$catManager->update_order($id, $orderParent)) {
                         $error = 1;
                     }
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = DB_CONST_NULL;
                     if (!$catManager->update($array, $conditions) > 0) {
                         $error = 1;
                     }
                     $orderParent++;
                 } else {
                     if ($parent != $catParent) {
                         $catParent = $parent;
                         $orderSub = 0;
                     }
                     if (!$catManager->update_order($id, $orderSub)) {
                         $error = 1;
                     }
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = $catParent;
                     if (!$catManager->update($array, $conditions) > 0) {
                         $error = 1;
                     }
                     $orderSub++;
                 }
             }
             $result = "{";
             $error = 0;
             if ($error) {
                 $result .= '"error" : "' . __("Some error ocurred") . '"';
             } else {
                 $result .= '"ok" : "' . __("Order saved") . '"';
             }
             $result .= "}";
             echo $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;
             if (!$error) {
                 try {
                     $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")) {
                         Field::newInstance()->cleanCategoriesFromField(Params::getParam("id"));
                         $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("id");
                         $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug)));
                         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")));
                         Field::newInstance()->insertCategories(Params::getParam("id"), Params::getParam("categories"));
                     } else {
                         $error = 1;
                         $message = __("Sorry, you already have one field with that name");
                     }
                 } catch (Exception $e) {
                     $error = 1;
                     $message = __("Error while updating.");
                 }
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "' . __("Saved") . '", "text" : "' . Params::getParam("s_name") . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'delete_field':
             $id = Params::getParam("id");
             $error = 0;
             try {
                 $fieldManager = Field::newInstance();
                 $fieldManager->deleteByPrimaryKey($id);
                 $message = __('The custom field have been deleted');
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "Saved." ';
             }
             $result .= "}";
             echo $result;
             break;
         case 'enable_category':
             $id = Params::getParam("id");
             $enabled = Params::getParam("enabled") != '' ? Params::getParam("enabled") : 0;
             $error = 0;
             $aUpdated = "";
             try {
                 if ($id != '') {
                     $categoryManager = Category::newInstance();
                     $categoryManager->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
                     if ($enabled == 1) {
                         $msg = __('The category has been enabled');
                     } else {
                         $msg = __('The category has been disabled');
                     }
                     $categoryManager->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id));
                     $aUpdated = $categoryManager->listWhere("fk_i_parent_id = {$id}");
                     if ($enabled == 1) {
                         $msg .= "<br>" . __('The subcategories has been enabled');
                     } else {
                         $msg .= "<br>" . __('The subcategories has been disabled');
                     }
                 } else {
                     $error = 1;
                     $msg = __('There was a problem with this page. The ID for the category hasn\'t been set');
                 }
                 $message = $msg;
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error: %s') . " " . $e->getMessage();
             }
             $result = "{";
             $error = 0;
             if ($error) {
                 $result .= '"error" : "' . $message . '"';
             } else {
                 $result .= '"ok" : "' . $message . '"';
                 if (count($aUpdated) > 0) {
                     $result .= ', "afectedIds": [';
                     foreach ($aUpdated as $category) {
                         $result .= '{ "id" : "' . $category['pk_i_id'] . '" },';
                     }
                     $result = substr($result, 0, -1);
                     $result .= ']';
                 } else {
                     $result .= ', "afectedIds": []';
                 }
             }
             $result .= "}";
             echo $result;
             break;
         case 'delete_category':
             $id = Params::getParam("id");
             $error = 0;
             try {
                 $categoryManager = Category::newInstance();
                 $categoryManager->deleteByPrimaryKey($id);
                 $message = __('The categories have been deleted');
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "Saved." ';
             }
             $result .= "}";
             echo $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;
             $postParams = Params::getParamsAsArray();
             foreach ($postParams as $k => $v) {
                 if (preg_match('|(.+?)#(.+)|', $k, $m)) {
                     if ($m[2] == 's_name') {
                         if ($v != "") {
                             $aFieldsDescription[$m[1]][$m[2]] = $v;
                         } else {
                             $error = 1;
                             $message = __("All titles are required");
                         }
                     } else {
                         $aFieldsDescription[$m[1]][$m[2]] = $v;
                     }
                 }
             }
             $l = osc_language();
             if (!$error) {
                 try {
                     $categoryManager = Category::newInstance();
                     $categoryManager->updateByPrimaryKey($fields, $aFieldsDescription, $id);
                 } catch (Exception $e) {
                     $error = 1;
                     $message = __("Error while updating.");
                 }
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "' . __("Saved") . '", "text" : "' . $aFieldsDescription[$l]['s_name'] . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_admin_base_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
         case 'test_mail':
             $title = __('Test email') . ", " . 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");
             $count = osc_count_static_pages();
             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') {
                     if ($actual_order > 0) {
                         $new_order = $actual_order - 1;
                     }
                 } else {
                     if ($order == 'down') {
                         if ($actual_order != $count - 1) {
                             $new_order = $actual_order + 1;
                         }
                     }
                 }
                 if ($new_order != $actual_order) {
                     $auxpage = $mPages->findByOrder($new_order);
                     $array = array('i_order' => $actual_order);
                     $conditions = array('pk_i_id' => $auxpage['pk_i_id']);
                     $mPages->update($array, $conditions);
                     $array = array('i_order' => $new_order);
                     $conditions = array('pk_i_id' => $id);
                     $mPages->update($array, $conditions);
                 } else {
                 }
                 // json for datatables
                 $prefLocale = osc_current_admin_locale();
                 $aPages = $mPages->listAll(0);
                 $json = "[";
                 foreach ($aPages as $key => $page) {
                     $body = array();
                     if (isset($page['locale'][$prefLocale]) && !empty($page['locale'][$prefLocale]['s_title'])) {
                         $body = $page['locale'][$prefLocale];
                     } else {
                         $body = current($page['locale']);
                     }
                     $p_body = str_replace("'", "\\'", trim(strip_tags($body['s_title']), "\"'"));
                     $json .= "[\"<input type='checkbox' name='id[]' value='" . $page['pk_i_id'] . "' />\",";
                     $json .= "\"" . $page['s_internal_name'] . "<div id='datatables_quick_edit'>";
                     $json .= "<a href='" . osc_static_page_url() . "'>" . __('View page') . "</a> | ";
                     $json .= "<a href='" . osc_admin_base_url(true) . "?page=pages&action=edit&id=" . $page['pk_i_id'] . "'>";
                     $json .= __('Edit') . "</a>";
                     if (!$page['b_indelible']) {
                         $json .= " | ";
                         $json .= "<a onclick=\\\"javascript:return confirm('";
                         $json .= __('This action can\\\\\'t be undone. Are you sure you want to continue?') . "')\\\" ";
                         $json .= " href='" . osc_admin_base_url(true) . "?page=pages&action=delete&id=" . $page['pk_i_id'] . "'>";
                         $json .= __('Delete') . "</a>";
                     }
                     $json .= "</div>\",";
                     $json .= "\"" . $p_body . "\",";
                     $json .= "\"<img id='up' onclick='order_up(" . $page['pk_i_id'] . ");' style='cursor:pointer;width:15;height:15px;' src='" . osc_current_admin_theme_url('images/arrow_up.png') . "'/> <br/> <img id='down' onclick='order_down(" . $page['pk_i_id'] . ");' style='cursor:pointer;width:15;height:15px;' src='" . osc_current_admin_theme_url('images/arrow_down.png') . "'/>\"]";
                     if ($key != count($aPages) - 1) {
                         $json .= ',';
                     } else {
                         $json .= '';
                     }
                 }
                 $json .= "]";
                 echo $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;
             $remove_error_msg = "";
             $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 ****
              ***********************/
             if (Params::getParam('file') != '') {
                 $tmp = explode("/", Params::getParam('file'));
                 $filename = end($tmp);
                 $result = osc_downloadFile(Params::getParam('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
                                 /**********************
                                  **** REMOVE FILES ****
                                  **********************/
                                 if (file_exists(ABS_PATH . 'oc-temp/remove.list')) {
                                     $lines = file(ABS_PATH . 'oc-temp/remove.list', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                     foreach ($lines as $line_num => $r_file) {
                                         $unlink = @unlink(ABS_PATH . $r_file);
                                         if (!$unlink) {
                                             $remove_error_msg .= sprintf(__('Error removing file: %s'), $r_file) . "<br/>";
                                         }
                                     }
                                 }
                                 // Removing files is not important for the rest of the proccess
                                 // We will inform the user of the problems but the upgrade could 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 = getConnection();
                                     $error_queries = $conn->osc_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 ($remove_error_msg != '') {
                 if ($error == 0) {
                     $message .= "<br /><br />" . __('We had some errors removing files, those are not super-sensitive errors, so we continued upgrading your installation. Please remove the following files (you already have OSClass upgraded, but to ensure maximun performance)');
                 }
             }
             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;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Пример #15
0
function feed_get_job_data($item)
{
    $conn = getConnection();
    $detail = $conn->osc_dbFetchResult("SELECT * FROM %st_item_job_attr WHERE fk_i_item_id = %d", DB_TABLE_PREFIX, $item['pk_i_id']);
    if (count($detail) > 0) {
        foreach ($detail as $k => $v) {
            $item[$k] = $v;
        }
    }
    $detail = $conn->osc_dbFetchResult("SELECT * FROM %st_item_job_description_attr WHERE fk_i_item_id = %d AND fk_c_locale_code = '%s'", DB_TABLE_PREFIX, osc_item_id(), osc_language());
    if (count($detail) == 0) {
        $detail = $conn->osc_dbFetchResult("SELECT * FROM %st_item_job_description_attr WHERE fk_i_item_id = %d", DB_TABLE_PREFIX, osc_item_id());
    }
    if (count($detail) > 0) {
        foreach ($detail as $k => $v) {
            $item[$k] = $v;
        }
    }
    return $item;
}
Пример #16
0
 /**
  * Gets title from current item, if $locale is unspecified $locale is current user locale
  *
  * @param string $locale
  * @return string
  */
 function osc_item_title($locale = "") {
     if ($locale == "") $locale = osc_current_user_locale();
     $title = osc_item_field("s_title", $locale);
     if($title=='') {
         $title = osc_item_field("s_title", osc_language());
         if($title=='') {
             $aLocales = osc_get_locales();
             foreach($aLocales as $locale) {
                 $title = osc_item_field("s_title", @$locale['pk_c_code']);
                 if($title!='') {
                     break;
                 }
             }
         }
     }
     return (string) $title;
 }
Пример #17
0
" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <script type="text/javascript">
        var osc = window.osc || {};
<?php 
/* TODO: enqueue js lang strings */
$lang = array('nochange_expiration' => __('No change expiration'), 'without_expiration' => __('Without expiration'), 'expiration_day' => __('1 day'), 'expiration_days' => __('%d days'), 'select_category' => __('Select category'), 'no_subcategory' => __('No subcategory'), 'select_subcategory' => __('Select subcategory'));
$locales = osc_get_locales();
$codes = array();
foreach ($locales as $locale) {
    $codes[] = '\'' . osc_esc_js($locale['pk_c_code']) . '\'';
}
?>
        osc.locales = {};
        osc.locales._default = '<?php 
echo osc_language();
?>
';
        osc.locales.current = '<?php 
echo osc_current_admin_locale();
?>
';
        osc.locales.codes   = new Array(<?php 
echo join(',', $codes);
?>
);
        osc.locales.string  = '[name*="' + osc.locales.codes.join('"],[name*="') + '"],.' + osc.locales.codes.join(',.');
        osc.langs = <?php 
echo json_encode($lang);
?>
;
Пример #18
0
function fn_email_new_comment_admin($aItem)
{
    $authorName = trim($aItem['authorName']);
    $authorName = strip_tags($authorName);
    $authorEmail = trim($aItem['authorEmail']);
    $authorEmail = strip_tags($authorEmail);
    $body = trim($aItem['body']);
    $body = strip_tags($body);
    $title = $aItem['title'];
    $itemId = $aItem['id'];
    $userId = $aItem['userId'];
    $admin_email = osc_contact_email();
    $prefLocale = osc_language();
    $item = Item::newInstance()->findByPrimaryKey($itemId);
    View::newInstance()->_exportVariableToView('item', $item);
    $itemURL = osc_item_url();
    $itemURL = '<a href="' . $itemURL . '" >' . $itemURL . '</a>';
    $mPages = new Page();
    $aPage = $mPages->findByInternalName('email_new_comment_admin');
    $locale = osc_current_user_locale();
    $content = array();
    if (isset($aPage['locale'][$locale]['s_title'])) {
        $content = $aPage['locale'][$locale];
    } else {
        $content = current($aPage['locale']);
    }
    $words = array();
    $words[] = array('{COMMENT_AUTHOR}', '{COMMENT_EMAIL}', '{COMMENT_TITLE}', '{COMMENT_TEXT}', '{ITEM_TITLE}', '{ITEM_ID}', '{ITEM_URL}');
    $words[] = array($authorName, $authorEmail, $title, $body, $item['s_title'], $itemId, $itemURL);
    $title_email = osc_mailBeauty(osc_apply_filter('email_title', osc_apply_filter('email_new_comment_admin_title', $content['s_title'])), $words);
    $body_email = osc_mailBeauty(osc_apply_filter('email_description', osc_apply_filter('email_new_comment_admin_description', $content['s_text'])), $words);
    $from = osc_contact_email();
    $from_name = osc_page_title();
    if (osc_notify_contact_item()) {
        $add_bbc = osc_contact_email();
    }
    $emailParams = array('from' => $admin_email, 'from_name' => __('Admin mail system'), 'subject' => $title_email, 'to' => $admin_email, 'to_name' => __('Admin mail system'), 'body' => $body_email, 'alt_body' => $body_email);
    osc_sendMail($emailParams);
}
Пример #19
0
    function fn_alert_email_instant($user, $ads, $s_search) {
        $prefLocale = osc_language();
        $page = Page::newInstance()->findByInternalName('alert_email_instant');
        $page_description = $page['locale'];

        $_title = osc_apply_filter('email_title', osc_apply_filter('alert_email_instant_title', $page_description[$prefLocale]['s_title'], $user, $ads, $s_search));
        $_body  = osc_apply_filter('email_description', osc_apply_filter('alert_email_instant_description', $page_description[$prefLocale]['s_text'], $user, $ads, $s_search));

        if( $user['fk_i_user_id'] != 0 ) {
            $user = User::newInstance()->findByPrimaryKey($user['fk_i_user_id']);
        } else {
            $user['s_name'] = $user['s_email'];
        }

        $unsub_link = osc_user_unsubscribe_alert_url($s_search['pk_i_id'], $user['s_email'], $s_search['s_secret']);
        $unsub_link = '<a href="' . $unsub_link . '">' . __('unsubscribe alert') . '</a>';

        $words   = array();
        $words[] = array(
            '{USER_NAME}',
            '{USER_EMAIL}',
            '{ADS}',
            '{UNSUB_LINK}'
        );
        $words[] = array(
            $user['s_name'],
            $user['s_email'],
            $ads,
            $unsub_link
        );
        $title = osc_apply_filter('alert_email_instant_title_after', osc_mailBeauty($_title, $words), $user, $ads, $s_search);
        $body  = osc_apply_filter('alert_email_instant_description_after', osc_mailBeauty($_body, $words), $user, $ads, $s_search);

        $params = array(
            'subject'  => $title,
            'from'     => _osc_from_email_aux(),
            'to'       => $user['s_email'],
            'to_name'  => $user['s_name'],
            'body'     => $body,
            'alt_body' => $body
        );

        osc_sendMail($params);
    }
Пример #20
0
" /></div></div>
                    <div class="form-row">
                        <div class="form-label"><?php 
_e('Default language');
?>
</div>
                        <div class="form-controls">
                            <select name="language">
                            <?php 
foreach ($aLanguages as $lang) {
    ?>
                            <option value="<?php 
    echo $lang['pk_c_code'];
    ?>
" <?php 
    echo osc_language() == $lang['pk_c_code'] ? 'selected="selected"' : '';
    ?>
><?php 
    echo $lang['s_name'];
    ?>
</option>
                            <?php 
}
?>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-label"><?php 
_e('Default currency');
?>
Пример #21
0
 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 adimporter_ad($listing, $cat_info, $meta_info)
{
    $mItems = new ItemActions(true);
    $catId = @$listing->getElementsByTagName("categoryid")->item(0)->nodeValue;
    Params::setParam("country", @$listing->getElementsByTagName("country")->item(0)->nodeValue);
    Params::setParam("countryId", @$listing->getElementsByTagName("countryId")->item(0)->nodeValue);
    Params::setParam("region", @$listing->getElementsByTagName("region")->item(0)->nodeValue);
    Params::setParam("city", @$listing->getElementsByTagName("city")->item(0)->nodeValue);
    Params::setParam("cityArea", @$listing->getElementsByTagName("city_area")->item(0)->nodeValue);
    Params::setParam("address", @$listing->getElementsByTagName("address")->item(0)->nodeValue);
    Params::setParam("price", @$listing->getElementsByTagName("price")->item(0)->nodeValue);
    Params::setParam("currency", @$listing->getElementsByTagName("currency")->item(0)->nodeValue);
    Params::setParam("contactName", @$listing->getElementsByTagName("contactname")->item(0)->nodeValue);
    Params::setParam("contactEmail", @$listing->getElementsByTagName("contactemail")->item(0)->nodeValue);
    if ($catId == null) {
        $cats = $listing->getElementsByTagName("category");
        $cat_insert = true;
        $catId = 0;
        if ($cats->length > 0) {
            foreach ($cats as $cat) {
                $lang = osc_language();
                if ($cat->hasAttributes()) {
                    $attrs = $cat->attributes;
                    foreach ($attrs as $a) {
                        if ($a->name == 'lang') {
                            $lang = $a->value;
                            break;
                        }
                    }
                    $categoryDescription[$lang] = array('s_name' => $cat->nodeValue);
                    if ($catId == 0) {
                        if (isset($cat_info[$lang]) && isset($meta_info[$lang][$cat->nodeValue])) {
                            $catId = $cat_info[$lang][$cat->nodeValue];
                        } else {
                            $exists = Category::newInstance()->listWhere("b.fk_c_locale_code = '" . $lang . "' AND b.s_name = '" . $cat->nodeValue . "'");
                            if (isset($exists[0]) && isset($exists[0]['pk_i_id'])) {
                                $cat_info[$lang][$cat->nodeValue] = $exists[0]['pk_i_id'];
                                $cat_insert = false;
                                $catId = $exists[0]['pk_i_id'];
                                break;
                            }
                        }
                    }
                }
            }
            $category = array();
            $category['fk_i_parent_id'] = NULL;
            $category['i_expiration_days'] = 0;
            $category['i_position'] = 0;
            $category['b_enabled'] = 1;
            if ($cat_insert) {
                $catId = Category::newInstance()->insert($category, $categoryDescription);
            }
        }
    }
    Params::setParam("catId", $catId);
    $title_list = $listing->getElementsByTagName("title");
    $content_list = $listing->getElementsByTagName("content");
    $image_list = $listing->getElementsByTagName("image");
    $custom_list = $listing->getElementsByTagName("custom");
    $title = array();
    $content = array();
    $photos = '';
    $l = $title_list->length;
    for ($k = 0; $k < $l; $k++) {
        $lang = osc_language();
        if ($title_list->item($k)->hasAttributes()) {
            $attrs = $title_list->item($k)->attributes;
            foreach ($attrs as $a) {
                if ($a->name == 'lang') {
                    $lang = $a->value;
                    break;
                }
            }
        }
        $title[$lang] = $title_list->item($k)->nodeValue;
    }
    $l = $content_list->length;
    for ($k = 0; $k < $l; $k++) {
        $lang = osc_language();
        if ($content_list->item($k)->hasAttributes()) {
            $attrs = $content_list->item($k)->attributes;
            foreach ($attrs as $a) {
                if ($a->name == 'lang') {
                    $lang = $a->value;
                    break;
                }
            }
        }
        $content[$lang] = $content_list->item($k)->nodeValue;
    }
    $meta_array = array();
    $l = $custom_list->length;
    for ($k = 0; $k < $l; $k++) {
        if ($custom_list->item($k)->hasAttributes()) {
            $attrs = $custom_list->item($k)->attributes;
            foreach ($attrs as $a) {
                if ($a->name == 'name') {
                    $field_name = $a->value;
                    if (isset($meta_info[$field_name])) {
                        $meta_array[$meta_info[$field_name]] = $custom_list->item($k)->nodeValue;
                    } else {
                        $cfield = Field::newInstance()->findBySlug($field_name);
                        if ($cfield) {
                            $meta_info[$field_name] = $cfield['pk_i_id'];
                            $meta_array[$meta_info[$field_name]] = $custom_list->item($k)->nodeValue;
                        }
                    }
                    break;
                }
            }
        }
    }
    if (!empty($meta_array)) {
        Params::setParam("meta", $meta_array);
    }
    foreach ($image_list as $k => $image) {
        $tmp_name = "adimporterimage_" . $k . '_' . microtime();
        $image_ok = osc_downloadFile($image->nodeValue, $tmp_name);
        if ($image_ok) {
            $photos['error'][] = 0;
            $photos['size'][] = 100;
            $photos['type'][] = 'image/jpeg';
            $photos['tmp_name'][] = osc_content_path() . "downloads/" . $tmp_name;
        }
    }
    $_FILES['photos'] = $photos;
    Params::setParam("title", $title);
    Params::setParam("description", $content);
    //Params::_view();
    $mItems->prepareData(true);
    $success = $mItems->add();
    return array($success, $cat_info, $meta_info);
}
Пример #23
0
 function doModel()
 {
     switch ($this->action) {
         case 'add':
             // caliing add view
             $this->doView('languages/add.php');
             break;
         case 'add_post':
             // adding a new language
             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=languages');
             }
             osc_csrf_check();
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_translations_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
                 @unlink($filePackage['tmp_name']);
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The translation folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     if (osc_checkLocales()) {
                         $msg = _m('The language has been installed correctly');
                         osc_add_flash_ok_message($msg, 'admin');
                     } else {
                         $msg = _m('There was a problem adding the language');
                         osc_add_flash_error_message($msg, 'admin');
                     }
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_warning_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=languages&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the language');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'edit':
             // editing a language
             $sLocale = Params::getParam('id');
             if (!preg_match('/.{2}_.{2}/', $sLocale)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $aLocale = $this->localeManager->findByPrimaryKey($sLocale);
             if (count($aLocale) == 0) {
                 osc_add_flash_error_message(_m('Language id doesn\'t exist'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $this->_exportVariableToView("aLocale", $aLocale);
             $this->doView('languages/frm.php');
             break;
         case 'edit_post':
             // edit language post
             osc_csrf_check();
             $iUpdated = 0;
             $languageCode = Params::getParam('pk_c_code');
             $enabledWebstie = Params::getParam('b_enabled');
             $enabledBackoffice = Params::getParam('b_enabled_bo');
             $languageName = Params::getParam('s_name');
             $languageShortName = Params::getParam('s_short_name');
             $languageDescription = Params::getParam('s_description');
             $languageCurrencyFormat = Params::getParam('s_currency_format');
             $languageDecPoint = Params::getParam('s_dec_point');
             $languageNumDec = Params::getParam('i_num_dec');
             $languageThousandsSep = Params::getParam('s_thousands_sep');
             $languageDateFormat = Params::getParam('s_date_format');
             $languageStopWords = Params::getParam('s_stop_words');
             // formatting variables
             if (!preg_match('/.{2}_.{2}/', $languageCode)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $enabledWebstie = $enabledWebstie != '' ? true : false;
             $enabledBackoffice = $enabledBackoffice != '' ? true : false;
             $languageName = strip_tags($languageName);
             $languageName = trim($languageName);
             $languageShortName = strip_tags($languageShortName);
             $languageShortName = trim($languageShortName);
             $languageDescription = strip_tags($languageDescription);
             $languageDescription = trim($languageDescription);
             $languageCurrencyFormat = strip_tags($languageCurrencyFormat);
             $languageCurrencyFormat = trim($languageCurrencyFormat);
             $languageDateFormat = strip_tags($languageDateFormat);
             $languageDateFormat = trim($languageDateFormat);
             $languageStopWords = strip_tags($languageStopWords);
             $languageStopWords = trim($languageStopWords);
             $msg = '';
             if (!osc_validate_text($languageName)) {
                 $msg .= _m("Language name field is required") . "<br/>";
             }
             if (!osc_validate_text($languageShortName)) {
                 $msg .= _m("Language short name field is required") . "<br/>";
             }
             if (!osc_validate_text($languageDescription)) {
                 $msg .= _m("Language description field is required") . "<br/>";
             }
             if (!osc_validate_text($languageCurrencyFormat)) {
                 $msg .= _m("Currency format field is required") . "<br/>";
             }
             if (!osc_validate_int($languageNumDec)) {
                 $msg .= _m("Number of decimals must only contain numeric characters") . "<br/>";
             }
             if ($msg != '') {
                 osc_add_flash_error_message($msg, 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages&action=edit&id=' . $languageCode);
             }
             $array = array('b_enabled' => $enabledWebstie, 'b_enabled_bo' => $enabledBackoffice, 's_name' => $languageName, 's_short_name' => $languageShortName, 's_description' => $languageDescription, 's_currency_format' => $languageCurrencyFormat, 's_dec_point' => $languageDecPoint, 'i_num_dec' => $languageNumDec, 's_thousands_sep' => $languageThousandsSep, 's_date_format' => $languageDateFormat, 's_stop_words' => $languageStopWords);
             $iUpdated = $this->localeManager->update($array, array('pk_c_code' => $languageCode));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(sprintf(_m('%s has been updated'), $languageShortName), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been enabled for the website');
             $iUpdated = 0;
             $aValues = array('b_enabled' => 1);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 osc_translate_categories($i);
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been disabled for the website');
             $msg_warning = '';
             $iUpdated = 0;
             $aValues = array('b_enabled' => 0);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 if (osc_language() == $i) {
                     $msg_warning = sprintf(_m("%s can't be disabled because it's the default language"), osc_language());
                     continue;
                 }
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($msg_warning != '') {
                 if ($iUpdated > 0) {
                     osc_add_flash_warning_message($msg . '</p><p>' . $msg_warning, 'admin');
                 } else {
                     osc_add_flash_warning_message($msg_warning, 'admin');
                 }
             } else {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_bo_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been enabled for the backoffice (oc-admin)');
             $iUpdated = 0;
             $aValues = array('b_enabled_bo' => 1);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 osc_translate_categories($i);
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_bo_selected':
             osc_csrf_check();
             $msg = _m('Selected languages have been disabled for the backoffice (oc-admin)');
             $msg_warning = '';
             $iUpdated = 0;
             $aValues = array('b_enabled_bo' => 0);
             $id = Params::getParam('id');
             if (!is_array($id)) {
                 osc_add_flash_warning_message(_m("The language ids aren't in the correct format"), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             foreach ($id as $i) {
                 if (osc_language() == $i) {
                     $msg_warning = sprintf(_m("%s can't be disabled because it's the default language"), osc_language());
                     continue;
                 }
                 $iUpdated += $this->localeManager->update($aValues, array('pk_c_code' => $i));
             }
             if ($msg_warning != '') {
                 if ($iUpdated > 0) {
                     osc_add_flash_warning_message($msg . '</p><p>' . $msg_warning, 'admin');
                 } else {
                     osc_add_flash_warning_message($msg_warning, 'admin');
                 }
             } else {
                 osc_add_flash_ok_message($msg, 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'delete':
             osc_csrf_check();
             if (is_array(Params::getParam('id'))) {
                 $default_lang = osc_language();
                 foreach (Params::getParam('id') as $code) {
                     if ($default_lang != $code) {
                         if ($this->localeManager->deleteLocale($code)) {
                             if (!osc_deleteDir(osc_translations_path() . $code)) {
                                 osc_add_flash_error_message(sprintf(_m("Directory '%s' couldn't be removed"), $code), 'admin');
                             } else {
                                 osc_add_flash_ok_message(sprintf(_m('Directory "%s" has been successfully removed'), $code), 'admin');
                             }
                         } else {
                             osc_add_flash_error_message(sprintf(_m("Directory '%s' couldn't be removed;)"), $code), 'admin');
                         }
                     } else {
                         osc_add_flash_error_message(sprintf(_m("Directory '%s' couldn't be removed because it's the default language. Set another language as default first and try again"), $code), 'admin');
                     }
                 }
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         default:
             if (Params::getParam('checkUpdated') != '') {
                 osc_admin_toolbar_update_languages(true);
             }
             if (Params::getParam("action") != "") {
                 osc_run_hook("language_bulk_" . Params::getParam("action"), Params::getParam('id'));
             }
             // -----
             if (Params::getParam('iDisplayLength') == '') {
                 Params::setParam('iDisplayLength', 10);
             }
             // ?
             $this->_exportVariableToView('iDisplayLength', Params::getParam('iDisplayLength'));
             $p_iPage = 1;
             if (is_numeric(Params::getParam('iPage')) && Params::getParam('iPage') >= 1) {
                 $p_iPage = Params::getParam('iPage');
             }
             Params::setParam('iPage', $p_iPage);
             $aLanguages = OSCLocale::newInstance()->listAll();
             // pagination
             $start = ($p_iPage - 1) * Params::getParam('iDisplayLength');
             $limit = Params::getParam('iDisplayLength');
             $count = count($aLanguages);
             $displayRecords = $limit;
             if ($start + $limit > $count) {
                 $displayRecords = $start + $limit - $count;
             }
             // ----
             $aLanguagesToUpdate = json_decode(osc_get_preference('languages_to_update'));
             $bLanguagesToUpdate = is_array($aLanguagesToUpdate) ? true : false;
             // ----
             $aData = array();
             $max = $start + $limit;
             if ($max > $count) {
                 $max = $count;
             }
             for ($i = $start; $i < $max; $i++) {
                 $l = $aLanguages[$i];
                 $row = array();
                 $row[] = '<input type="checkbox" name="id[]" value="' . $l['pk_c_code'] . '" />';
                 $options = array();
                 $options[] = '<a href="' . osc_admin_base_url(true) . '?page=languages&amp;action=edit&amp;id=' . $l['pk_c_code'] . '">' . __('Edit') . '</a>';
                 $options[] = '<a href="' . osc_admin_base_url(true) . '?page=languages&amp;action=' . ($l['b_enabled'] == 1 ? 'disable_selected' : 'enable_selected') . '&amp;id[]=' . $l['pk_c_code'] . '&amp;' . osc_csrf_token_url() . '">' . ($l['b_enabled'] == 1 ? __('Disable (website)') : __('Enable (website)')) . '</a> ';
                 $options[] = '<a href="' . osc_admin_base_url(true) . '?page=languages&amp;action=' . ($l['b_enabled_bo'] == 1 ? 'disable_bo_selected' : 'enable_bo_selected') . '&amp;id[]=' . $l['pk_c_code'] . '&amp;' . osc_csrf_token_url() . '">' . ($l['b_enabled_bo'] == 1 ? __('Disable (oc-admin)') : __('Enable (oc-admin)')) . '</a>';
                 $options[] = '<a onclick="return delete_dialog(\'' . $l['pk_c_code'] . '\');"  href="' . osc_admin_base_url(true) . '?page=languages&amp;action=delete&amp;id[]=' . $l['pk_c_code'] . '&amp;' . osc_csrf_token_url() . '">' . __('Delete') . '</a>';
                 $auxOptions = '<ul>' . PHP_EOL;
                 foreach ($options as $actual) {
                     $auxOptions .= '<li>' . $actual . '</li>' . PHP_EOL;
                 }
                 $actions = '<div class="actions">' . $auxOptions . '</div>' . PHP_EOL;
                 $sUpdate = '';
                 // get languages to update from t_preference
                 if ($bLanguagesToUpdate) {
                     if (in_array($l['pk_c_code'], $aLanguagesToUpdate)) {
                         $sUpdate = '<a class="btn-market-update btn-market-popup" href="#' . htmlentities($l['pk_c_code']) . '">' . __("Update here") . '</a>';
                     }
                 }
                 $row[] = $l['s_name'] . $sUpdate . $actions;
                 $row[] = $l['s_short_name'];
                 $row[] = $l['s_description'];
                 $row[] = $l['b_enabled'] ? __('Yes') : __('No');
                 $row[] = $l['b_enabled_bo'] ? __('Yes') : __('No');
                 $aData[] = $row;
             }
             // ----
             $array['iTotalRecords'] = $displayRecords;
             $array['iTotalDisplayRecords'] = count($aLanguages);
             $array['iDisplayLength'] = $limit;
             $array['aaData'] = $aData;
             $page = (int) Params::getParam('iPage');
             if (count($array['aaData']) == 0 && $page != 1) {
                 $total = (int) $array['iTotalDisplayRecords'];
                 $maxPage = ceil($total / (int) $array['iDisplayLength']);
                 $url = osc_admin_base_url(true) . '?' . $_SERVER['QUERY_STRING'];
                 if ($maxPage == 0) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=1', $url);
                     $this->redirectTo($url);
                 }
                 if ($page > 1) {
                     $url = preg_replace('/&iPage=(\\d)+/', '&iPage=' . $maxPage, $url);
                     $this->redirectTo($url);
                 }
             }
             $this->_exportVariableToView('aLanguages', $array);
             $bulk_options = array(array('value' => '', 'data-dialog-content' => '', 'label' => __('Bulk actions')), array('value' => 'enable_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Enable (Website)'))), 'label' => __('Enable (Website)')), array('value' => 'disable_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Disable (Website)'))), 'label' => __('Disable (Website)')), array('value' => 'enable_bo_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Enable (oc-admin)'))), 'label' => __('Enable (oc-admin)')), array('value' => 'disable_bo_selected', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Disable (oc-admin)'))), 'label' => __('Disable (oc-admin)')), array('value' => 'delete', 'data-dialog-content' => sprintf(__('Are you sure you want to %s the selected languages?'), strtolower(__('Delete'))), 'label' => __('Delete')));
             $bulk_options = osc_apply_filter("language_bulk_filter", $bulk_options);
             $this->_exportVariableToView('bulk_options', $bulk_options);
             $this->doView('languages/index.php');
             break;
     }
 }
Пример #24
0
 function doModel()
 {
     switch ($this->action) {
         case 'add':
             // caliing add view
             $this->doView('languages/add.php');
             break;
         case 'add_post':
             // adding a new language
             $filePackage = Params::getFiles('package');
             if (isset($filePackage['size']) && $filePackage['size'] != 0) {
                 $path = osc_translations_path();
                 (int) ($status = osc_unzip_file($filePackage['tmp_name'], $path));
             } else {
                 $status = 3;
             }
             switch ($status) {
                 case 0:
                     $msg = _m('The translation folder is not writable');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 1:
                     if (osc_checkLocales()) {
                         $msg = _m('The language has been installed correctly');
                         osc_add_flash_ok_message($msg, 'admin');
                     } else {
                         $msg = _m('There was a problem adding the language');
                         osc_add_flash_error_message($msg, 'admin');
                     }
                     break;
                 case 2:
                     $msg = _m('The zip file is not valid');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
                 case 3:
                     $msg = _m('No file was uploaded');
                     osc_add_flash_warning_message($msg, 'admin');
                     $this->redirectTo(osc_admin_base_url(true) . "?page=languages&action=add");
                     break;
                 case -1:
                 default:
                     $msg = _m('There was a problem adding the language');
                     osc_add_flash_error_message($msg, 'admin');
                     break;
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'edit':
             // editing a language
             $sLocale = Params::getParam('id');
             if (!preg_match('/.{2}_.{2}/', $sLocale)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $aLocale = $this->localeManager->findByPrimaryKey($sLocale);
             if (count($aLocale) == 0) {
                 osc_add_flash_error_message(_m('Language id doesn\'t exist'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $this->_exportVariableToView("aLocale", $aLocale);
             $this->doView('languages/frm.php');
             break;
         case 'edit_post':
             // edit language post
             $iUpdated = 0;
             $languageCode = Params::getParam('pk_c_code');
             $enabledWebstie = Params::getParam('b_enabled');
             $enabledBackoffice = Params::getParam('b_enabled_bo');
             $languageName = Params::getParam('s_name');
             $languageShortName = Params::getParam('s_short_name');
             $languageDescription = Params::getParam('s_description');
             $languageCurrencyFormat = Params::getParam('s_currency_format');
             $languageDecPoint = Params::getParam('s_dec_point');
             $languageNumDec = Params::getParam('i_num_dec');
             $languageThousandsSep = Params::getParam('s_thousands_sep');
             $languageDateFormat = Params::getParam('s_date_format');
             $languageStopWords = Params::getParam('s_stop_words');
             // formatting variables
             if (!preg_match('/.{2}_.{2}/', $languageCode)) {
                 osc_add_flash_error_message(_m('Language id isn\'t in the correct format'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $enabledWebstie = $enabledWebstie != '' ? true : false;
             $enabledBackoffice = $enabledBackoffice != '' ? true : false;
             $languageName = strip_tags($languageName);
             $languageName = trim($languageName);
             if ($languageName == '') {
                 osc_add_flash_error_message(_m('Language name can\'t be empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $languageShortName = strip_tags($languageShortName);
             $languageShortName = trim($languageShortName);
             if ($languageShortName == '') {
                 osc_add_flash_error_message(_m('Language short name can\'t be empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $languageDescription = strip_tags($languageDescription);
             $languageDescription = trim($languageDescription);
             if ($languageDescription == '') {
                 osc_add_flash_error_message(_m('Language description can\'t be empty'), 'admin');
                 $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             }
             $languageCurrencyFormat = strip_tags($languageCurrencyFormat);
             $languageCurrencyFormat = trim($languageCurrencyFormat);
             $languageDateFormat = strip_tags($languageDateFormat);
             $languageDateFormat = trim($languageDateFormat);
             $languageStopWords = strip_tags($languageStopWords);
             $languageStopWords = trim($languageStopWords);
             $array = array('b_enabled' => $enabledWebstie, 'b_enabled_bo' => $enabledBackoffice, 's_name' => $languageName, 's_short_name' => $languageShortName, 's_description' => $languageDescription, 's_currency_format' => $languageCurrencyFormat, 's_dec_point' => $languageDecPoint, 'i_num_dec' => $languageNumDec, 's_thousands_sep' => $languageThousandsSep, 's_date_format' => $languageDateFormat, 's_stop_words' => $languageStopWords);
             $iUpdated = $this->localeManager->update($array, array('pk_c_code' => $languageCode));
             if ($iUpdated > 0) {
                 osc_add_flash_ok_message(sprintf(_m('%s has been updated'), $languageShortName), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable':
         case 'enable_bo':
             $default_lang = osc_language();
             $id = Params::getParam('id');
             $enabled = Params::getParam('enabled');
             if ($id) {
                 if ($action == 'enable' && $default_lang == $id && $enabled == 0) {
                     osc_add_flash_error_message(sprintf(_m('The language can\'t be disabled because it\'s the default language. You can change modify it in General Settings'), $i), 'admin');
                 } else {
                     $msg = $enabled == 1 ? _m('The language has been enabled for the public website') : _m('The language has been disabled for the public website');
                     $aValues = array('b_enabled' => $enabled);
                     $this->localeManager->update($aValues, array('pk_c_code' => $id));
                 }
                 if ($action == 'enable_bo') {
                     $msg = $enabled == 1 ? _m('The language has been enabled for the backoffice (oc-admin)') : _m('The language has been disabled for the backoffice (oc-admin)');
                     $aValues = array('b_enabled_bo' => $enabled);
                     $this->localeManager->update($aValues, array('pk_c_code' => $id));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the language. The language id was lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_selected':
             $msg = _m('Selected languages have been enabled for the website');
             $aValues = array('b_enabled' => 1);
             $id = Params::getParam('id');
             if ($id != '') {
                 foreach ($id as $i) {
                     $this->localeManager->update($aValues, array('pk_c_code' => $i));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_selected':
             $msg = _m('Selected languages have been disabled for the website');
             $aValues = array('b_enabled' => 0);
             $id = Params::getParam('id');
             if ($id != '') {
                 $default_lang = osc_language();
                 foreach ($id as $i) {
                     if ($default_lang == $i) {
                         $msg = _m('The language can\'t be disabled because it\'s the default language. You can change the default language under General Settings in order to disable it');
                     } else {
                         $this->localeManager->update($aValues, array('pk_c_code' => $i));
                     }
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'enable_bo_selected':
             $msg = _m('Selected languages have been enabled for the backoffice (oc-admin)');
             $aValues = array('b_enabled_bo' => 1);
             $id = Params::getParam('id');
             if ($id != '') {
                 foreach ($id as $i) {
                     $this->localeManager->update($aValues, array('pk_c_code' => $i));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'disable_bo_selected':
             $msg = _m('Selected languages have been disabled for the backoffice (oc-admin)');
             $aValues = array('b_enabled_bo' => 0);
             $id = Params::getParam('id');
             if ($id != '') {
                 foreach ($id as $i) {
                     $this->localeManager->update($aValues, array('pk_c_code' => $i));
                 }
                 osc_add_flash_ok_message($msg, 'admin');
             } else {
                 osc_add_flash_error_message(_m('There was a problem updating the languages. The language ids were lost'), 'admin');
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         case 'delete':
             if (is_array(Params::getParam('id'))) {
                 $default_lang = osc_language();
                 foreach (Params::getParam('id') as $code) {
                     if ($default_lang != $code) {
                         $this->localeManager->deleteLocale($code);
                         if (!osc_deleteDir(osc_translations_path() . $code)) {
                             osc_add_flash_error_message(sprintf(_m('Directory "%s" couldn\'t be removed'), $code), 'admin');
                         } else {
                             osc_add_flash_ok_message(sprintf(_m('Directory "%s" has been successfully removed'), $code), 'admin');
                         }
                     } else {
                         osc_add_flash_error_message(sprintf(_m('Directory "%s" couldn\'t be removed because it\'s the default language. Set another language as default first and try again'), $code), 'admin');
                     }
                 }
             }
             $this->redirectTo(osc_admin_base_url(true) . '?page=languages');
             break;
         default:
             $locales = OSCLocale::newInstance()->listAll();
             $this->_exportVariableToView("locales", $locales);
             $this->doView('languages/index.php');
             break;
     }
 }
Пример #25
0
/**
 * Gets description/information of current user
 *
 * @return string
 */
function osc_user_info($locale = "")
{
    if ($locale == "") {
        $locale = osc_current_user_locale();
    }
    $info = osc_user_field("s_info", $locale);
    if ($info == '') {
        $info = osc_user_field("s_info", osc_language());
        if ($info == '') {
            $aLocales = osc_get_locales();
            foreach ($aLocales as $locale) {
                $info = osc_user_field("s_info", $locale['pk_c_code']);
                if ($info != '') {
                    break;
                }
            }
        }
    }
    return (string) $info;
}
Пример #26
0
function osc_runAlert($type = null)
{
    if ($type == null) {
        return;
    }
    $internal_name = 'alert_email_hourly';
    switch ($type) {
        case 'HOURLY':
            $internal_name = 'alert_email_hourly';
            break;
        case 'DAILY':
            $internal_name = 'alert_email_daily';
            break;
        case 'WEEKLY':
            $internal_name = 'alert_email_weekly';
            break;
        case 'INSTANT':
            $internal_name = 'alert_email_instant';
            break;
    }
    $searches = Alerts::newInstance()->getAlertsByTypeGroup($type);
    foreach ($searches as $s_search) {
        $a_search = Search::newInstance();
        // Get if there're new ads on this search
        $a_search = osc_unserialize(base64_decode($s_search['s_search']));
        $crons = Cron::newInstance()->getCronByType($type);
        if (isset($crons[0])) {
            $last_exec = $crons[0]['d_last_exec'];
        } else {
            $last_exec = '0000-00-00 00:00:00';
        }
        $a_search->addConditions(sprintf(" %st_item.dt_pub_date > '%s' ", DB_TABLE_PREFIX, $last_exec));
        $totalItems = $a_search->count();
        $items = $a_search->doSearch();
        if (count($items) > 0) {
            //If we have new items from last check
            //Catch the user subscribed to this search
            $users = Alerts::newInstance()->getUsersBySearchAndType($s_search['s_search'], $type);
            if (count($users) > 0) {
                $prefLocale = osc_language();
                $page = Page::newInstance()->findByInternalName($internal_name);
                $page = Page::newInstance()->findByInternalName($internal_name);
                $page_description = $page['locale'];
                $_title = $page_description[$prefLocale]['s_title'];
                $_body = $page_description[$prefLocale]['s_text'];
                $ads = "";
                foreach ($items as $item) {
                    $ads .= '<a href="' . osc_item_url_ns($item['pk_i_id']) . '">' . $item['s_title'] . '</a><br/>';
                }
                foreach ($users as $user) {
                    if ($user['fk_i_user_id'] != 0) {
                        $user = User::newInstance()->findByPrimaryKey($user['fk_i_user_id']);
                    } else {
                        $user['s_name'] = $user['s_email'];
                    }
                    $unsub_link = osc_user_unsubscribe_alert_url($user['s_email'], $s_search['s_search']);
                    //osc_create_url(array('file' => 'user', 'action' => 'unsub_alert', 'email' => $user['s_email'], 'alert' => $s_search['s_search'])) ;
                    $unsub_link = '<a href="' . $unsub_link . '">unsubscribe alert</a>';
                    $words = array();
                    $words[] = array('{USER_NAME}', '{USER_EMAIL}', '{ADS}', '{UNSUB_LINK}');
                    $words[] = array($user['s_name'], $user['s_email'], $ads, $unsub_link);
                    $title = osc_mailBeauty($_title, $words);
                    $body = osc_mailBeauty($_body, $words);
                    $params = array('subject' => $title, 'to' => $user['s_email'], 'to_name' => $user['s_name'], 'body' => $body, 'alt_body' => $body);
                    osc_sendMail($params);
                }
            }
        }
    }
}
Пример #27
0
/**
 * Gets title from current premium, if $locale is unspecified $locale is current user locale
 * 
 * @param string $locale
 * @return string 
 */
function osc_premium_title($locale = "")
{
    if ($locale == "") {
        $locale = osc_current_user_locale();
    }
    $title = osc_premium_field("s_title", $locale);
    if ($title == '') {
        $title = osc_premium_field("s_title", osc_language());
        if ($title == '') {
            $aLocales = osc_get_locales();
            foreach ($aLocales as $locale) {
                $title = osc_premium_field("s_title", $locale);
                if ($title != '') {
                    break;
                }
            }
        }
    }
    return (string) $title;
}
Пример #28
0
 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&amp;action=edit&amp;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&amp;action=delete&amp;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(' &middot; ', $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();
 }