<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;

// if( !class_exists("os_libMain") ){
//     try{
//         $ss = new os_libMain();
//     }catch( Exception $e ){
//         die("Please reinstall OrdaSoft Joomla CCK Package!");
//     }
// }

class AdminCategory{
  static function showCategories(){
    global $db, $user, $option, $menutype, $app, $jConf;
    $db = new os_cckDb();
      if(!JFactory::getUser()->authorise('access_to_categories', 'com_os_cck')){
          $app->enqueueMessage("Access denied", 'error');
          return;
      }

    $user_checked_out_categories = " UPDATE #__os_cck_categories SET checked_out=0, checked_out_time='0000-00-00 00:00:00'
      WHERE checked_out_time > 0 AND ( TIME_TO_SEC('" . date('Y-m-d H:i:s') . "') - TIME_TO_SEC(checked_out_time) ) >= 7200;";
    $db->setQuery($user_checked_out_categories);
    $db->execute();
    $grooups = get_group_children_cck();

    $section = "com_os_cck";
    $sectionid = $app->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
    $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
    $limitstart = $app->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
    $levellimit = $app->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);
    
    $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
    $lang = $app->getUserStateFromRequest("language{$option}", 'language', '*');
    $entities = array();
    $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES')); 
    // $query = "SELECT ent.eid AS value, ent.name AS text FROM #__os_cck_entity as ent"
    //           ."\n LEFT JOIN #__os_cck_layout as lay ON lay.fk_eid = ent.eid WHERE lay.type = 'add_instance' GROUP BY ent.eid";
    $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity ORDER BY name ";

    $db->setQuery($query);
    $ent = $db->loadObjectList("value");

    $entities = (count($ent) > 1) ? array_merge($entities, (array)$ent) : $entities;
    $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);
    
    $where = '';
    
    if ($entity_id != '' && isset($ent[$entity_id])) {
        $where .= "AND (c.fk_eid ='{$entity_id}' OR c.fk_eid ='0')";
    }
    if ($lang != '*') {
      $where .= " AND c.language='$lang' ";
    }

    $query = "SELECT  c.*, c.checked_out as checked_out_contact_category, " .
        " c.parent_id as parent, u.name AS editor, COUNT(c_con.id) AS cc , c.rent_request, c.buy_request, c.language as lang "
        . "\n FROM #__os_cck_categories AS c"
        . "\n LEFT JOIN #__os_cck_categories_connect AS c_con ON c_con.fk_cid=c.cid"
        . "\n LEFT JOIN #__users AS u ON u.id = c.checked_out"
        . "\n WHERE c.section='$section'" . $where
        . "\n GROUP BY c.cid"
        . "\n ORDER BY section, parent_id, ordering";

    $db->setQuery($query);
    $rows = $db->loadObjectList();
    
    if(count($rows)>0)
    {
      $date = strtotime(JFactory::getDate()->toSql());
        foreach ($rows as $row) {
          $check = strtotime($row->checked_out_time);
          $remain = 7200 - ($date - $check);
          if (($remain <= 0) && ($row->checked_out != 0)) {
              $db->setQuery("UPDATE #__os_cck_categories SET checked_out=0,checked_out_time=0");
              
              try {
                  $db->execute();
              } catch (RuntimeException $e) {
                  echo $e->getMessage();
                  return false;
              }
              $row->checked_out = 0;
              $row->checked_out_time = 0;
          }
      }
    }

    
//    if ($db->getErrorNum()) {
//        echo $db->stderr();
//        return false;
//    }

    foreach ($rows as $k => $v) {
//      foreach ($rows as $k1 => $v1) {
//        if ($v->cid == $v1->parent_id) $rows[$k]->cc += $v1->cc;
//      }

      $rows[$k]->nentity = ($rows[$k]->cc == 0) ? "-" : "<a href=\"index.php?option=com_os_cck&section=categories&catid=" . $v->cid . "\">" . ($v->cc) . "</a>";

      $curgroup = array();
      $ss = explode(',', $v->params);
      foreach ($ss as $s) {
        if ($s == '') $s = '1';
        $curgroup[] = $grooups[$s];
      }
      $rows[$k]->groups = implode(', ', $curgroup);
    }

    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach ($rows as $v) {
      $pt = $v->parent_id;
      $list = @$children[$pt] ? $children[$pt] : array();
      array_push($list, $v);
      $children[$pt] = $list;
    }

    // second pass - get an indent list of the items
    $list = os_cckTreeRecurse(0, '', array(), $children, max(0, $levellimit - 1));
    
    $total = count($list);
    $limit = intval($limit);
    $language = JFactory::getApplication()->getLanguage();
    $language->load('os_lib',JPATH_ROOT);
    $pageNav = new os_libPagination($total, $limitstart, $limit);

    $levellist = JHTML::_('select.integerlist',1, 20, 1, 'levellimit', 'size="1" onchange="document.adminForm.submit();"', $levellimit);
    // slice out elements based on limits
    $list = array_slice($list, $pageNav->limitstart, $pageNav->limit);
    
    if (version_compare(JVERSION, "3.7.0", "ge")) {
        $install_lang = JLanguageHelper::getKnownLanguages();
    }else{
        $install_lang = JLanguage::getKnownLanguages();
    }
    $lang_list = array();
    $lang_opt[] = JHTML::_('select.option','*',cck_lang_text('COM_OS_CCK_OPTION_ALL_LANGUAGES'));
    foreach($install_lang as $key => $item){
        $lang_opt[] = JHTML::_('select.option',$key,$item['name']);
    }
    $lang_list = JHTML::_('select.genericlist',$lang_opt, 'language', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $lang); //new nik edit

    AdminViewCategory::show($list, $user->id, $pageNav, $lists, 'other', $entity_list, $lang_list);
  }

  static function showCategoriesModal(){
    global $db, $user, $option, $menutype, $app, $jConf, $moduleId;
    $db = new os_cckDb();
    $grooups = get_group_children_cck();
    $moduleId = protectInjectionWithoutQuote('module_id','');
    $section = "com_os_cck";
    $sectionid = $app->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
    $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
    $limitstart = $app->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
    $levellimit = $app->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);
    $eid = protectInjectionWithoutQuote('fk_eid', 0, 'INT');
//    var_dump($eid);
    $query = "SELECT  c.*, c.checked_out as checked_out_contact_category, " .
        " c.parent_id as parent, u.name AS editor, COUNT(c_con.id) AS cc , c.rent_request, c.buy_request, e.name as entity_name "
        . "\n FROM #__os_cck_categories AS c"
        . "\n LEFT JOIN #__os_cck_entity AS e ON e.eid=c.fk_eid"
        . "\n LEFT JOIN #__os_cck_categories_connect AS c_con ON c_con.fk_cid=c.cid"
        . "\n LEFT JOIN #__users AS u ON u.id = c.checked_out"
        . "\n WHERE c.section='$section'"
        . "\n AND c.published = 1"
        . "\n AND (c.fk_eid = $eid OR c.fk_eid = 0)"
        . "\n GROUP BY c.cid"
        . "\n ORDER BY section, parent_id, ordering";

    $db->setQuery($query);
    
    try {
        $rows = $db->loadObjectList();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
        return false;
    }
//    if ($db->getErrorNum()) {
//        echo $db->stderr();
//        return false;
//    }

    foreach ($rows as $k => $v) {
      foreach ($rows as $k1 => $v1) {
        if ($v->cid == $v1->parent_id) $rows[$k]->cc += $v1->cc;
      }

      $rows[$k]->nentity = ($rows[$k]->cc == 0) ? "-" : $v->cc;

      $curgroup = array();
      $ss = explode(',', $v->params);
      foreach ($ss as $s) {
        if ($s == '') $s = '1';
        $curgroup[] = $grooups[$s];
      }
      $rows[$k]->groups = implode(', ', $curgroup);
    }

    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach ($rows as $v) {
      $pt = $v->parent_id;
      $list = @$children[$pt] ? $children[$pt] : array();
      array_push($list, $v);
      $children[$pt] = $list;
    }

    // second pass - get an indent list of the items
    $list = os_cckTreeRecurse(0, '', array(), $children, max(0, $levellimit - 1));
    $total = count($list);
//    $pageNav = new JPagination($total, $limitstart, $limit);

    $levellist = JHTML::_('select.integerlist',1, 20, 1, 'levellimit', 'size="1" onchange="document.adminForm.submit();"', $levellimit);
    // slice out elements based on limits
//    $list = array_slice($list, $pageNav->limitstart, $pageNav->limit);

    AdminViewCategory::showModal($list, $user->id, $pageNav, $lists, 'other');
  }

  static function showCategoryModalPlg($option){
    global $db, $user, $option, $menutype, $app, $jConf, $moduleId;
    $db = new os_cckDb();
    $grooups = get_group_children_cck();
    $moduleId = protectInjectionWithoutQuote('module_id','');
    $section = "com_os_cck";
    $sectionid = $app->getUserStateFromRequest("sectionid{$section}{$section}", 'sectionid', 0);
    $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
    $limitstart = $app->getUserStateFromRequest("view{$section}limitstart", 'limitstart', 0);
    $levellimit = $app->getUserStateFromRequest("view{$option}limit$menutype", 'levellimit', 10);
    $lid = protectInjectionWithoutQuote('lid','');
    $query = "SELECT  c.*, c.checked_out as checked_out_contact_category, " .
        " c.parent_id as parent, u.name AS editor, COUNT(c_con.id) AS cc , c.rent_request, c.buy_request "
        . "\n FROM #__os_cck_categories AS c"
        . "\n LEFT JOIN #__os_cck_categories_connect AS c_con ON c_con.fk_cid=c.cid"
        . "\n LEFT JOIN #__users AS u ON u.id = c.checked_out"
        . "\n WHERE c.section='$section'"
        . "\n AND c.published = 1"
        . "\n GROUP BY c.cid"
        . "\n ORDER BY section, parent_id, ordering";

    $db->setQuery($query);
    //$rows = $db->loadObjectList();
    
    try {
        $rows = $db->loadObjectList();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
        return false;
    }
//    if ($db->getErrorNum()) {
//        echo $db->stderr();
//        return false;
//    }

    foreach ($rows as $k => $v) {
      foreach ($rows as $k1 => $v1) {
        if ($v->cid == $v1->parent_id) $rows[$k]->cc += $v1->cc;
      }

      $rows[$k]->nentity = ($rows[$k]->cc == 0) ? "-" : $v->cc;

      $curgroup = array();
      $ss = explode(',', $v->params);
      foreach ($ss as $s) {
        if ($s == '') $s = '1';
        $curgroup[] = $grooups[$s];
      }
      $rows[$k]->groups = implode(', ', $curgroup);
    }

    // establish the hierarchy of the categories
    $children = array();
    // first pass - collect children
    foreach ($rows as $v) {
      $pt = $v->parent_id;
      $list = @$children[$pt] ? $children[$pt] : array();
      array_push($list, $v);
      $children[$pt] = $list;
    }

    // second pass - get an indent list of the items
    $list = os_cckTreeRecurse(0, '', array(), $children, max(0, $levellimit - 1));
    $total = count($list);
    $language = JFactory::getApplication()->getLanguage();
    $language->load('os_lib',JPATH_ROOT);
    $pageNav = new os_libPagination($total, $limitstart, $limit);

    $levellist = JHTML::_('select.integerlist',1, 20, 1, 'levellimit', 'size="1" onchange="document.adminForm.submit();"', $levellimit);
    // slice out elements based on limits
    $list = array_slice($list, $pageNav->limitstart, $pageNav->limit);

    AdminViewCategory::showCategoryModalPlg($list, $user->id, $pageNav, $lists, 'other', $lid);
  }

  static function editCategory($section = '', $uid = 0){ 
      global $db, $user,$app, $os_cck_state;

      if (version_compare(JVERSION, "4.0.0-alpha10", "lt")) {

      } else {
        $input = JFactory::getApplication()->input;
        $input->set('hidemainmenu', true);
      }
      $db = new os_cckDb();
      $type = mosGetParam($_REQUEST, 'type', '');
      $redirect = mosGetParam($_POST, 'section', '');;
      $row = new os_cckCategory($db->_db);
      $parent_id = protectInjectionWithoutQuote('parent_id', '');
      $title = protectInjectionWithoutQuote('title', '');
      $name = protectInjectionWithoutQuote('name', '');
      $entity_id = protectInjectionWithoutQuote('entity_id', '');
      $image = protectInjectionWithoutQuote('image', '');
      $published = protectInjectionWithoutQuote('published', '');
      $description = protectInjectionWithoutQuote('description', '');
      
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      // load the row from the db table
      $row->load($uid);
      if($parent_id != ''){
          $row->parent_id = $parent_id;
      }
      if($title != ''){
          $row->title = $title;
      }
      if($name != ''){
          $row->name = $name;
      }
      if($entity_id != ''){
          $row->fk_eid = $entity_id;
      }
      if($image != ''){
          $row->image = $image;
      }
      if($published != ''){
          $row->published = $published;
      }
      if($description != ''){
          $row->description = $description;
      }
      
      
      // fail if checked out not by 'me'
      if ($row->checked_out && $row->checked_out <> $user->id) {
          $app->redirect('index.php?option=com_os_cck&task=show_categories', 'The category ' . $row->title . ' is currently being edited by another administrator');
      }

      if ($uid) {
        
          // existing record
          $row->checkout($user->id);
          // code for Link Menu
      } else {
          // new record
          $row->section = $section;
          $row->published = 1;
      }
      // make order list

      $order = array();
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $db->setQuery("SELECT COUNT(*) FROM #__os_cck_categories WHERE section='$row->section'");
      
      $max = intval($db->loadResult()) + 1;
      for ($i = 1; $i < $max; $i++) {
          $order[] = JHTML::_('select.option',$i);
      }
      // build the html select list for ordering
      $query = "SELECT ordering AS value, title AS text"
          . "\n FROM #__os_cck_categories"
          . "\n WHERE section = '$row->section'"
          . "\n ORDER BY ordering";
      if (version_compare(JVERSION, "3.0.0", "lt")) {
          $lists['ordering'] = JHTML::_('list.specificordering',$row, $uid, $query);
      } else {
        //   $lists['ordering'] = JHTML::_('list.ordering',$row, $query,$attribs = null, $uid);
          $lists['ordering'] = JHTML::_('list.ordering','', $query,$attribs = null, $uid);
      }
      // build the select list for the image positions
      $active = ($row->image_position ? $row->image_position : 'left');
      $lists['image_position'] = JHTML::_('list.positions','image_position', $active, null, 0, 0);
      // Imagelist
      
      $lists['image'] = os_cck_HTML::imageList('image', $row->image);
      $lists['published'] = JHTML::_('select.booleanlist','published', 'class="inputbox"', $row->published);
      //print_r($row);exit;
      // build the html select list for paraent item
      $options = array();
      $options[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_A_SELECT_TOP'));

      //***********access category
      $gtree = get_group_children_tree_cck();

      $f = array();
      if($row->params){
        $s = explode(',', $row->params);
      }else{
        $s = array();
      }
      for ($i = 0; $i < count($s); $i++)
          $f[] = JHTML::_('select.option',$s[$i]); 
      if(empty($f))
          $f[] = '1';
      $attr = array (
        'list.attr' => ' multiple="true" ',
        'id' => 'category_registrationlevel',
        'list.select' => $f,
        'group.items' => null,
        'option.key.toHtml' => false,
        'option.text.toHtml' => false
      );
      $lists['category']['registrationlevel'] = JHTML::_('select.groupedlist',$gtree,'category_registrationlevel[]', $attr);
      
      //********end access category
      $lists['parent'] = os_cck_HTML::categoryParentList($row->cid, "", $options, 1, $row->fk_eid);
      
      $lists['entity'] = os_cck_HTML::categoryEntityList($row->fk_eid);
      
      if (version_compare(JVERSION, "3.7.0", "ge")) {
            $install_lang = JLanguageHelper::getKnownLanguages();
        }else{
            $install_lang = JLanguage::getKnownLanguages();
        }
        
      $lang_list = array();
      $categories_lang_list = array();
      $lang_list[] = JHTML::_('select.option','*','All');
        foreach($install_lang as $key => $item){
            $lang_list[] = JHTML::_('select.option',$key,$item['name']);
            $lang_categories = $row->getCategoryListLang($key);

            if(!empty($lang_categories)){
                $categories_lang_list[$key] = array();
                $categories_lang_list[$key][] = JHTML::_('select.option','',cck_lang_text('COM_OS_CCK_ADMIN_PLEASE_SEL'));
                foreach($lang_categories as $cat){
                    
                    $categories_lang_list[$key][] = JHTML::_('select.option',$cat->cid,$cat->title);
                }
            }
        }
      $lists['lang_list'] = JHTML::_('select.genericlist',$lang_list, 'language', 'size="1" class="inputbox"', 'value', 'text', $row->language);
      $lists['categories_lang_list'] = $categories_lang_list;
      if($row->associate_category){
            $lists['assoc_list'] = unserialize($row->associate_category);
        }else{
            $lists['assoc_list'] = array();
        }
      AdminViewCategory::edit($row, $section, $lists, $redirect);
  }

  static function saveCategory()
  {
      global $db,$app, $os_cck_state;
      $db = new os_cckDb();
      if(!cck_checkReferer()){
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
          return;
      }
      
      
      $row = new os_cckCategory($db->_db);
      $post = $_POST;
      
      $post = JFactory::getApplication()->input->post->getArray(array(), null, 'raw'); 
      
      $post['checked_out_time'] = '0000-00-00 00:00:00';
      if(empty($post['title']) || empty($post['name'])){
        echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
        exit();
      }
      
      if (!$row->bind($post)) {
          echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
          exit();
      }
      if($row->parent_id != 0){
        $query = "SELECT fk_eid FROM #__os_cck_categories WHERE cid=$row->parent_id";
        $db->setQuery($query);
        $parent_entity = $db->loadResult();

        if($parent_entity != $post['entity_id']){
            $post['entity_id'] = $parent_entity;
        }
      }
      
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $assoc_categories_list = array();
    foreach ($post as $key => $value) {
       if(stripos($key,'category_assoc_') !== false){
           $lang = str_replace('category_assoc_', '', $key);
           $assoc_categories_list[$lang] = $value;
           if($lang == $post['language']){
               $assoc_categories_list[$lang] = $post['cid'];
           }
       }
    }
    $row->associate_category = serialize($assoc_categories_list);
    // var_dump($row); exit;
    foreach ($assoc_categories_list as $cat){
        $query = "UPDATE #__os_cck_categories SET associate_category='".serialize($assoc_categories_list)."' WHERE cid='$cat'";
        $db->setQuery($query);
        $db->execute();
    }
      $row->section = 'com_os_cck';
      $row->parent_id = $post['parent_id'];
      
      $row->fk_eid = $post['entity_id'];
      if($row->fk_eid == '*') $row->fk_eid = 0;


      if (!$row->check()) {
          echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
          exit();
      }
//        var_dump(mosGetParam($_POST, 'category_registrationlevel', array())); exit;
      //****set access level
      $row->params = implode(',', mosGetParam($_POST, 'category_registrationlevel', array()));
      
      //****end set access level
      if ($row->params == "") $row->params = "1";

      if (!$row->store()) {
          echo "<script> alert('" . addslashes($row->getError()) . "'); window.history.go(-1); </script>\n";
          exit();
      }
      
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $row->checkin();
      $row->updateOrder("section='$row->section' AND parent_id='$row->parent_id'");

      $app->redirect('index.php?option=com_os_cck&task=show_categories');
  }


  //this function check - is exist houses in this folder and folders under this category
  static function is_exist_curr_and_subcategory_items($catid)
  {
      global $db, $user;
      $db = new os_cckDb();
      $query = "SELECT *, COUNT(a.fk_cid) AS numlinks FROM #__os_cck_categories AS cc"
          . "\n  JOIN #__os_cck_categories_connect AS a ON a.fk_cid = cc.cid"
          . "\n WHERE  cc.cid='$catid' "
          . "\n GROUP BY cc.cid"
          . "\n ORDER BY cc.ordering";
      $db->setQuery($query);
      $categories = $db->loadObjectList();
      if (count($categories) != 0) return true;

      $query = "SELECT cid "
          . "FROM #__os_cck_categories AS cc "
          . " WHERE parent_id='$catid' ";
      $db->setQuery($query);
      $categories = $db->loadObjectList();
      if (count($categories) == 0) return false;

      foreach ($categories as $k) {
          if (AdminCategory::is_exist_curr_and_subcategory_items($k->cid)) return true;
      }
      return false;
  }

  //end function


  static function removeCategoriesFromDB($cid)
  {
      global $db, $user;
      $db = new os_cckDb();
      if(!cck_checkReferer()){
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
          return;
      }
      $query = "SELECT cid  "
          . "FROM #__os_cck_categories AS cc "
          . " WHERE parent_id='$cid' ";
      $db->setQuery($query);
      $categories = $db->loadObjectList();
     // print_r($categories);exit;
      //    echo $db->getErrorMsg() ;

      if (count($categories) != 0) {
          //delete child
          foreach ($categories as $k) {
              AdminCategory::removeCategoriesFromDB($k->cid);
          }
      }

      $sql = "DELETE FROM #__os_cck_categories WHERE cid = $cid ";
      $db->setQuery($sql);
      $db->execute();

  }

  static function removeCategories($section, $cid)
  {
      global $db,$app;
      $db = new os_cckDb();
      if(!cck_checkReferer()){
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
          return;
      }
      if (count($cid) < 1) {
           $app->redirect('index.php?option=com_os_cck&task=show_categories',cck_lang_text('COM_OS_CCK_SELECT_CAT_DELETE'));
      }

      foreach ($cid as $catid) {
          if (AdminCategory::is_exist_curr_and_subcategory_items($catid)) {
              $app->enqueueMessage(cck_lang_text('COM_OS_CCK_CONTAIN_INCTANCES'));
              $app->redirect('index.php?option=com_os_cck&task=show_categories');
          }
      }

      foreach ($cid as $catid) {
          AdminCategory::removeCategoriesFromDB($catid);
      }


      $msg = "Categories " . cck_lang_text('COM_OS_CCK_DELETED');
      $app->redirect('index.php?option=com_os_cck&task=show_categories&mosmsg=' . $msg);
  }

  static function publishCategories($section, $categoryid = null, $cid = null, $publish = 1)
  {
      global $db, $user, $app, $os_cck_state;
      $db = new os_cckDb();
      if(!cck_checkReferer()){
          $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
          return;
      }
      if (!is_array($cid)) {
          $cid = array();
      }
      if ($categoryid) {
          $cid[] = $categoryid;
      }

      if (count($cid) < 1) {
          $action = $publish ? _PUBLISH : _DML_UNPUBLISH;
          echo "<script> alert('" . _DML_SELECTCATTO . " $action'); window.history.go(-1);</script>\n";
          exit;
      }

      $cids = implode(',', $cid);
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $query = "UPDATE #__os_cck_categories SET published='$publish'"
          . "\nWHERE cid IN ($cids) AND (checked_out=0 OR (checked_out='$user->id'))";
      $db->setQuery($query);
      try {
          $db->execute();
      } catch (RuntimeException $e) {
          echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
          exit;
      }
      
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
      }

      if (count($cid) == 1 && $cid[0] > 0 ) {
          $row = new os_cckCategory($db->_db);
          $row->checkin($cid[0]);
      }

      $app->redirect('index.php?option=com_os_cck&task=show_categories');
  }

  static function cancelCategory()
  {
      global $db, $app;
      $db = new os_cckDb();

      $row = new os_cckCategory($db->_db);
      $row->bind($_POST);
      $row->checkin();
      $app->redirect('index.php?option=com_os_cck&task=show_categories');
  }

  static function orderCategory($uid, $inc)
  {
      global $db, $app;
      $db = new os_cckDb();
      $row = new os_cckCategory($db->_db);
      $row->load($uid);
      if ($row->ordering == 1 && $inc == -1) $app->redirect('index.php?option=com_os_cck&task=show_categories');

      $new_order = $row->ordering + $inc;

      //change ordering - for other element
      $query = "UPDATE #__os_cck_categories SET ordering='" . ($row->ordering) . "'"
          . "\nWHERE parent_id = $row->parent_id and ordering=$new_order";
      $db->setQuery($query);
      $db->execute();

      //change ordering - for this element
      $query = "UPDATE #__os_cck_categories SET ordering='" . $new_order . "'"
          . "\nWHERE cid = $uid";
      $db->setQuery($query);
      $db->execute();

      $app->redirect('index.php?option=com_os_cck&task=show_categories');

  }

  static function accessCategory($uid, $access)
  {
      global $db, $app;
      $db = new os_cckDb();
      $row = new os_cckCategory($db->_db);
      $row->load($uid);
      $row->access = $access;

      if (!$row->check()) {
          return $row->getError();
      }
      if (!$row->store()) {
          return $row->getError();
      }

      $app->redirect('index.php?option=com_os_cck&task=show_categories');
  }

}
