<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Content class
 */

class Content extends MY_Controller
{

    /**
     * 관리자 페이지 상의 현재 디렉토리입니다
     * 페이지 이동시 필요한 정보입니다
     */
    public $pagedir = 'contents/content';

    /**
     * 모델을 로딩합니다
     */
    protected $models = array('Contents', 'Upload_file', 'Apps', 'Contents_category', 'Contents_tag', 'Crawl_list', 'Contents_bookmark', 'Contents_like', 'Contents_comment');

    /**
     * 이 컨트롤러의 메인 모델 이름입니다
     */
    protected $modelname = 'Contents_model';

    /**
     * 헬퍼를 로딩합니다
     */
    protected $helpers = array('form', 'array', 'dhtml_editor');

    function __construct()
    {
        parent::__construct();

        /**
         * 라이브러리를 로딩합니다
         */
        $this->load->library(array('pagination', 'querystring'));
    }

    /**
     * 목록을 가져오는 메소드입니다
     */
    public function index()
    {

		$this->accesslevel->check_admin('read');

        $view = array();
        $view['view'] = array();

        /**
         * 페이지에 숫자가 아닌 문자가 입력되거나 1보다 작은 숫자가 입력되면 에러 페이지를 보여줍니다.
         */
        $param =& $this->querystring;

		$view['view']['sort'] = array(
            'con_id' => $param->sort('con_id', 'desc'),
            'con_sort' => $param->sort('con_sort', 'desc'),
            'con_published_at' => $param->sort('con_published_at', 'desc'),
            'con_hit' => $param->sort('con_hit', 'desc'),
        );



		$page = (((int) $this->input->get('page')) > 0) ? ((int) $this->input->get('page')) : 1;
        $findex = $this->input->get('findex') ? $this->input->get('findex') : 'con_published_at';
        $forder = $this->input->get('forder', null, 'desc');
        $sfield = $this->input->get('sfield', null, '');
        $skeyword = $this->input->get('skeyword', null, '');

        $per_page = admin_listnum();
        $offset = ($page - 1) * $per_page;

        /**
         * 게시판 목록에 필요한 정보를 가져옵니다.
         */
        $this->{$this->modelname}->allow_search_field = array('app_id','con_sort','con_title','con_content'); // 검색이 가능한 필드
        $this->{$this->modelname}->search_field_equal = array('app_id','con_sort'); // 검색중 like 가 아닌 = 검색을 하는 필드
        $this->{$this->modelname}->allow_order_field = array('con_id', 'con_sort', 'con_published_at', 'con_hit', 'con_like'); // 정렬이 가능한 필드
		$where = array('is_del' => '0');
		$like = array();
		if ($this->input->get('app_id')) {
			$where['contents.app_id'] = $this->input->get('app_id');
		}
		if ($this->input->get('tag_name')) {
			$where['contents_tag.tag_name'] = $this->input->get('tag_name');
		}
		if ($this->input->get('cat_id')) {
			$where['contents.cat1_id'] = $this->input->get('cat_id');
		}
		if ($this->input->get('site_key')) {
			$where['crawl_list.site_key'] = $this->input->get('site_key');
		}
		if ($this->input->get('crawl_category_name')) {
			$where['crawl_list.crawl_category_name'] = $this->input->get('crawl_category_name');
		}
		if ($this->input->get('con_title')) {
			$like['contents.con_title'] = $this->input->get('con_title');
		}
		if ($this->input->get('con_content')) {
			$like['contents.con_content'] = $this->input->get('con_content');
		}
		if ($this->input->get('start_date')) {
			$where['contents.con_published_at >='] = $this->input->get('start_date');
		}
		if ($this->input->get('end_date')) {
			$where['contents.con_published_at <='] = $this->input->get('end_date');
		}
		if ($this->input->get('is_push') == 'Y') {
			$like['contents.is_push'] = '1';
		}
		if ($this->input->get('is_push') == 'N') {
			$like['contents.is_push'] = '0';
		}
        $result = $this->{$this->modelname}
            ->get_admin_list($per_page, $offset, $where, $like, $findex, $forder, $sfield, $skeyword);

        $list_num = $result['total_rows'] - ($page - 1) * $per_page;
        if (element('list', $result)) {
            foreach (element('list', $result) as $key => $val) {
                $result['list'][$key]['num'] = $list_num--;
				if (element('cat1_id', $val)) {
					$result['list'][$key]['category1'] = $this->Contents_category_model->get_one(element('cat1_id', $val));
				}
				if (element('cat2_id', $val)) {
		            $result['list'][$key]['category2'] = $this->Contents_category_model->get_one(element('cat2_id', $val));
				}
				$tagwhere = array(
					'con_id' => element('con_id', $val),
				);
	            $result['list'][$key]['tags'] = $this->Contents_tag_model->get('', '', $tagwhere);
				if (element('site_type', $val) == '1') {
					if (element('crawl_category', $val)) {
						$result['list'][$key]['origin_link'] = 'http://m.blog.naver.com/PostList.nhn?blogId=' . element('site_key', $val) . '&categoryNo=' . element('crawl_category', $val);
					} else {
						$result['list'][$key]['origin_link'] = 'http://m.blog.naver.com/' . element('site_key', $val);
					}
				}
				if (element('site_type', $val) == '2') {
					$result['list'][$key]['origin_link'] = 'ttp://m.post.naver.com/my.nhn?memberNo=' . element('site_key', $val);
				}
				if (element('site_type', $val) == '3') {
					if (element('crawl_category', $val)) {
						$result['list'][$key]['origin_link'] = 'https://www.vingle.net/collections/' . element('crawl_category', $val);
					} else {
						$result['list'][$key]['origin_link'] = 'https://www.vingle.net/' . element('site_key', $val);
					}
				}
				if (element('site_type', $val) == '4') {
					$result['list'][$key]['origin_link'] = 'https://story.kakao.com/ch/' . element('site_key', $val);
				}
				/*
				if (element('cat3_id', $val)) {
		            $result['list'][$key]['category3'] = $this->Contents_category_model->get_one(element('cat3_id', $val));
				}
				if (element('cat4_id', $val)) {
					$result['list'][$key]['category4'] = $this->Contents_category_model->get_one(element('cat4_id', $val));
				}
				*/
            }
        }

        $view['view']['data'] = $result;
        $view['view']['applist'] = $this->Apps_model->app_list();
        $view['view']['crawl_site'] = $this->Crawl_list_model->get_by_site();
        $view['view']['crawl_category'] = $this->Crawl_list_model->get_by_category();
		if ($this->input->get('app_id')) {
			$view['view']['app_category'] = $this->Contents_category_model->cat_list($this->input->get('app_id'));
		}

        /**
         * primary key 정보를 저장합니다
         */
        $view['view']['primary_key'] = $this->{$this->modelname}->primary_key;

        /**
         * 페이지네이션을 생성합니다
         */
        $config['base_url'] = admin_url($this->pagedir) . '?' . $param->replace('page');
        $config['total_rows'] = $result['total_rows'];
        $config['per_page'] = $per_page;
        $this->pagination->initialize($config);
        $view['view']['paging'] = $this->pagination->create_links();
        $view['view']['page'] = $page;

        /**
         * 쓰기 주소, 삭제 주소등 필요한 주소를 구합니다
         */
        $search_option = array('con_title' => '제목','con_content' => '내용');
        $view['view']['skeyword'] = ($sfield && array_key_exists($sfield, $search_option)) ? $skeyword : '';
        $view['view']['search_option'] = search_option($search_option, $sfield);
        $view['view']['listall_url'] = admin_url($this->pagedir);
        $view['view']['write_url'] = admin_url($this->pagedir . '/write');
        $view['view']['publish_update_url'] = admin_url($this->pagedir . '/publishupdate/?' . $param->output());
        $view['view']['publish_update2_url'] = admin_url($this->pagedir . '/publishupdate2/?' . $param->output());
        $view['view']['publish_update3_url'] = admin_url($this->pagedir . '/publishupdate3/?' . $param->output());
        $view['view']['push_update_url'] = admin_url($this->pagedir . '/pushupdate/?' . $param->output());
        $view['view']['push_update2_url'] = admin_url($this->pagedir . '/pushupdate2/?' . $param->output());
        $view['view']['sort_update_url'] = admin_url($this->pagedir . '/sortupdate/?' . $param->output());
        $view['view']['list_delete_url'] = admin_url($this->pagedir . '/listdelete/?' . $param->output());

        /**
         * 어드민 레이아웃을 정의합니다
         */
        $layoutconfig = array('layout' => 'layout', 'skin' => 'index');
        $view['layout'] = $this->layoutlib->admin($layoutconfig, $this->configlib->get_device_view_type());
        $this->data = $view;
        $this->layout = element('layout_skin_file', element('layout', $view));
        $this->view = element('view_skin_file', element('layout', $view));
    }


    /**
     * 게시판 글쓰기 또는 수정 페이지를 가져오는 메소드입니다
     */
    public function write($pid = 0)
    {

		$this->accesslevel->check_admin('read');

		$view = array();
        $view['view'] = array();


        /**
         * 프라이머리키에 숫자형이 입력되지 않으면 에러처리합니다
         */
        if ($pid) {
            $pid = (int) $pid;
            if (empty($pid) OR $pid < 1) {
                show_404();
            }
        }
        $primary_key = $this->{$this->modelname}->primary_key;

        /**
         * 수정 페이지일 경우 기존 데이터를 가져옵니다
         */
        $getdata = array();
        if ($pid) {
            $getdata = $this->{$this->modelname}->get_one($pid);
			if (element('is_del', $getdata)) {
				alert('삭제된 게시글입니다');
			}
        } else if ($this->input->get('app_id')) {
			$getdata['app_id'] = $this->input->get('app_id');
		}

        /**
         * Validation 라이브러리를 가져옵니다
         */
        $this->load->library('form_validation');

		$view['view']['upload_file_count'] = $upload_file_count = 5;


        /**
         * 전송된 데이터의 유효성을 체크합니다
         */
        $config = array(
			array('field' => 'app_id',	'label' => '어플이름',	'rules' => 'trim|required'),
			array('field' => 'cat1_id',	'label' => '1차분류',	'rules' => 'trim|required'),
			array('field' => 'cat2_id',	'label' => '2차분류',	'rules' => 'trim'),
			//array('field' => 'cat3_id',	'label' => '소분류',	'rules' => 'trim'),
			//array('field' => 'cat4_id',	'label' => '세분류',	'rules' => 'trim'),
			array('field' => 'con_sort',	'label' => '정렬순서',	'rules' => 'trim|required'),
			array('field' => 'con_title',	'label' => '제목',	'rules' => 'trim|required'),
			array('field' => 'con_content',	'label' => '내용',	'rules' => 'trim|required'),
			array('field' => 'user_name',	'label' => '작성자명',	'rules' => 'trim|required'),
			array('field' => 'con_hit',	'label' => '조회수',	'rules' => 'trim|required'),
			array('field' => 'con_like',	'label' => 'Like 수',	'rules' => 'trim|required'),
			array('field' => 'con_published_at',	'label' => '예약발행일자',	'rules' => 'trim'),
        );
        $this->form_validation->set_rules($config);
        $form_validation = $this->form_validation->run();
        $file_error = '';


        $uploadfiledata = '';
        $uploadfiledata2 = '';
        if ($upload_file_count > 0 && $form_validation) {
            $this->load->library('upload');
            if (isset($_FILES) && isset($_FILES['upload_file']) && isset($_FILES['upload_file']['name']) && is_array($_FILES['upload_file']['name'])) {
                $filecount = count($_FILES['upload_file']['name']);
                $upload_path = config_item('uploads_dir') . '/files/';
                if (is_dir($upload_path) === false) {
                    mkdir($upload_path, 0707);
                    $file = $upload_path . 'index.php';
                    $f = @fopen($file, 'w');
                    @fwrite($f, '');
                    @fclose($f);
                    @chmod($file, 0644);
                }
                $upload_path .= cdate('Y') . '/';
                if (is_dir($upload_path) === false) {
                    mkdir($upload_path, 0707);
                    $file = $upload_path . 'index.php';
                    $f = @fopen($file, 'w');
                    @fwrite($f, '');
                    @fclose($f);
                    @chmod($file, 0644);
                }
                $upload_path .= cdate('m') . '/';
                if (is_dir($upload_path) === false) {
                    mkdir($upload_path, 0707);
                    $file = $upload_path . 'index.php';
                    $f = @fopen($file, 'w');
                    @fwrite($f, '');
                    @fclose($f);
                    @chmod($file, 0644);
                }

                foreach ($_FILES['upload_file']['name'] as $i => $value) {
                    if ($value) {
                        $uploadconfig = '';
                        $uploadconfig['upload_path'] = $upload_path;
                        $uploadconfig['allowed_types'] = '*';
                        $uploadconfig['max_size'] = 10240;
                        $uploadconfig['encrypt_name'] = true;

                        $this->upload->initialize($uploadconfig);
                        $_FILES['userfile']['name'] = $_FILES['upload_file']['name'][$i];
                        $_FILES['userfile']['type'] = $_FILES['upload_file']['type'][$i];
                        $_FILES['userfile']['tmp_name'] = $_FILES['upload_file']['tmp_name'][$i];
                        $_FILES['userfile']['error'] = $_FILES['upload_file']['error'][$i];
                        $_FILES['userfile']['size'] = $_FILES['upload_file']['size'][$i];
                        if ($this->upload->do_upload()) {
                            $filedata = $this->upload->data();

                            $uploadfiledata[$i]['ufi_filename'] = cdate('Y') . '/' . cdate('m') . '/' . element('file_name', $filedata);
                            $uploadfiledata[$i]['ufi_originname'] = element('orig_name', $filedata);
                            $uploadfiledata[$i]['ufi_filesize'] = intval(element('file_size', $filedata) * 1024);
                            $uploadfiledata[$i]['ufi_width'] = element('image_width', $filedata) ? element('image_width', $filedata) : 0;
                            $uploadfiledata[$i]['ufi_height'] = element('image_height', $filedata) ? element('image_height', $filedata) : 0;
                            $uploadfiledata[$i]['ufi_type'] = str_replace('.', '', element('file_ext', $filedata));
                            $uploadfiledata[$i]['is_image'] = element('is_image', $filedata) ? element('is_image', $filedata) : 0;
                        } else {
                            $file_error = $this->upload->display_errors();
                            break;
                        }
                    }
                }
            }
            if (isset($_FILES) && isset($_FILES['upload_file_update'])
                && isset($_FILES['upload_file_update']['name'])
                && is_array($_FILES['upload_file_update']['name'])
                && $file_error === '') {
                $filecount = count($_FILES['upload_file_update']['name']);
                $upload_path = config_item('uploads_dir') . '/files/';
                if (is_dir($upload_path) === false) {
                    mkdir($upload_path, 0707);
                    $file = $upload_path . 'index.php';
                    $f = @fopen($file, 'w');
                    @fwrite($f, '');
                    @fclose($f);
                    @chmod($file, 0644);
                }
                $upload_path .= cdate('Y') . '/';
                if (is_dir($upload_path) === false) {
                    mkdir($upload_path, 0707);
                    $file = $upload_path . 'index.php';
                    $f = @fopen($file, 'w');
                    @fwrite($f, '');
                    @fclose($f);
                    @chmod($file, 0644);
                }
                $upload_path .= cdate('m') . '/';
                if (is_dir($upload_path) === false) {
                    mkdir($upload_path, 0707);
                    $file = $upload_path . 'index.php';
                    $f = @fopen($file, 'w');
                    @fwrite($f, '');
                    @fclose($f);
                    @chmod($file, 0644);
                }

                foreach ($_FILES['upload_file_update']['name'] as $i => $value) {
                    if ($value) {
                        $uploadconfig = '';
                        $uploadconfig['upload_path'] = $upload_path;
                        $uploadconfig['allowed_types'] = '*';
                        $uploadconfig['max_size'] = 10240;
                        $uploadconfig['encrypt_name'] = true;
                        $this->upload->initialize($uploadconfig);
                        $_FILES['userfile']['name'] = $_FILES['upload_file_update']['name'][$i];
                        $_FILES['userfile']['type'] = $_FILES['upload_file_update']['type'][$i];
                        $_FILES['userfile']['tmp_name'] = $_FILES['upload_file_update']['tmp_name'][$i];
                        $_FILES['userfile']['error'] = $_FILES['upload_file_update']['error'][$i];
                        $_FILES['userfile']['size'] = $_FILES['upload_file_update']['size'][$i];
                        if ($this->upload->do_upload()) {
                            $filedata = $this->upload->data();

                            $olduploadfile = $this->Upload_file_model->get_one($i);
                            if ((int) element('origin_id', $olduploadfile) !== (int) element('con_id', $getdata)) {
                                alert('잘못된 접근입니다');
                            }
                            @unlink(config_item('uploads_dir') .  '/files/' . element('ufi_filename', $oldpostfile));

                            $uploadfiledata2[$i]['ufi_id'] = $i;
                            $uploadfiledata2[$i]['ufi_filename'] = cdate('Y') . '/' . cdate('m') . '/' . element('file_name', $filedata);
                            $uploadfiledata2[$i]['ufi_originname'] = element('orig_name', $filedata);
                            $uploadfiledata2[$i]['ufi_filesize'] = intval(element('file_size', $filedata) * 1024);
                            $uploadfiledata2[$i]['ufi_width'] = element('image_width', $filedata)
                                ? element('image_width', $filedata) : 0;
                            $uploadfiledata2[$i]['ufi_height'] = element('image_height', $filedata)
                                ? element('image_height', $filedata) : 0;
                            $uploadfiledata2[$i]['ufi_type'] = str_replace('.', '', element('file_ext', $filedata));
                            $uploadfiledata2[$i]['is_image'] = element('is_image', $filedata)
                                ? element('is_image', $filedata) : 0;
                        } else {
                            $file_error = $this->upload->display_errors();
                            break;
                        }
                    }
                }
            }
        }


        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($form_validation === false OR $file_error !== '') {

            $view['view']['applist'] = $applist = $this->Apps_model->app_list();


			if ( ! $pid) {
				if ($this->input->get('app_id')) {
					$getdata['app_id'] = $app_id = $this->input->get('app_id');
					$getdata['app_name'] = html_escape(element('app_name', element($app_id, $applist)));
		            $view['view']['catlist'] = $catlist = $this->Contents_category_model->cat_list($app_id);
					$max_sort = $this->{$this->modelname}->select_max_sort($app_id);
					$getdata['con_sort'] = $max_sort + 1;
					$where = array(
						'cat_parent' => '0',
						'app_id' => $app_id,
					);
					$getdata['cat_1'] = $this->Contents_category_model->get('', '', $where, '', '', 'cat_sort', 'desc');
				} else {
					alert('잘못된 접근입니다');
				}
			} else {
				$app_id = element('app_id', $getdata);
				$getdata['app_name'] = html_escape(element('app_name', element($app_id, $applist)));
				$getdata['crawl_list'] = $this->Crawl_list_model->get_one(element('crawl_id', $getdata));
				$view['view']['catlist'] = $catlist = $this->Contents_category_model->cat_list($app_id);
				$where = array(
					'cat_parent' => '0',
					'app_id' => $app_id,
				);
				$getdata['cat_1'] = $this->Contents_category_model->get('', '', $where, '', '', 'cat_sort', 'desc');

				$tagwhere = array(
					'app_id' => $app_id,
					'con_id' => element('con_id', $getdata),
				);
				$tags = $this->Contents_tag_model->get('', '', $tagwhere);
				$tagdata = '';
				if ($tags) {
					foreach ($tags as $tval) {
						if ($tagdata) $tagdata .= ',';
						$tagdata .= element('tag_name', $tval);
					}
				}
				$getdata['tags'] = $tagdata;

			}
            $view['view']['data'] = $getdata;

            /**
             * primary key 정보를 저장합니다
             */
            $view['view']['primary_key'] = $primary_key;

			if (element('con_id', $getdata)) {
				$uploadwhere = array(
					'origin_table' => 'contents',
					'origin_id' => element('con_id', $getdata),
				);
				$view['view']['file'] = $file = $this->Upload_file_model->get('', '', $uploadwhere, '', '', 'ufi_id', 'ASC');
				if ($file && is_array($file)) {
					foreach ($file as $key => $value) {
						$view['view']['file'][$key]['download_link']
							= site_url('download/downfiles/' . element('ufi_id', $value));
					}
				}
			}

            /**
             * 어드민 레이아웃을 정의합니다
             */
            $layoutconfig = array('layout' => 'layout', 'skin' => 'write');
            $view['layout'] = $this->layoutlib->admin($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));

        } else {
            /**
             * 유효성 검사를 통과한 경우입니다.
             * 즉 데이터의 insert 나 update 의 process 처리가 필요한 상황입니다
             */


            $updatedata = array(
				'app_id'          => $this->input->post('app_id',	null,	''),
				'cat1_id'          => $this->input->post('cat1_id',	null,	''),
				'cat2_id'          => $this->input->post('cat2_id',	null,	''),
				//'cat3_id'          => $this->input->post('cat3_id',	null,	''),
				//'cat4_id'          => $this->input->post('cat4_id',	null,	''),
				'con_sort'          => $this->input->post('con_sort',	null,	''),
				'con_title'          => $this->input->post('con_title',	null,	''),
				'con_content'          => $this->input->post('con_content',	null,	''),
				'user_name'          => $this->input->post('user_name',	null,	''),
				'con_hit'          => $this->input->post('con_hit',	null,	''),
				'con_like'          => $this->input->post('con_like',	null,	''),
            );
			if ($this->input->post('con_published_at')) {
				$updatedata['is_open'] = '1';
				$updatedata['con_published_at'] = $this->input->post('con_published_at');
			} else {
				$updatedata['is_open'] = '0';
				$updatedata['con_published_at'] = null;
			}

            /**
             * 게시물을 수정하는 경우입니다
             */
            if ($this->input->post($primary_key)) {

				$this->accesslevel->check_admin('edit');

				$updatedata['con_updated_at'] = cdate('Y-m-d H:i:s');
                $this->{$this->modelname}->update($this->input->post($primary_key), $updatedata);
				$origin_id = $this->input->post($primary_key);
                $this->session->set_flashdata('message','정상적으로 수정되었습니다');
            } else {

				$this->accesslevel->check_admin('write');
 
                /**
                 * 게시물을 새로 입력하는 경우입니다
                 */

				$updatedata['con_created_at'] = cdate('Y-m-d H:i:s');
				$updatedata['con_updated_at'] = cdate('Y-m-d H:i:s');
				$updatedata['user_id'] = $this->userlib->item('user_id');
                $origin_id = $this->{$this->modelname}->insert($updatedata);
                $this->session->set_flashdata('message','정상적으로 입력되었습니다');
            }

			$deletewhere = array(
				'app_id' => $this->input->post('app_id'),
				'con_id' => $origin_id,
			);
			$this->Contents_tag_model->delete('', $deletewhere);
			if ($this->input->post('tags')) {
				$extag = explode(',', $this->input->post('tags'));
				if ($extag) {
					foreach ($extag as $tag) {
						$taginsert = array(
							'app_id' => $this->input->post('app_id'),
							'con_id' => $origin_id,
							'tag_name' => trim($tag),
						);
						$this->Contents_tag_model->insert($taginsert);
					}
				}
			}


            $file_updated = false;
            $file_changed = false;
            if (is_array($uploadfiledata) && count($uploadfiledata) > 0) {
                foreach ($uploadfiledata as $pkey => $pval) {
                    if ($pval) {
                        $fileupdate = array(
                            'origin_id' => $origin_id,
                            'origin_table' => 'contents',
                            'user_id' => $this->userlib->item('user_id'),
                            'ufi_originname' => element('ufi_originname', $pval),
                            'ufi_filename' => element('ufi_filename', $pval),
                            'ufi_filesize' => element('ufi_filesize', $pval),
                            'ufi_width' => element('ufi_width', $pval),
                            'ufi_height' => element('ufi_height', $pval),
                            'ufi_type' => element('ufi_type', $pval),
                            'ufi_is_image' => element('is_image', $pval),
                            'ufi_datetime' => cdate('Y-m-d H:i:s'),
                            'ufi_ip' => $this->input->ip_address(),
                        );
                        $file_id = $this->Upload_file_model->insert($fileupdate);
                        $file_updated = true;
                    }
                }
                $file_changed = true;
            }
            if (is_array($uploadfiledata2) && count($uploadfiledata2) > 0) {
                foreach ($uploadfiledata2 as $pkey => $pval) {
                    if ($pval) {
                        $fileupdate = array(
                            'user_id' => $this->userlib->item('user_id'),
                            'ufi_originname' => element('ufi_originname', $pval),
                            'ufi_filename' => element('ufi_filename', $pval),
                            'ufi_filesize' => element('ufi_filesize', $pval),
                            'ufi_width' => element('ufi_width', $pval),
                            'ufi_height' => element('ufi_height', $pval),
                            'ufi_type' => element('ufi_type', $pval),
                            'ufi_is_image' => element('is_image', $pval),
                            'ufi_datetime' => cdate('Y-m-d H:i:s'),
                            'ufi_ip' => $this->input->ip_address(),
                        );
                        $this->Upload_file_model->update($pkey, $fileupdate);
                        $file_changed = true;
                    }
                }
            }
            if ($this->input->post('upload_file_del')) {
                foreach ($this->input->post('upload_file_del') as $key => $val) {
                    if ($val === '1' && ! isset($uploadfiledata2[$key])) {
                        $olduploadfile = $this->Upload_file_model->get_one($key);
                        if ( ! element('origin_id', $olduploadfile) OR (int) element('origin_id', $olduploadfile) !== (int) $origin_id) {
                            alert('잘못된 접근입니다.');
                        }
                        @unlink(config_item('uploads_dir') .  '/files/' . element('ufi_filename', $olduploadfile));
                        $this->Upload_file_model->delete($key);
                        $file_changed = true;
                    }
                }
            }


            /**
             * 게시물의 신규입력 또는 수정작업이 끝난 후 목록 페이지로 이동합니다
             */
            $param =& $this->querystring;
            $redirecturl = admin_url($this->pagedir . '?' . $param->output());

            redirect($redirecturl);
        }
    }




    public function copy($type = 'copy')
    {

	    $con_id_list = '';
        if ($this->input->get('chk')) {
            $con_id_list = '';
            $chk_con_id = $this->input->get('chk');
            foreach ($chk_con_id as $val) {
                if (empty($con_id)) {
                    $con_id = $val;
                }
                $con_id_list .= $val . ',';
            }
        }
        if ($this->input->get('con_id_list')) {
            $con_id_list = $this->input->get('con_id_list');
        }
        $view['view']['con_id_list'] = $con_id_list;

        $contents = $this->Contents_model->get_one($con_id);
        $apps = $this->Apps_model->get_one(element('app_id', $contents));
		if ($this->input->get('to_app_id')) {
		$view['view']['catlist'] = $catlist = $this->Contents_category_model->cat_list($this->input->get('to_app_id'));
		}

        if ($type !== 'move') {
            $type = 'copy';
        }
        $view['view']['contents'] = $contents;
        $view['view']['apps'] = $apps;
        $view['view']['typetext'] = $typetext = ($type === 'copy') ? '복사' : '이동';

        $config = array(
            array(
                'field' => 'is_submit',
                'label' => '체크',
                'rules' => 'trim',
            ),
        );
        $this->load->library('form_validation');
        $this->form_validation->set_rules($config);
        $form_validation = $this->form_validation->run();

        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($form_validation === false OR ! $this->input->post('is_submit')) {


            $result = $this->Apps_model->app_list();
            $view['view']['list'] = $result;

        
            /**
             * 레이아웃을 정의합니다
             */
            $page_title = element('con_title', $contents) . ' > 게시물 ' . $typetext;
            $layoutconfig = array('layout' => 'layout_popup', 'skin' => 'copy');
            $view['layout'] = $this->layoutlib->admin($layoutconfig, $this->configlib->get_device_view_type());
            $this->data = $view;
            $this->layout = element('layout_skin_file', element('layout', $view));
            $this->view = element('view_skin_file', element('layout', $view));

        } else {

            $old_app_id = element('app_id', $apps);
            $new_app_id = (int) $this->input->post('to_app_id');
            $new_cat_id = (int) $this->input->post('to_cat_id');

            if ($con_id_list) {
                $arr = explode(',', $con_id_list);
                if ($arr) {
                    $arrsize = count($arr);
                    for ($k= $arrsize-1; $k>= 0; $k--) {
                        $con_id = element($k, $arr);
                        if (empty($con_id)) {
                            continue;
                        }

                        $contents = $this->Contents_model->get_one($con_id);
                        $apps = $this->Apps_model->get_one(element('app_id', $contents));

                        if ($type === 'copy') {
                            // 게시글 복사

                            $insertdata = array(
                                'app_id' => $new_app_id,
                                'con_sort' => $contents['con_sort'],
                                'cat1_id' => $new_cat_id,
                                'crawl_id' => $contents['crawl_id'],
                                'user_id' => $contents['user_id'],
                                'user_name' => $contents['user_name'],
                                'con_title' => $contents['con_title'],
                                'con_content' => $contents['con_content'],
                                'con_origin_url' => $contents['con_origin_url'],
                                'con_created_at' => $contents['con_created_at'],
                                'con_updated_at' => $contents['con_updated_at'],
                                'con_published_at' => $contents['con_published_at'],
                                'con_origin_created_at' => $contents['con_origin_created_at'],
                                'is_open' => $contents['is_open'],
                                'is_del' => $contents['is_del'],
                            );
                            $new_con_id = $this->Contents_model->insert($insertdata);


                            $conwhere = array(
                                'con_id' => $con_id,
                            );
                            $tagdata = $this->Contents_tag_model->get('', '', $conwhere);
                            if ($tagdata) {
                                foreach ($tagdata as $data) {
                                    $taginsert = array(
                                        'con_id' => $new_con_id,
                                        'app_id' => $new_app_id,
                                        'tag_name' => $data['tag_name'],
                                    );
                                    $this->Contents_tag_model->insert($taginsert);
                                }
                            }

                        }
                        if ($type === 'move') {

                            // post table update
                            $postupdate = array(
                                'app_id' => $new_app_id,
                                'cat1_id' => $new_cat_id,
                                'cat2_id' => '0',
                            );

                            $this->Contents_model->update($con_id, $postupdate);


                            $dataupdate = array(
                                'app_id' => $new_app_id,
                            );
                            $where = array(
                                'con_id' => $con_id,
                            );
                            $this->Contents_bookmark_model->update('', $dataupdate, $where);
                            $this->Contents_comment_model->update('', $dataupdate, $where);
                            $this->Contents_like_model->update('', $dataupdate, $where);
                            $this->Contents_tag_model->update('', $dataupdate, $where);

                        }
                    }
                }
            }


            $alert = ($type === 'copy') ? '게시글 복사가 완료되었습니다' : '게시글 이동이 완료되었습니다';
            alert_refresh_close($alert);
		}
    }

    public function publishupdate()
    {
		$now = cdate('Y-m-d H:i:s');
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
					$updatedata = array(
						'is_open' => '1',
						'con_published_at' => cdate('Y-m-d H:i:s', time() - 3),
					);
					$this->db->where('con_id', $val);
					$this->db->where("( is_open = 0 OR con_published_at >'$now' )");
					$this->db->update('contents', $updatedata);
                }
            }
        }

        $this->session->set_flashdata('message','발행이 되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }

    public function publishupdate2()
    {
		$now = cdate('Y-m-d H:i:s');
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {

		            $content = $this->Contents_model->get_one($val);
		            $category = $this->Contents_category_model->get_one(element('cat1_id', $content));
					$time = element('cat_publish_time', $category) ? element('cat_publish_time', $category) : '00:00:00';
					$publish_at = $this->input->post('reserve_publish_date') . ' ' . $time;

					$updatedata = array(
						'is_open' => '1',
						'con_published_at' => $publish_at,
					);
					$this->db->where('con_id', $val);
					$this->db->where("( is_open = 0 OR con_published_at >'$now' )");
					$this->db->update('contents', $updatedata);
                }
            }
        }

        $this->session->set_flashdata('message','발행이 되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }


    public function publishupdate3()
    {
		$now = cdate('Y-m-d H:i:s');
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
					$updatedata = array(
						'is_open' => '0',
						'con_published_at' => null,
					);
					$this->db->where('con_id', $val);
					$this->db->update('contents', $updatedata);
                }
            }
        }

        $this->session->set_flashdata('message','발행이 취소되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }


    public function pushupdate()
    {
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
					$updatedata = array(
						'is_push' => '1',
					);
					$this->db->where('con_id', $val);
					$this->db->update('contents', $updatedata);
                }
            }
        }

        $this->session->set_flashdata('message','푸쉬등록이 완료되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }

    public function pushupdate2()
    {
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
					$updatedata = array(
						'is_push' => '0',
					);
					$this->db->where('con_id', $val);
					$this->db->update('contents', $updatedata);
                }
            }
        }

        $this->session->set_flashdata('message','푸쉬해제가 완료되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }

    /**
     * 목록 페이지에서 선택삭제를 하는 경우 실행되는 메소드입니다
     */
    public function sortupdate()
    {
		$origin_sort = array();
		$key = 0;
		if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
                    $res = $this->{$this->modelname}->get_one($val, 'con_sort');
					$origin_sort[$key] = element('con_sort', $res);
					$key++;
                }
            }
        }
		shuffle($origin_sort);

		$key = 0;
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
					$con_sort = element($key, $origin_sort);
					$updatedata = array(
						'con_sort' => $con_sort,
					);
                    $this->{$this->modelname}->update($val, $updatedata);
					$key++;
                }
            }
        }

        $this->session->set_flashdata('message','정렬순서가 변경되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }

    /**
     * 목록 페이지에서 선택삭제를 하는 경우 실행되는 메소드입니다
     */
    public function listdelete()
    {

		$this->accesslevel->check_admin('delete');
 
		 /**
         * 체크한 게시물의 삭제를 실행합니다
         */
        if ($this->input->post('chk') && is_array($this->input->post('chk'))) {
            foreach ($this->input->post('chk') as $val) {
                if ($val) {
                    $this->{$this->modelname}->update($val, array('is_del' => '1'));
                }
            }
        }

        /**
         * 삭제가 끝난 후 목록페이지로 이동합니다
         */
        $this->session->set_flashdata('message','정상적으로 삭제되었습니다');
        $param =& $this->querystring;
        $redirecturl = admin_url($this->pagedir . '?' . $param->output());

        redirect($redirecturl);
    }


    public function getselectcategory($app_id = '', $parent_id = '', $depth = '')
    {
		if ( ! $app_id) return;
		if ( ! $parent_id) return;
		if ( ! $depth) return;
		if ($depth != '2' && $depth != '3' && $depth != '4') return;

		$view = array();
        $view['view'] = array();


		$where = array(
			'app_id' => $app_id,
			'cat_parent' => $parent_id,
			'cat_depth' => $depth,
		);
        $result = $this->Contents_category_model->get('', '', $where, '', '', 'cat_sort', 'desc');

        $this->output->set_content_type('application/json');
		exit(json_encode($result));

    }
}