Ejemplo n.º 1
0
if (osc_market_api_connect() != '') {
    ?>
                    <h2 class="render-title separate-top"><?php 
    _e('Market Settings');
    ?>
</h2>
                    <div class="form-row">
                        <div class="form-label"><?php 
    _e('Connect ID');
    ?>
</div>
                        <div class="form-controls">
                            <div class="form-label-checkbox">
                                <label>
                                    <?php 
    echo osc_market_api_connect();
    ?>
                                </label>
                            </div>
                            <span class="help-box"><a href="#" id="market_disconnect"><?php 
    _e('Disconnect from market.osclass.org');
    ?>
</a></span>
                        </div>
                    </div>
                    <?php 
}
?>
                    <h2 class="render-title separate-top"><?php 
_e('Software updates');
?>
Ejemplo n.º 2
0
function customPageHeader()
{
    $action = Params::getParam("action");
    ?>
        <div class="header-title-market">
            <h1><?php 
    _e('Discover how to improve your Osclass!');
    ?>
</h1>
            <h2>Osclass offers many templates and plugins.<br/>Turn your Osclass installation into a classifieds site in a minute!</h2>
        </div>
        <div class="banner-market">

        </div>
        <ul class="tabs">
            <li <?php 
    if ($action == '') {
        echo 'class="active"';
    }
    ?>
><a href="<?php 
    echo osc_admin_base_url(true) . '?page=market';
    ?>
"><?php 
    _e('Market');
    ?>
</a></li>
            <li <?php 
    if ($action == 'plugins') {
        echo 'class="active"';
    }
    ?>
><a href="<?php 
    echo osc_admin_base_url(true) . '?page=market&action=plugins';
    ?>
"><?php 
    _e('Plugins');
    ?>
</a></li>
            <li <?php 
    if ($action == 'themes') {
        echo 'class="active"';
    }
    ?>
><a href="<?php 
    echo osc_admin_base_url(true) . '?page=market&action=themes';
    ?>
"><?php 
    _e('Themes');
    ?>
</a></li>
            <li <?php 
    if ($action == 'languages') {
        echo 'class="active"';
    }
    ?>
><a href="<?php 
    echo osc_admin_base_url(true) . '?page=market&action=languages';
    ?>
"><?php 
    _e('Languages');
    ?>
</a></li>
            <?php 
    if (osc_market_api_connect() == '') {
        ?>
                <li class="connect"><a id="market_connect" href="#"><?php 
        _e('Connect');
        ?>
</a></li>
            <?php 
    } else {
        ?>
                <li class="purchases <?php 
        if ($action == 'purchases') {
            echo 'active';
        }
        ?>
"><a href="<?php 
        echo osc_admin_base_url(true) . '?page=market&action=purchases';
        ?>
"><?php 
        _e('My purchases');
        ?>
</a></li>
                <li class="disconnect"><a id="market_disconnect" href="#"><?php 
        _e('Disconnect from Market');
        ?>
</a></li>
            <?php 
    }
    ?>
        </ul>

        <script type="text/javascript">
            $(document).ready(function() {
                <?php 
    if (osc_market_api_connect() == '') {
        ?>
                $("#dialog-connect").dialog({
                    width: '480',
                    autoOpen: false,
                    modal: true
                });
                $("#connect-submit").on('click', function() {
                    $('#connect_form').hide();
                    $('#connect_wait').show();
                    $.getJSON(
                        '<?php 
        echo osc_admin_base_url(true);
        ?>
?page=ajax&action=market_connect',
                        {'s_email' : $('#connect_user').attr('value'), 's_password' : $('#connect_password').attr('value')},
                        function(data){
                            if(data==null) {
                                $('#connect_form').show();
                                $('#connect_wait').hide();
                                var data = new Object();
                                data.error = 1;
                                data.msg = '<?php 
        _e('Sorry, the market is currently unavailable. Please try again in a few moments.');
        ?>
';
                            }
                            if(data.error==1) {
                                $('#connect_form').show();
                                $('#connect_wait').hide();
                                alert(data.msg);
                                var flash = $("#flash_js");
                                var message = $('<div>').addClass('pubMessages').addClass(class_type).attr('id', 'flashmessage').html(data.msg);
                                flash.html(message);
                                $("#flashmessage").slideDown('slow').delay(3000).slideUp('slow');
                            } else {
                                window.location.reload(true);
                            }
                        }
                    );
                });

                $("#connect-cancel").on('click', function() {
                    $('#dialog-connect').dialog('close');
                });

                $("#market_connect").on('click', function() {
                    $('#dialog-connect').dialog('open');
                });

                <?php 
    }
    ?>

                $('#market_categories').bind("change", function() {
                    <?php 
    if (Params::getParam('action') != '') {
        ?>
                        window.location = theme.marketCurrentURL + '&sCategory=' + $("#market_categories option:selected").prop('value');
                    <?php 
    } else {
        ?>
                        window.location = theme.marketCurrentURL + $("#market_categories option:selected").attr('section-data') + '&sCategory=' + $("#market_categories option:selected").prop('value');
                    <?php 
    }
    ?>
                });

                $("#market_disconnect").on('click', function() {
                    var x = confirm('<?php 
    _e('You are going to be disconnected from the Market, all your plugins and themes downloaded will remain installed and configured but you will not be able to update or download new plugins and themes. Are you sure?');
    ?>
');
                    if(x) {
                        window.location = '<?php 
    echo osc_admin_base_url(true);
    ?>
?page=settings&action=market_disconnect&<?php 
    echo osc_csrf_token_url();
    ?>
&redirect=<?php 
    echo base64_encode(osc_admin_base_url(true) . '?page=market&action=' . Params::getParam('action'));
    ?>
';
                    }
                })

                $.getJSON(
                    '<?php 
    echo osc_admin_base_url(true);
    ?>
?page=ajax&action=market_header',
                    function(data){
                        if(data.error==1) {
                        } else {
                            $('#content-head div.banner-market').html(data.html);
                        }
                    });
            });
        </script>
<?php 
}
Ejemplo n.º 3
0
function osc_market($section, $code)
{
    $plugin = false;
    $re_enable = false;
    $message = "";
    $data = array();
    $download_post_data = array('api_key' => osc_market_api_connect());
    /************************
     *** CHECK VALID CODE ***
     ************************/
    if ($code != '' && $section != '') {
        if (stripos($code, "http://") === FALSE) {
            // OSCLASS OFFICIAL REPOSITORY
            $url = osc_market_url($section, $code);
            $data = osc_file_get_contents($url, array('api_key' => osc_market_api_connect()));
            $data = json_decode(osc_file_get_contents($url, array('api_key' => osc_market_api_connect())), true);
        } else {
            // THIRD PARTY REPOSITORY
            if (osc_market_external_sources()) {
                $download_post_data = array();
                $data = json_decode(osc_file_get_contents($code), true);
            } else {
                return array('error' => 9, 'message' => __('No external sources are allowed'), 'data' => $data);
            }
        }
        /***********************
         **** DOWNLOAD FILE ****
         ***********************/
        if (isset($data['s_update_url']) && isset($data['s_source_file']) && isset($data['e_type'])) {
            if ($data['e_type'] == 'THEME') {
                $folder = 'themes/';
            } else {
                if ($data['e_type'] == 'LANGUAGE') {
                    $folder = 'languages/';
                } else {
                    // PLUGINS
                    $folder = 'plugins/';
                    $plugin = Plugins::findByUpdateURI($data['s_update_url']);
                    if ($plugin != false) {
                        if (Plugins::isEnabled($plugin)) {
                            Plugins::runHook($plugin . '_disable');
                            Plugins::deactivate($plugin);
                            $re_enable = true;
                        }
                    }
                }
            }
            $filename = date('YmdHis') . "_" . osc_sanitize_string($data['s_title']) . "_" . $data['s_version'] . ".zip";
            $url_source_file = $data['s_source_file'];
            $result = osc_downloadFile($url_source_file, $filename, $download_post_data);
            if ($result) {
                // Everything is OK, continue
                /**********************
                 ***** UNZIP FILE *****
                 **********************/
                @mkdir(osc_content_path() . 'downloads/oc-temp/');
                $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, osc_content_path() . 'downloads/oc-temp/');
                if ($res == 1) {
                    // Everything is OK, continue
                    /**********************
                     ***** COPY FILES *****
                     **********************/
                    $fail = -1;
                    if ($handle = opendir(osc_content_path() . 'downloads/oc-temp')) {
                        $folder_dest = ABS_PATH . "oc-content/" . $folder;
                        if (function_exists('posix_getpwuid')) {
                            $current_user = posix_getpwuid(posix_geteuid());
                            $ownerFolder = posix_getpwuid(fileowner($folder_dest));
                        }
                        $fail = 0;
                        while (false !== ($_file = readdir($handle))) {
                            if ($_file != '.' && $_file != '..') {
                                $copyprocess = osc_copy(osc_content_path() . "downloads/oc-temp/" . $_file, $folder_dest . $_file);
                                if ($copyprocess == false) {
                                    $fail = 1;
                                }
                            }
                        }
                        closedir($handle);
                        // Additional actions is not important for the rest of the proccess
                        // We will inform the user of the problems but the upgrade could continue
                        // Also remove the zip package
                        /****************************
                         ** REMOVE TEMPORARY FILES **
                         ****************************/
                        @unlink(osc_content_path() . 'downloads/' . $filename);
                        $path = osc_content_path() . 'downloads/oc-temp';
                        $rm_errors = 0;
                        $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                        for ($dir->rewind(); $dir->valid(); $dir->next()) {
                            if ($dir->isDir()) {
                                if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                    if (!rmdir($dir->getPathname())) {
                                        $rm_errors++;
                                    }
                                }
                            } else {
                                if (!unlink($dir->getPathname())) {
                                    $rm_errors++;
                                }
                            }
                        }
                        if (!rmdir($path)) {
                            $rm_errors++;
                        }
                        if ($fail == 0) {
                            // Everything is OK, continue
                            if ($data['e_type'] != 'THEME' && $data['e_type'] != 'LANGUAGE') {
                                if ($plugin != false && $re_enable) {
                                    $enabled = Plugins::activate($plugin);
                                    if ($enabled) {
                                        Plugins::runHook($plugin . '_enable');
                                    }
                                }
                            } else {
                                if ($data['e_type'] == 'LANGUAGE') {
                                    osc_checkLocales();
                                }
                            }
                            // recount plugins&themes for update
                            if ($section == 'plugins') {
                                osc_check_plugins_update(true);
                            } else {
                                if ($section == 'themes') {
                                    osc_check_themes_update(true);
                                } else {
                                    if ($section == 'languages') {
                                        osc_check_languages_update(true);
                                    }
                                }
                            }
                            if ($rm_errors == 0) {
                                $message = __('Everything looks good!');
                                $error = 0;
                            } else {
                                $message = __('Nearly everything looks good! but there were some errors removing temporary files. Please manually remove the \\"oc-content/downloads/oc-temp\\" folder');
                                $error = 6;
                                // Some errors removing files
                            }
                        } else {
                            $message = __('Problems when copying files. Please check your permissions. ');
                            if ($current_user['uid'] != $ownerFolder['uid']) {
                                if (function_exists('posix_getgrgid')) {
                                    $current_group = posix_getgrgid($current_user['gid']);
                                    $message .= '<p><strong>' . sprintf(__('NOTE: Web user and destination folder user is not the same, you might have an issue there. <br/>Do this in your console:<br/>chown -R %s:%s %s'), $current_user['name'], $current_group['name'], $folder_dest) . '</strong></p>';
                                }
                            }
                            $error = 4;
                            // Problems copying files. Maybe permissions are not correct
                        }
                    } else {
                        $message = __('Nothing to copy');
                        $error = 99;
                        // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file!
                    }
                } else {
                    $message = __('Unzip failed');
                    $error = 3;
                    // Unzip failed
                }
            } else {
                $message = __('Download failed');
                $error = 2;
                // Download failed
            }
        } else {
            if (isset($data['s_buy_url']) && isset($data['b_paid']) && $data['s_buy_url'] != '' && $data['b_paid'] == 0) {
                $message = __('This is a paid item, you need to buy it before you are able to download it');
                $error = 8;
                // Item not paid
            } else {
                $message = __('Input code not valid');
                $error = 7;
                // Input code not valid
            }
        }
    } else {
        $message = __('Missing download URL');
        $error = 1;
        // Missing download URL
    }
    return array('error' => $error, 'message' => $message, 'data' => $data);
}
Ejemplo n.º 4
0
 function doModel()
 {
     parent::doModel();
     if (time() - (int) osc_market_data_update() > 86400) {
         //84600 = 24*60*60
         $json = osc_file_get_contents(osc_market_url() . 'categories/', array('api_key' => osc_market_api_connect()));
         $data = @json_decode($json, true);
         if (is_array($data)) {
             osc_set_preference('marketCategories', $json);
             osc_set_preference('marketDataUpdate', time());
             osc_reset_preferences();
         }
     }
     switch ($this->action) {
         case 'buy':
             osc_csrf_check();
             $json = osc_file_get_contents(osc_market_url() . 'token/', array('api_key' => osc_market_api_connect()));
             $data = json_decode($json, true);
             osc_redirect_to(Params::getParam('url') . '?token=' . @$data['token']);
             break;
         case 'purchases':
         case 'plugins':
         case 'themes':
         case 'languages':
             $section = $this->action;
             $title = array('plugins' => __('Recommended plugins for You'), 'themes' => __('Recommended themes for You'), 'languages' => __('Languages for this version'), 'purchases' => __('My purchases'));
             // page number
             $marketPage = Params::getParam("mPage");
             $url_actual = osc_admin_base_url(true) . '?page=market&action=' . $section . '&mPage=' . $marketPage;
             if ($marketPage >= 1) {
                 $marketPage--;
             }
             // api
             $url = osc_market_url($section) . (Params::getParam('sCategory') != '' ? 'category/' . Params::getParam('sCategory') . '/' : '') . "page/" . $marketPage . '/length/9/';
             // default sort
             $sort_actual = '';
             $sort_download = $url_actual . '&sort=downloads&order=desc';
             $sort_updated = $url_actual . '&sort=updated&order=desc';
             // sorting options (default)
             $_order = 'desc';
             $order_download = $_order;
             $order_updated = $_order;
             $sort = Params::getParam("sort");
             $order = Params::getParam("order");
             if ($sort == '') {
                 $sort = 'updated';
             }
             if ($order == '') {
                 $order = $_order;
             }
             $aux = $order == 'desc' ? 'asc' : 'desc';
             switch ($sort) {
                 case 'downloads':
                     $sort_actual = '&sort=downloads&order=';
                     $sort_download = $url_actual . $sort_actual . $aux;
                     $sort_actual .= $order;
                     $order_download = $order;
                     // market api call
                     $url .= 'order/downloads/' . $order;
                     break;
                 case 'updated':
                     $sort_actual = '&sort=updated&order=';
                     $sort_updated = $url_actual . $sort_actual . $aux;
                     $sort_actual .= $order;
                     $order_updated = $order;
                     // market api call
                     $url .= 'order/updated/' . $order;
                     break;
                 default:
                     break;
             }
             // pageSize or length attribute is hardcoded
             $out = osc_file_get_contents($url, array('api_key' => osc_market_api_connect()));
             $array = json_decode($out, true);
             $output_pagination = '';
             if (is_numeric($array['total']) && $array['total'] > 0) {
                 $totalPages = ceil($array['total'] / $array['sizePage']);
                 $pageActual = $array['page'];
                 $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => osc_admin_base_url(true) . '?page=market' . '&amp;action=' . $section . '&amp;mPage={PAGE}' . $sort_actual, 'sides' => 5);
                 // set pagination
                 $pagination = new Pagination($params);
                 $output_pagination = $pagination->doPagination();
             } else {
                 $array['total'] = 0;
             }
             // export variable to view
             $this->_exportVariableToView("sort", $sort);
             $this->_exportVariableToView("title", $title);
             $this->_exportVariableToView("section", $section);
             $this->_exportVariableToView("array", $array);
             $this->_exportVariableToView("sort_download", $sort_download);
             $this->_exportVariableToView("sort_updated", $sort_updated);
             $this->_exportVariableToView("order_download", $order_download);
             $this->_exportVariableToView("order_updated", $order_updated);
             $this->_exportVariableToView("market_categories", json_decode(osc_market_categories(), true));
             $this->_exportVariableToView('pagination', $output_pagination);
             $this->doView("market/section.php");
             break;
         default:
             $aPlugins = array();
             $aThemes = array();
             $aLanguages = array();
             $out_plugin = osc_file_get_contents(osc_market_featured_url('plugins', 6));
             $array_plugins = json_decode($out_plugin, true);
             if (isset($array_plugins)) {
                 $aPlugins = $array_plugins['plugins'];
             }
             $out_themes = osc_file_get_contents(osc_market_featured_url('themes', 6));
             $array_themes = json_decode($out_themes, true);
             if (isset($array_themes)) {
                 $aThemes = $array_themes['themes'];
             }
             $out_languages = osc_file_get_contents(osc_market_featured_url('languages', 6));
             $array_languages = json_decode($out_languages, true);
             if (isset($array_languages)) {
                 $aLanguages = $array_languages['languages'];
             }
             $count = json_decode(osc_file_get_contents(osc_market_count_url()), true);
             if (!isset($count['pluginsTotal'])) {
                 $count['pluginsTotal'] = 0;
             }
             if (!isset($count['themesTotal'])) {
                 $count['themesTotal'] = 0;
             }
             if (!isset($count['languagesTotal'])) {
                 $count['languagesTotal'] = 0;
             }
             $this->_exportVariableToView("count", $count);
             $this->_exportVariableToView("aPlugins", $aPlugins);
             $this->_exportVariableToView("aThemes", $aThemes);
             $this->_exportVariableToView("aLanguages", $aLanguages);
             $this->_exportVariableToView("market_categories", json_decode(osc_market_categories(), true));
             $this->doView("market/index.php");
             break;
     }
 }
Ejemplo n.º 5
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();
 }