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

/**
 * Apps class
 */

class Apps extends MY_Controller
{

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

    /**
     * 모델을 로딩합니다
     */
    protected $models = array('Apps', 'Upload_file');

    /**
     * 이 컨트롤러의 메인 모델 이름입니다
     */
    protected $modelname = 'Apps_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;
        $page = (((int) $this->input->get('page')) > 0) ? ((int) $this->input->get('page')) : 1;
        $findex = $this->input->get('findex') ? $this->input->get('findex') : 'app_sort';
        $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','app_package','app_name'); // 검색이 가능한 필드
        $this->{$this->modelname}->search_field_equal = array('app_id'); // 검색중 like 가 아닌 = 검색을 하는 필드
        $this->{$this->modelname}->allow_order_field = array('app_id', 'app_sort'); // 정렬이 가능한 필드
        $result = $this->{$this->modelname}
            ->get_admin_list($per_page, $offset, '', '', $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--;
            }
        }

        $view['view']['data'] = $result;

        /**
         * 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('app_id' => '고유번호','app_package' => '패키지명','app_name' => '어플 이름');
        $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']['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);
        }

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

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


        /**
         * 전송된 데이터의 유효성을 체크합니다
         */
        $config = array(
			array('field' => 'app_package',	'label' => '패키지명',	'rules' => 'trim|required'),
			array('field' => 'app_name',	'label' => '어플 이름',	'rules' => 'trim|required'),
			array('field' => 'app_sort',	'label' => '정렬순서',	'rules' => 'trim|required'),
			array('field' => 'app_policy',	'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('app_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 !== '') {

			if ( ! $pid) {
				$max_sort = $this->{$this->modelname}->select_max_sort();
				$getdata['app_sort'] = $max_sort + 1;
			}
            
			$view['view']['data'] = $getdata;

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

			if (element('app_id', $getdata)) {
				$uploadwhere = array(
					'origin_table' => 'apps',
					'origin_id' => element('app_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_package'          => $this->input->post('app_package',	null,	''),
				'app_name'          => $this->input->post('app_name',	null,	''),
				'app_sort'          => $this->input->post('app_sort',	null,	''),
				'app_policy'          => $this->input->post('app_policy',	null,	''),
				
            );

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

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

				$updatedata['app_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['app_created_at'] = cdate('Y-m-d H:i:s');
				$updatedata['app_updated_at'] = cdate('Y-m-d H:i:s');
				
				
                $origin_id = $this->{$this->modelname}->insert($updatedata);
                $this->session->set_flashdata('message','정상적으로 입력되었습니다');
            }


            $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' => 'apps',
                            '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;
                    }
                }
            }


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




    /**
     * 게시판 글쓰기 또는 수정 페이지를 가져오는 메소드입니다
     */
    public function write_rank($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);
			$getdata['app_rank'] = json_decode($getdata['app_rank'], true);
        }



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

        /**
         * 전송된 데이터의 유효성을 체크합니다
         */
        $config = array(
            array(
                'field' => 'is_submit',
                'label' => '전송',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_1_title',
                'label' => '1위 제목',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_1_desc',
                'label' => '1위 소개내용',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_1_link',
                'label' => '1위 링크',
                'rules' => 'trim',
            ),
            array(
                'field' => 'app_rank_1_image_url',
                'label' => '1위 이미지 URL',
                'rules' => 'trim',
            ),
            array(
                'field' => 'app_rank_2_title',
                'label' => '2위 제목',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_2_desc',
                'label' => '2위 소개내용',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_2_link',
                'label' => '2위 링크',
                'rules' => 'trim',
            ),
            array(
                'field' => 'app_rank_2_image_url',
                'label' => '2위 이미지 URL',
                'rules' => 'trim',
            ),
            array(
                'field' => 'app_rank_3_title',
                'label' => '3위 제목',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_3_desc',
                'label' => '3위 소개내용',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'app_rank_3_link',
                'label' => '3위 링크',
                'rules' => 'trim',
            ),
            array(
                'field' => 'app_rank_3_image_url',
                'label' => '3위 이미지 URL',
                'rules' => 'trim',
            ),
        );
        $this->form_validation->set_rules($config);

        /**
         * 유효성 검사를 하지 않는 경우, 또는 유효성 검사에 실패한 경우입니다.
         * 즉 글쓰기나 수정 페이지를 보고 있는 경우입니다
         */
        if ($this->form_validation->run() === false) {
			
			$view['view']['data'] = $getdata['app_rank'];
			$view['view']['data']['app_id'] = $getdata['app_id'];
			
            /**
             * 어드민 레이아웃을 정의합니다
             */
            $layoutconfig = array('layout' => 'layout', 'skin' => 'write_rank');
            $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_rank_1_title'          => $this->input->post('app_rank_1_title',	null,	''),
				'app_rank_1_desc'          => $this->input->post('app_rank_1_desc',	null,	''),
				'app_rank_1_link'          => $this->input->post('app_rank_1_link',	null,	''),
				'app_rank_2_title'          => $this->input->post('app_rank_2_title',	null,	''),
				'app_rank_2_desc'          => $this->input->post('app_rank_2_desc',	null,	''),
				'app_rank_2_link'          => $this->input->post('app_rank_2_link',	null,	''),
				'app_rank_3_title'          => $this->input->post('app_rank_3_title',	null,	''),
				'app_rank_3_desc'          => $this->input->post('app_rank_3_desc',	null,	''),
				'app_rank_3_link'          => $this->input->post('app_rank_3_link',	null,	''),
				'app_rank_1_image_url'	=> element('app_rank_1_image_url', element('app_rank', $getdata)),
				'app_rank_2_image_url'	=> element('app_rank_2_image_url', element('app_rank', $getdata)),
				'app_rank_3_image_url'	=> element('app_rank_3_image_url', element('app_rank', $getdata)),
            );

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



			$this->load->library('upload');
			$app_rank_1_image_url = '';
			if (isset($_FILES) && isset($_FILES['app_rank_1_image_url']) && isset($_FILES['app_rank_1_image_url']['name']) && $_FILES['app_rank_1_image_url']['name']) {
				$upload_path = config_item('uploads_dir') . '/apprank/';
				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);
				}

				$uploadconfig = '';
				$uploadconfig['upload_path'] = $upload_path;
				$uploadconfig['allowed_types'] = 'jpg|jpeg|png|gif';
				$uploadconfig['max_size'] = '2000';
				$uploadconfig['max_width'] = '1000';
				$uploadconfig['max_height'] = '1000';
				$uploadconfig['encrypt_name'] = true;

				$this->upload->initialize($uploadconfig);

				if ($this->upload->do_upload('app_rank_1_image_url')) {
					$img = $this->upload->data();
					$app_rank_1_image_url = element('file_name', $img);
				} else {
					$file_error = $this->upload->display_errors();
				}
			}

			$app_rank_2_image_url = '';
			if (isset($_FILES) && isset($_FILES['app_rank_2_image_url']) && isset($_FILES['app_rank_2_image_url']['name']) && $_FILES['app_rank_2_image_url']['name']) {
				$upload_path = config_item('uploads_dir') . '/apprank/';
				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);
				}

				$uploadconfig = '';
				$uploadconfig['upload_path'] = $upload_path;
				$uploadconfig['allowed_types'] = 'jpg|jpeg|png|gif';
				$uploadconfig['max_size'] = '2000';
				$uploadconfig['max_width'] = '1000';
				$uploadconfig['max_height'] = '1000';
				$uploadconfig['encrypt_name'] = true;

				$this->upload->initialize($uploadconfig);

				if ($this->upload->do_upload('app_rank_2_image_url')) {
					$img = $this->upload->data();
					$app_rank_2_image_url = element('file_name', $img);
				} else {
					$file_error = $this->upload->display_errors();
				}
			}

			$app_rank_3_image_url = '';
			if (isset($_FILES) && isset($_FILES['app_rank_3_image_url']) && isset($_FILES['app_rank_3_image_url']['name']) && $_FILES['app_rank_3_image_url']['name']) {
				$upload_path = config_item('uploads_dir') . '/apprank/';
				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);
				}

				$uploadconfig = '';
				$uploadconfig['upload_path'] = $upload_path;
				$uploadconfig['allowed_types'] = 'jpg|jpeg|png|gif';
				$uploadconfig['max_size'] = '2000';
				$uploadconfig['max_width'] = '1000';
				$uploadconfig['max_height'] = '1000';
				$uploadconfig['encrypt_name'] = true;

				$this->upload->initialize($uploadconfig);

				if ($this->upload->do_upload('app_rank_3_image_url')) {
					$img = $this->upload->data();
					$app_rank_3_image_url = element('file_name', $img);
				} else {
					$file_error = $this->upload->display_errors();
				}
			}

			if ($app_rank_1_image_url) {
				$updatedata['app_rank_1_image_url'] = $app_rank_1_image_url;
			}
			if ($app_rank_2_image_url) {
				$updatedata['app_rank_2_image_url'] = $app_rank_2_image_url;
			}
			if ($app_rank_3_image_url) {
				$updatedata['app_rank_3_image_url'] = $app_rank_3_image_url;
			}

			$updata = json_encode($updatedata,JSON_UNESCAPED_UNICODE);



			$this->{$this->modelname}->update($pid, array('app_rank' => $updata));
			$this->session->set_flashdata('message','정상적으로 수정되었습니다');



            /**
             * 게시물의 신규입력 또는 수정작업이 끝난 후 목록 페이지로 이동합니다
             */
			$redirecturl = admin_url($this->pagedir . '/write_rank/' . $pid);
			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}->delete($val);
                }
            }
        }

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

        redirect($redirecturl);
    }
}