<?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 AdminReview{

  static function showReviews($option){
    global $db, $app, $jConf, $entityFieldLists;
    $db = new os_cckDb();
      if(!JFactory::getUser()->authorise('access_to_reviews', 'com_os_cck')){
          $app->enqueueMessage("Access denied", 'error');
          return;
      }
    // SORTING parameters start
    $item_session = JFactory::getSession();
    $item_sort_param = mosGetParam($_GET, 'sort', 'jei.eiid');
    if (is_array($sort_arr = $item_session->get('eq_itemsort', ''))) {
      if(protectInjectionWithoutQuote('sorting_direction','')){
        if(protectInjectionWithoutQuote('sorting_direction')=="ASC"){
          $sort_arr['sorting_direction'] = "DESC";
        }else{
          $sort_arr['sorting_direction'] = "ASC";
        }
      }elseif($item_session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $item_session->get('sorting_direction');
      }else{
        $sort_arr['sorting_direction']="DESC";
      }
      if ($item_sort_param == $sort_arr['field']) {
      } else {
        $sort_arr['field'] = $item_sort_param;
      }
      if($item_sort_param == 'category'){
        $sort_string = 'c.fk_cid' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_entity'){
        $sort_string = 'jei.fk_eid' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_id'){
        $sort_string = 'jei.eiid' . " " . $sort_arr['sorting_direction'];
      }else{
        $sort_string = $sort_arr['field'] . " " . $sort_arr['sorting_direction'];
      }
    } else { 
      $sort_arr = array();
      if(protectInjectionWithoutQuote('sorting_direction','')){
        $sort_arr['sorting_direction'] = protectInjectionWithoutQuote('sorting_direction');
      }elseif($item_session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $item_session->get('sorting_direction');
      }else{
        $sort_arr['sorting_direction']="DESC";
      }

      if($item_sort_param == 'category'){
        $sort_string = 'c.fk_cid'. " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_entity'){
        $sort_string = 'jei.fk_eid'. " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_id'){
        $sort_string = 'jei.eiid'. " " . $sort_arr['sorting_direction'];
      }else{
        $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
      }
      $sort_arr['field'] = $item_sort_param;
    }
    $item_session->set('eq_itemsort', $sort_arr);

    //maybe it is search below
    $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
    $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
    $catid = $app->getUserStateFromRequest("catid{$option}", 'catid', '');
    $pub = $app->getUserStateFromRequest("pub{$option}", 'pub', '');
    $search = $app->getUserStateFromRequest("search{$option}", 'search', '');

    $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
    $entities = array();
    $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES'));
    $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity  ORDER BY name";             
    $db->setQuery($query);
    $ent = $db->loadObjectList("value");
    if( count($ent) > 1 ){
      $entities = array_merge($entities, (array)$ent) ;
    } else{
      //$entities = $entities;
      //set $entity_id == "" - when we haven 1 entity, and yet one - old was war selected we removed, 
      //for clear old values from $entity_list filter and from $where array
      $entity_id = "";
    }
    $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 
      'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);

    $where = $where2 = array();
    $catwhere = "";
    if ($entity_id != '' && isset($ent[$entity_id])) {
        array_push($where, "jei.fk_eid ='{$entity_id}'");
    }
    if ($pub == "pub") {
      array_push($where, "jei.published = 1");
    } else if ($pub == "not_pub") {
      array_push($where, "jei.published = 0");
    }
    if ($catid > 0) {
      array_push($where, "c.fk_cid='$catid'");
    }
    array_push($where, "cl.type = 'review_instance'");
    //pagination?*
    $selectstring = "SELECT count(jei.eiid) " .
      "\n FROM #__os_cck_entity_instance AS jei" .
      "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
      "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";

    if($search || protectInjectionWithoutQuote('sort','')){
      $fieldNames = $item_session->get('field_names');
      foreach ($fieldNames as $value) {
        foreach ($value['fields'] as $name) {
          if($value['field_type'] == 'categoryfield' && $name == protectInjectionWithoutQuote('sort','')){
            $sort_string = 'cc.title'. " " . $sort_arr['sorting_direction'];
            continue;
          }
          array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
        }
        $selectstring .= "\n LEFT JOIN #__os_cck_content_entity_".$value['ent_name'].
          " ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
      }
      array_push($where2, "jei.eiid LIKE '%$search%' ");
    }

    $selectstring .=  "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
      "\n LEFT JOIN #__users AS u ON u.id = jei.checked_out " .
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

    if($search){
      $selectstring .=  (count($where2) ? "\nAND (" . implode(' OR ', $where2).')' : "");
    }
    $db->setQuery($selectstring);

    try {
        $total = $db->loadResult();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
    }
    //echo $db->getErrorMsg();
    $pageNav = new os_libPagination($total, $limitstart, $limit);

    $selectstring = "SELECT jei.*, cl.title as lay_title, cl.type as lay_type, cl.params as lay_params, " .
      "\n GROUP_CONCAT(DISTINCT cc.title SEPARATOR ', ') AS category, ce.name AS entity, " .
      "\n l.id as rentid, l.rent_from as rent_from, l.rent_return as rent_return,l.rent_until as rent_until,u.name AS editor, " .
      "\n GROUP_CONCAT(DISTINCT cpc.fid_parent SEPARATOR ',') AS fid_parent " .
      "\n FROM #__os_cck_entity_instance AS jei" .
      "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
      "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid " .
      "\n LEFT JOIN #__os_cck_child_parent_connect AS cpc ON jei.eiid=cpc.fid_child ";

      if($search || protectInjectionWithoutQuote('sort','')){
        $fieldNames = $item_session->get('field_names');
        foreach ($fieldNames as $value) {
          foreach ($value['fields'] as $name) {
            if($value['field_type'] == 'categoryfield' && $name == protectInjectionWithoutQuote('sort','')){
              $sort_string = 'cc.title'. " " . $sort_arr['sorting_direction'];
              continue;
            }
            array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
          }
          $selectstring .= "\n LEFT JOIN #__os_cck_content_entity_".$value['ent_name'].
            " ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
        }
        array_push($where2, "jei.eiid LIKE '%$search%' ");
      }

    $selectstring .= "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
      "\n LEFT JOIN #__users AS u ON u.id = jei.checked_out " .
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

    if($search){
      $selectstring .=  (count($where2) ? "\nAND (" . implode(' OR ', $where2).')' : "");
    }
    
    $selectstring .= "\n GROUP BY jei.eiid " .
      "\nORDER BY jei.notreaded desc,$sort_string " .
      "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
    $db->setQuery($selectstring);
    try {
        $rows = $db->loadObjectList();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
        return false;
    }
    
    //prepere for show fields: selected for show in ReviewManager
    $show_fields = $entityEaaray = $layoutArray = $fieldNames = array();
    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_entity_instance SET checked_out=0,checked_out_time=0");
            $db->execute();
            $row->checked_out = 0;
            $row->checked_out_time = 0;
        }
        // $lay_params = unserialize($row->lay_params);
        $entityEaaray[] = $row->fk_eid;
        $layoutArray[] = $row->fk_lid;
      }
        
        $entityEaaray = array_unique($entityEaaray);
        $layoutArray = array_unique($layoutArray);
        $uniqFieldsArray = array(); //need for add fields only 1 time
        foreach($entityEaaray as $key => $value){
          foreach($layoutArray as $key2 => $value2){

          $layout = new os_cckLayout($db->_db);
          $layout->load($layoutArray[$key2]);
          $bootstrap_version = $item_session->get( 'bootstrap','2');
          $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
          // $layout_params = unserialize($layout->params);
          $extra_fields_list = $entityFieldLists[$value];
          foreach($extra_fields_list as $Fieldvalue){
            $params = new JRegistry;
            $params->loadString($Fieldvalue->params);
            if($params->get('show_in_reviews', '') == 'yes' && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
              if( isset($uniqFieldsArray[$Fieldvalue->fid] ) ) continue; //need for add fields only 1 time
              $uniqFieldsArray[$Fieldvalue->fid] = $Fieldvalue->fid ;
              $fieldNames[$key]['ent_name'] = $Fieldvalue->fk_eid;
              $fieldNames[$key]['field_type'] = $Fieldvalue->field_type;
              $fieldNames[$key]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
              $show_fields[$value][]= $Fieldvalue;
            }
          }
        }
      }
      ksort($show_fields);
    }
    // $show_fields = array_unique($show_fields);
    $item_session->set('field_names', $fieldNames);

    //************* begin add for sub category  *************
    $categories[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_CATEGORIES'),'value','text');
    $options = $categories;
    $id = 0;
    $fromSearch=0;
    $list = CCK_CAT_Utils::categoryArray('com_os_cck',$fromSearch);
    $cat = new os_cckCategory($db->_db);
    $cat->load($id);

    $this_treename = '';
    foreach ($list as $item) {
      if ($this_treename) {
        if ($item->cid != $cat->cid && strpos($item->title, $this_treename) === false) {
          $options[] = JHTML::_('select.option',$item->cid, $item->title,'value','text');
        }
      } else {
        if ($item->cid != $cat->cid) {
          $options[] = JHTML::_('select.option',$item->cid, $item->title,'value','text');
        } else {
          $this_treename = "$item->title/";
        }
      }
    }
    $clist = JHTML::_('select.genericlist',$options, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); //new nik edit

    $pubmenu[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
    $pubmenu[] = JHTML::_('select.option','not_pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_PUBLIC'),'value','text');
    $pubmenu[] = JHTML::_('select.option','pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_PUBLIC'),'value','text');
    $publist = JHTML::_('select.genericlist',$pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);

    AdminViewReview :: showReviews($option, $rows, $clist, $publist, $search, $pageNav, $sort_arr, $show_fields,$entity_list);
  }


  static function editReview($option, $bid){
    global $db, $user, $os_cck_state, $entityFieldLists;
    $db = new os_cckDb();
    /////new
    $entityInstance = new os_cckEntityInstance($db->_db);
    $entityInstance->load(intval($bid));
    if(!$entityInstance->eiid){
      return;
    }
    if(intval($bid)){
      $query="UPDATE #__os_cck_entity_instance SET notreaded=0 WHERE eiid=".intval($bid);
      $db->setQuery($query);
      $db->execute();
    }

    $entityInstance->checkout($user->id);

    $layout = new os_cckLayout($db->_db);
    $layout->load($entityInstance->fk_lid);
    $bootstrap_version = '2';
    $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }

    $layout_params = unserialize($layout->params);
    $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child = $entityInstance->eiid";
    $db->setQuery($query);


    $layout_params['parent_instance'] = $db->loadResult();
    $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];

    AdminViewReview::editReview($option, $entityInstance, $layout,$layout_params);
    
  }

  static function showParentInstance($option, $bid){
    global $db, $entityFieldLists, $app, $doc;
    $db = new os_cckDb();
    $entityInstance = new os_cckEntityInstance($db->_db);
    $entityInstance->load(intval($bid));
    if(!$entityInstance->eiid){
      return;
    }
    $layout = new os_cckLayout($db->_db);
    $layout->load($layout->getDefaultLayout($entityInstance->fk_eid, 'instance'));
    $bootstrap_version = '2';
    $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
    $layout_params = unserialize($layout->params);
    $layout->field_list = $entityFieldLists[$entityInstance->fk_eid];
    AdminViewReview :: showParentInstance($option, $entityInstance, $layout,$layout_params);
  }

  static function saveReview($option){
    global $db, $my, $task, $app, $os_cck_state, $entityFieldLists;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $post = $_POST;
    $post = protectInjectionWithoutQuote($post, '', 'STRING', true);
    $instance = new os_cckEntityInstance($db->_db);

   
    $data = $post;
    $data['fields_data'] = array();
    foreach ($post as $key => $var) {
      if (strpos($key, 'fi_') === 0) $data['fields_data'][str_replace('fi_', '', $key)] = $var;
    }
    if ($post['id'] != 0) {
      $instance->load($post['id']);
      $data['changed'] = date("Y-m-d H:i:s");
    } else {
      $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".$post['lay_type'];
      $db->setQuery($query);
      $data['fk_eid'] = $db->loadResult();
      $data['created'] = date("Y-m-d H:i:s");
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $data['title'] = protectInjectionWithoutQuote('title','');
    $data['asset_id'] = 0;
    if(!isset($post['categories'])){
      $data['categories'] = array();
    }
    //$data['fk_userid'] = $my->id; -- edit review from other Man - so not change this
    if(protectInjectionWithoutQuote('lay_type',''))
      $data['fk_lid'] = protectInjectionWithoutQuote('lay_type');
    $data['published'] = 1;
    $data['approved'] = 1;
    $data['checked_out'] = 0;
    $data['checked_out_time'] = '0000-00-00 00:00:00';
    $data['teid'] = 0;
    $instance->fields_data = '';
    $instance->categories = '';
    if (!$instance->bind($data)) {
      echo "<script> alert('Entity with this name alredy exist'); 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 ;
    }
    //entity_name, entity_tbale_name
    $entitty = new os_cckEntity($db->_db);
    $entitty->load($instance->fk_eid);
    $instance->_entity_name = $entitty->name;
    $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;
    $instance->_field_list = $entitty->getFieldList();
    if(is_array($instance->fields_data) && !empty($instance->fields_data)){
        foreach($instance->fields_data as $k => $val){
            foreach ($instance->_field_list as $temp_field){
                if($k == $temp_field->db_field_name && $temp_field->field_type == 'text_textarea'){
                    $instance->fields_data[$k] = stripslashes($val);
                    $instance->fields_data[$k] = trim($instance->fields_data[$k], "'");
                }
            }
        }
    }

    $query = "SELECT c.title,c.lid,c.params,c.fk_eid FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n WHERE c.lid = $instance->fk_lid  limit 1 ";
    $db->setQuery($query);
    $layout = $db->loadObjectList();
    $layout_params = unserialize($layout[0]->params);
    $instance->_layout_params = $layout_params['fields'];
    $instance->fk_lid = $layout[0]->lid;
    if ($task != 'cancel_review' && !$instance->require_check()) {
      echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
      exit ();
    }

    if($task == 'cancel_review'){
      $instance->checkin();
      $app->redirect("index.php?option={$option}&task=manage_review");
      return;
    }
    
    $instance->store();
    
    $fields_for_mail = array();
    $parent_instance_id = $instance->getParentInstance();

    // $query = "INSERT INTO #__os_cck_child_parent_connect (media_type,fid_parent,fid_child)"
    //         ."\n VALUES ('instance',$parent_instance_id,$instance->eiid)";
    // $db->setQuery($query);
    // $db->execute();

    
    $layout = new os_cckLayout($db->_db);
    $layout->load($instance->fk_lid);
    $layout_html = $layout->getLayoutHtml('3');


    $layout_mail = new os_cckLayout($db->_db);
    $layout_mail->load($instance->fk_lid);
    // $mail = unserialize($layout_mail->mail);
    
    //old code - where we can have ONE mail field in layout
    if(!isset($layout_params['mail_fields']) && strpos($layout_html,"{|f-cck_mail|}")){
        $app->enqueueMessage(cck_lang_text("Email send not work. Please create new email fieled in this layout!!!"), 'warning');
    }


    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ){
        $mail_data = array(); 
        $mail_data['mail'] = unserialize($layout_mail->mail) ;

        $fields_for_mail = getInstanceFieldsData( $instance->eiid);
        $mail_data['request_instance_fields_data'] = $fields_for_mail ;

        $mail_data['mail_fields'] = $layout_params['mail_fields'] ;
        $mail_data['mail_event'] = "change";

        $parent_fields_data = array();
        $parentIdsArr = array();
        $price_fields_assoc = array();
        if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
            && isset($parent_instance_id) && $parent_instance_id != 0 ){

            $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc );
            
        } 
        //in add_instance $parent_fields_data - empty
        $mail_data['parent_instances_fields_data'] = $parent_fields_data ;
        cckSendMailEvent($mail_data, $parentIdsArr, $instance );

    }    

    $app->redirect("index.php?option={$option}&task=manage_review");
  }


  static function removeReviews($bid, $option){
    global $db, $app;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if (!is_array($bid) || count($bid) < 1) {
      echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
      exit;
    }
    if (count($bid)) {
      foreach ($bid as $id) {
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($id);
        $instance->delete();
      }
    }
    $app->redirect("index.php?option={$option}&task=manage_review");
  }

  static function publishReviews($bid, $publish, $option){
    global $db, $my, $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(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $catid = mosGetParam($_POST, 'catid', array(0));
    if (!is_array($bid) || count($bid) < 1) {
      $action = $publish ? 'publish' : 'unpublish';
      echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
      exit;
    }
    foreach ($bid as $eiid){
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($eiid);
        $instance->publishInstance($publish);
    }
//    $bids = implode(',', $bid);
//    
//    $query  = $db->setQuery("UPDATE #__os_cck_entity_instance SET published='$publish'"
//                    . "\n WHERE eiid IN ($bids) AND (checked_out=0 OR (checked_out='$my->id'))");
//    try {
//        $db->execute();
//    } catch (RuntimeException $e) {
//        echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
//        exit ();
//    }
////    if (!$db->execute()) {
////      echo "<script> alert('" . addslashes($db->getErrorMsg()) . "'); window.history.go(-1); </script>\n";
////      exit ();
////    }
//    if (count($bid) == 1) {
//      $instance = new os_cckEntityInstance($db->_db);
//      $instance->checkin($bid[0]);
//    }
    $app->redirect("index.php?option={$option}&task=manage_review");
  }

  static function approveReviews($bid, $publish, $option){
    global $db, $my, $app, $os_cck_state;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $catid = mosGetParam($_POST, 'catid', array(0));
    if (!is_array($bid) || count($bid) < 1) {
      $action = $publish ? 'approve' : 'unapprove';
      echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
      exit;
    }
//    $bids = implode(',', $bid);
    if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
    foreach ($bid as $eiid){
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($eiid);
        $instance->approvInstance($publish);
    }
//    $db->setQuery("UPDATE #__os_cck_entity_instance SET approved='$publish'"
//                    . "\n WHERE eiid IN ($bids) AND (checked_out=0 OR (checked_out='$my->id'))");
//    try {
//        $db->execute();
//    } catch (RuntimeException $e) {
//        echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
//        exit ();
//    }
//    
//    if (count($bid) == 1) {
//      $instance = new os_cckEntityInstance($db->_db);
//      $instance->checkin($bid[0]);
//    }
    $app->redirect("index.php?option={$option}&task=manage_review");
  }

  /**
   * Cancels an edit operation
   * @param string - The current author option
   */
  static function cancelReview($option){
    global $db,$app;
    $db = new os_cckDb();
    if(protectInjectionWithoutQuote('id','')){
      $row = new os_cckEntityInstance($db->_db);
      $row->load($_REQUEST['id']);
      $row->checkin();
    }
    $app->redirect("index.php?option={$option}&task=manage_review");
  }

}
