<?php
    /**
     * @author Webfairy MediaT CMS - www.Webfairy.net
     */

    include dirname(__FILE__).'/lib/engine.php';
        $Webfairy = new Webfairy();
            $Webfairy->start(true, true, true, array('ROOT', 'PANEL'));

    $Webfairy->require_auth();

    if ($Webfairy->isManager() == false) {
        $Webfairy->return_to();
    }

    $Webfairy->jsFile(
        array(
            'js/dialog.min.js',
            'js/panel.js?'.time(),
        )
    );

    $display_options = array();

    function adTitle($size)
    {
        return ftr('ad_title', array($size[0], $size[1]));
    }

    function caseUrl($c)
    {
        return 'panel.html?case='.$c;
    }

    function icon($i)
    {
        return sprintf('<i class="fa fa-%s"></i>', $i);
    }

    $Webfairy->loadClass('formbuilder', 'tools');
    $Webfairy->loadClass('navbar', 'tools');
    $Webfairy->loadClass('Arabic', 'I18N');

    $panel_nav = array(
        array(
            'title' => tr('overview'),
            'icon' => icon('home'),
            'url' => caseUrl('overview'),
        ),
        array(
            'title' => tr('content'),
            'icon' => icon('cubes'),
            'url' => '#',
            'children' => array(
                array(
                    'title' => tr('posts'),
                    'icon' => icon('book'),
                    'url' => caseUrl('posts'),
                ),
                array(
                    'title' => tr('cats'),
                    'icon' => icon('th-large'),
                    'url' => caseUrl('cats'),
                ),
                array(
                    'title' => tr('post_fetcher'),
                    'icon' => icon('refresh'),
                    'url' => caseUrl('fetcher'),
                ),
            ),
        ),
        array(
            'title' => tr('pages'),
            'icon' => icon('files-o'),
            'url' => caseUrl('pages'),
        ),
        array(
            'title' => tr('ads'),
            'icon' => icon('dollar'),
            'url' => caseUrl('ads'),
        ),
        array(
            'title' => tr('users'),
            'icon' => icon('users'),
            'url' => caseUrl('users'),
        ),
        array(
            'title' => ftr('inbox', array($Webfairy->getUserData('unReadMessages'))),
            'icon' => icon('inbox'),
            'url' => caseUrl('messages'),
        ),
        array(
            'title' => tr('themes'),
            'icon' => icon('magic'),
            'url' => caseUrl('#'),
            'children' => array(
                array(
                    'title' => tr('navbars'),
                    'icon' => icon('navicon'),
                    'url' => caseUrl('navbars'),
                ),
                array(
                    'title' => tr('langs'),
                    'icon' => icon('globe'),
                    'url' => caseUrl('langs'),
                ),
            ),
        ),
        array(
            'title' => tr('settings'),
            'icon' => icon('cog'),
            'url' => caseUrl('options'),
            'children' => array(
                array('title' => tr('siteinfo'),'url' => caseUrl('options&o=info'),'icon' => icon('cube')),
                array('title' => tr('themes'),'url' => caseUrl('options&o=themes'),'icon' => icon('magic')),
                array('title' => tr('posting'),'url' => caseUrl('options&o=posting'),'icon' => icon('plus')),
                array('title' => tr('post_fetcher'),'url' => caseUrl('options&o=fetcher'),'icon' => icon('rss')),
                array('title' => tr('content'),'url' => caseUrl('options&o=content'),'icon' => icon('archive')),
                array('title' => tr('mail'),'url' => caseUrl('options&o=mail'),'icon' => icon('envelope')),
                array('title' => tr('datetime'),'url' => caseUrl('options&o=datetime'),'icon' => icon('clock-o')),
                array('title' => tr('ads'),'url' => caseUrl('options&o=ads'),'icon' => icon('dollar')),
                array('title' => tr('social'),'url' => caseUrl('options&o=social'),'icon' => icon('facebook-square')),
                array('title' => tr('files'),'url' => caseUrl('options&o=files'),'icon' => icon('upload')),
                array('title' => tr('caching'),'url' => caseUrl('options&o=cache'),'icon' => icon('clock-o')),
                array('title' => tr('comments'),'url' => caseUrl('options&o=comments'),'icon' => icon('comments')),
                array('title' => tr('analytics'),'url' => caseUrl('options&o=analytics'),'icon' => icon('bar-chart-o')),
            ),
        ),
    );

    $Webfairy->smarty->assign('panel_nav', $panel_nav);

    $catgories_tree = $Webfairy->catgories_select_tree();

    $Webfairy->smarty->assign('catgories_tree', $catgories_tree);

    $pages = array();
    foreach ($Webfairy->db->pages() as $page) {
        $pages[$page['id']] = ((int) $page['type'] == 1) ? tr($page['prefix']) : $page['title'];
    }

    $Webfairy->smarty->assign('pages', $pages);

    $case = (isset($_GET['case']) == true) ? $_GET['case'] : '';

    $breadcrumb = array(
        array(
            'url' => caseUrl($case),
            'text' => tr($case),
        ),
    );

    if (isset($_GET['action']) == true) {
        $breadcrumb[] = array(
            'text' => tr($_GET['action']),
        );
    }

    switch ($case) {
        case 'ajax':
            switch ($_GET['c']) {
                case 'dataTable':
                    /*
                    $Webfairy->loadClass('ssp','tools');

                    $table = 'posts';
                    
                    $primaryKey = 'id';
                    
                    $columns = array(
                    	array( 'db' => 'id', 'dt' => 'id' ),
                    
                    );
                    
                    echo json_encode(
                    	SSP::simple( $Webfairy, $_GET, $table, $primaryKey, $columns )
                    );*/                    
                break;
                
                case 'sourcepreview':
                    $id = (int) $_GET['id'];
                    $items_num = (isset($_GET['items_num']) == true) ? (int) $_GET['items_num'] : 3;

                    try {
                        $data = $Webfairy->FetchRSS($id, $items_num, 0, false);
                        $Webfairy->smarty->assign('data', $data);
                        $Webfairy->smarty->display('string:{source_preview data=$data}');
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }

                break;

                case 'fetchitem':
                    $id = (int) $_POST['id'];
                    $cat_id = (int) $_POST['cat'];
                    $item_key = (int) $_POST['key'];

                    try {
                        $data = $Webfairy->FetchRSS($id, 0, 0, true, $item_key);
                        foreach ($data['result']['items'] as $item) {
                            if ($item['fresh'] == false) {
                                throw new \Exception(tr('post_already_exists'));
                            }
                            if ($cat_id > 0) {
                                $item['row']['cat_id'] = $cat_id;
                            }
                            $records = $Webfairy->db_post_array($item['row']);
                            if ($Webfairy->insert_post_to_db($records)) {
                                echo '<i class="fa fa-check"></i> '.tr('done');
                            }
                        }
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }

                break;

                case 'navbars':
                    $fields = array(
                        1 => array(
                            'title','url',
                        ),
                    );
                    switch ($_GET['o']) {
                        case 'insert':
                            $index = (int) $_GET['index'];
                            $type = (int) $_POST['type'];

                            $item = array(
                                'index' => $index,
                                'type' => $type,
                            );

                            $html = '';
                            $errors = array();
                            $errorFound = false;

                            $Webfairy->loadClass('validaforms', 'tools');
                            $vFs = new validaForms();

                            switch ($type) {
                                case 1:
                                    if (isset($_POST['noicon']) == true) {
                                        if (!$vFs->textBox(tr('title'), $_POST['title'], true)) {
                                            $errorFound = true;
                                        }
                                    }
                                    $item['title'] = $Webfairy->plaintext($_POST['title']);
                                    $item['url'] = $Webfairy->plaintext($_POST['url']);
                                break;

                                case 2:
                                    $page_id =  (int) $_POST['page_id'];
                                    $item['page_id'] = $page_id;
                                    $item['title'] = (empty($_POST['title']) == false) ? $Webfairy->plaintext($_POST['title']) : $pages[$page_id];
                                break;

                                case 3:
                                    $cat_id = (int) $_POST['cat_id'];
                                    $item['cat_id'] = $cat_id;
                                    $item['title'] = (empty($_POST['title']) == false) ? $Webfairy->plaintext($_POST['title']) : $Webfairy->getCatgory($cat_id, 'title');
                                break;
                            }

                            $item['noicon'] = (isset($_POST['noicon'])) ? 'true' : 'false';
                            $item['icon'] = $Webfairy->plaintext($_POST['icon']);

                            if ($errorFound == true) {
                                $errors = $vFs->erro;
                            } else {
                                $Webfairy->smarty->assign('item', $item);

                                ob_start();
                                $Webfairy->smarty->display('string:<li class="dd-item" data-index="'.$index.'">{navbars_builder_item item=$item}</li>');
                                $html = ob_get_contents();
                                ob_end_clean();
                            }

                            header("Content-type:application/json; charset: UTF-8");

                            exit(json_encode(
                                array(
                                    'html' => $html,
                                    'errors' => $errors,
                                )
                            ));
                        break;

                        case 'save':
                            $data = (is_array($_POST['data']) == true) ? $_POST['data'] : array();
                            $Webfairy->updateOption(
                                'navbar_'.$_GET['navbar_prefix'],
                                json_encode($data)
                            );
                            $Webfairy->cache->remove($Webfairy->cache_key('Navbars', true));
                        break;

                    }
                break;
             }
             exit;
        break;

        case 'cats':
            if (isset($_GET['action']) == true) {
                $action = $_GET['action'];

                if ($action == 'delete') {
                    $cats = (isset($_GET['cats']) == true) ? array_map('intval', $_GET['cats']) : array();

                    if (count($cats) == 0) {
                        $Webfairy->redirect(
                            tr('select_then_delete'),
                            $Webfairy->url('panel.html?case=cats')
                        );
                    }

                    $cats_array = $Webfairy->db->cats('id', $cats)->order("`id` DESC")->fetchPairs('id', 'title');

                    $Form = new FormBuilder('cats', tr('delete'), tr('cats'), true);

                    $Form->addField(array(
                            'id' => 'cats',
                            'type' => 'checkbox',
                            'label' => tr('cats'),
                            'required' => true,
                            'checkboxlabels' => array_values($cats_array),
                            'checkboxvalues' => array_keys($cats_array),
                            'checkboxchecked' => array_fill(0, count($cats_array), true),
                        )
                    );

                    $Form->addField(array(
                            'id' => 'delete_posts',
                            'type' => 'radio',
                            'label' => tr('delete_posts'),
                            'required' => true,
                            'instructions' => tr('delete_posts_ins'),
                            'radiolabels' => array(tr('yes'), tr('no')),
                            'radiovalues' => array(1, 0),
                            'defaultvalue' => 0,
                        )
                    );

                    if ($Form->formSuccess()) {
                        $Webfairy->delete_catgories((array) $_POST['cats_arr'], (boolean) $_POST['delete_posts']);
                        $Webfairy->go_to('panel.html?case=cats');
                    }
                } else {
                    $row = array(
                        'parent_id' => 0,
                        'title' => '',
                        'prefix' => '',
                    );
                    if ($action == 'edit' && isset($_GET['id'])) {
                        $id = (int) $_GET['id'];
                        if (($row = $Webfairy->db->cats[$id]) == false) {
                            $Webfairy->go_to('panel.html?case=cats');
                        }
                    }

                    $Form = new FormBuilder('cats', tr('save'), tr('cats'), true);

                    $Form->addField(array(
                            'id' => 'title',
                            'type' => 'textbox',
                            'label' => tr('title'),
                            'required' => true,
                            'maxlength' => 150,
                            'headerinjectioncheck' => 'full',
                            'defaultvalue' => $row['title'],
                        )
                    );

                    $Form->addField(array(
                            'id' => 'prefix',
                            'type' => 'textbox',
                            'label' => tr('permalink_name'),
                            'required' => true,
                            'maxlength' => 50,
                            'headerinjectioncheck' => 'full',
                            'defaultvalue' => $row['prefix'],
                        )
                    );

                    $cats = array(0 => tr('root_cat'));

                    $c = array('parent_id' => 0);

                    if ($action == 'edit') {
                        $c["id != ?"] = $id;
                    }

                    foreach ($Webfairy->db->cats($c)->order('id ASC') as $cat) {
                        $cats[$cat['id']] = $cat['title'];
                    }

                    $Form->addField(array(
                            'id' => 'parent_id',
                            'type' => 'select',
                            'label' => tr('parent_cat'),
                            'optionlabels' => array_values($cats),
                            'optionvalues' => array_keys($cats),
                            'defaultvalue' => $row['parent_id'],
                        )
                    );

                    if ($Form->formSuccess()) {
                        $isvalid = true;

                        $parent_id = (int) $_POST['parent_id'];

                        $title = $Webfairy->plaintext($_POST['title']);
                        $prefix = $Webfairy->plaintext($_POST['prefix']);

                        $records = array(
                            'parent_id' => $parent_id,
                            'title' => $title,
                            'prefix' => $Webfairy->seo_str($prefix),
                        );

                        $_where = ($action == 'edit') ? "prefix = '{$prefix}' AND id != {$id}" : "prefix = '{$prefix}'";

                        if ($Webfairy->db->cats($_where)->fetch()) {
                            $Form->forceErrorMessage('prefix', ftr('err_already_exists', array($prefix)));
                            $isvalid = false;
                        }

                        if ($isvalid == true) {
                            $Webfairy->cache->remove('catgories');
                            switch ($_GET['action']) {
                                case 'edit':
                                    $row->update($records);
                                    $Form->renderThanks();

                                    $display_options['redirect'] = true;
                                    $display_options['redirect_url'] = $Webfairy->url('panel.html?case=cats');
                                break;

                                case 'create':
                                    if ($id = $Webfairy->db->cats()->insert($records)) {
                                        $Webfairy->go_to('panel.html?case=cats');
                                    }
                                break;
                            }
                        }
                    }
                }

                $Webfairy->smarty->assign('Form', $Form->renderForm());
            } else {
                $cats = array();
                foreach ($Webfairy->catgories_tree() as $parent) {
                    $cats[$parent['id']] = $parent;
                    $cats[$parent['id']]['title'] = (count($parent['subcategories']) > 0) ? '+ '.$parent['title'] : '- '.$parent['title'];
                    foreach ($parent['subcategories'] as $sub) {
                        $cats[$sub['id']] = $sub;
                        $cats[$sub['id']]['title'] = "¦ ------ {$sub['title']}";
                    }
                }

                $Webfairy->smarty->assign('cats', $cats);
            }
            $tpl = 'panel-cats.tpl';
        break;

        case 'pages':
            if (isset($_GET['action']) == true) {
                $action = $_GET['action'];

                if ($action == 'delete') {
                    $pages = (isset($_GET['pages']) == true) ? array_map('intval', $_GET['pages']) : array();

                    if (count($pages) == 0) {
                        $Webfairy->redirect(
                            tr('select_then_delete'),
                            $Webfairy->url('panel.html?case=pages')
                        );
                    }

                    $pages_array = $Webfairy->db->pages('id', $pages)->where("type != 1")->order("`id` DESC")->fetchPairs('id', 'title');

                    $Form = new FormBuilder('pages', tr('delete'), tr('pages'), true);

                    $Form->addField(array(
                            'id' => 'pages',
                            'type' => 'checkbox',
                            'label' => tr('pages'),
                            'required' => true,
                            'checkboxlabels' => array_values($pages_array),
                            'checkboxvalues' => array_keys($pages_array),
                            'checkboxchecked' => array_fill(0, count($pages_array), true),
                        )
                    );

                    if ($Form->formSuccess()) {
                        foreach ($pages as $page_id) {
                            $Webfairy->db->pages('id', $page_id)->delete();
                        }
                        $Webfairy->go_to('panel.html?case=pages');
                    }
                } else {
                    $row = array(
                        'type' => 0,
                        'title' => '',
                        'prefix' => '',
                        'options' => array(
                            'require_auth' => 0,
                        ),
                        'content' => '',
                    );

                    if ($action == 'edit' && isset($_GET['id'])) {
                        $id = (int) $_GET['id'];
                        if (($row = $Webfairy->db->pages('id', $id)->where("type != 1")->fetch()) == false) {
                            $Webfairy->go_to('panel.html?case=pages');
                        }

                        $row['options'] = json_decode($row['options'], true);
                    }

                    $Form = new FormBuilder('pages', tr('save'), tr('pages'), true);

                    $Form->addField(array(
                            'id' => 'title',
                            'type' => 'textbox',
                            'label' => tr('title'),
                            'required' => true,
                            'maxlength' => 250,
                            'headerinjectioncheck' => 'full',
                            'defaultvalue' => $row['title'],
                        )
                    );

                    $Form->addField(array(
                            'id' => 'prefix',
                            'type' => 'textbox',
                            'label' => tr('permalink_name'),
                            'required' => true,
                            'maxlength' => 50,
                            'headerinjectioncheck' => 'full',
                            'defaultvalue' => $row['prefix'],
                        )
                    );

                    $Form->addField(array(
                            'id' => 'content',
                            'type' => 'textarea',
                            'label' => tr('content'),
                            'rows' => 8,
                            'required' => true,
                            'defaultvalue' => $row['content'],
                        )
                    );

                    $Webfairy->jsFile('ckeditor/ckeditor.js');
                    $Webfairy->jsFile('ckeditor/adapters/jquery.js');

                    $ckeditor_options = array(
                        'language' => $Webfairy->getLang(),
                    );

                    $Webfairy->html(
                        $Webfairy->javascript_code(
                            '$(document).ready(function () {
                                $( "#content" ).ckeditor('.json_encode($ckeditor_options).');
                            });'
                        ),
                        'footer'
                    );

                    $Form->addField(array(
                            'id' => 'options[require_auth]',
                            'type' => 'radio',
                            'label' => tr('require_auth'),
                            'radiolabels' => array(tr('yes'), tr('no')),
                            'radiovalues' => array(1, 0),
                            'defaultvalue' => $row['options']['require_auth'],
                        )
                    );

                    if ($Form->formSuccess()) {
                        $isvalid = true;

                        $prefix = $Webfairy->plaintext($_POST['prefix']);
                        $prefix = $Webfairy->seo_str($prefix);

                        $records = array(
                            'title' => $Webfairy->plaintext($_POST['title']),
                            'prefix' => $prefix,
                            'content' => $_POST['content'],
                        );

                        if (count($_POST['options']) > 0) {
                            $records['options'] = json_encode($_POST['options']);
                        }

                        $_where = ($action == 'edit') ? "prefix = '{$prefix}' AND id != {$id}" : "prefix = '{$prefix}'";

                        if ($Webfairy->db->pages($_where)->fetch()) {
                            $Form->forceErrorMessage('prefix', ftr('err_already_exists', array($prefix)));
                            $isvalid = false;
                        }

                        if ($isvalid == true) {
                            switch ($_GET['action']) {
                                case 'edit':
                                    $row->update($records);
                                    $Form->renderThanks();

                                    $display_options['redirect'] = true;
                                    $display_options['redirect_url'] = $Webfairy->url('panel.html?case=pages');
                                break;

                                case 'create':
                                    if ($id = $Webfairy->db->pages()->insert($records)) {
                                        $Webfairy->go_to('panel.html?case=pages');
                                    }
                                break;
                            }
                        }
                    }
                }

                $Webfairy->smarty->assign('Form', $Form->renderForm());
            } else {
                $Webfairy->loadClass('pagination', 'tools');

                $pagination = new pagination(
                    $Webfairy->db->pages("type != 1")->order("`id` DESC"), 10);

                $Webfairy->smarty->assign('pages',
                    $pagination->rows()
                );

                $Webfairy->smarty->assign('pagination', $pagination->display());
            }
            $tpl = 'panel-pages.tpl';
        break;

    case 'langs':
            if (isset($_GET['action']) == true) {
                $action = $_GET['action'];

                $row = array(
                        'var_key' => '',
                    );
                if ($action == 'edit' && isset($_GET['id'])) {
                    $id = (int) $_GET['id'];
                    if (($row = $Webfairy->db->langs[$id]) == false) {
                        $Webfairy->go_to('panel.html?case=langs');
                    }
                }

                $Form = new FormBuilder('langs', tr('save'), tr('langs'), true);

                if ($action == 'create') {
                    $Form->addField(array(
                                'id' => 'var_key',
                                'type' => 'textbox',
                                'label' => tr('key'),
                                'required' => true,
                                'maxlength' => 50,
                                'defaultvalue' => $row['var_key'],
                            )
                        );
                }

                foreach ($Webfairy->availableLangs() as $key => $value) {
                    $Form->addField(array(
                                'id' => $key,
                                'type' => 'textarea',
                                'label' => tr($value),
                                'rows' => 2,
                                'defaultvalue' => ($action == 'edit') ? $row[$key] : '',
                            )
                        );
                }

                if ($Form->formSuccess()) {
                    $isvalid = true;

                    $records = array(
                            'version' => (int) Webfairy::VERSION,
                            'modified' => new NotORM_Literal("CURRENT_TIMESTAMP()"),
                        );

                    foreach ($Webfairy->availableLangs() as $key => $value) {
                        if (empty($_POST[$key]) == false) {
                            $records[$key] = ($key != 'ar') ? ucfirst($_POST[$key]) : $_POST[$key];
                        }
                    }

                    if ($action == 'create') {
                        $var_key = $Webfairy->plaintext($_POST['var_key']);
                        $var_key = strtolower($var_key);
                        $var_key = preg_replace('/[^\da-z_]/i', '_', $var_key);

                        if ($Webfairy->db->langs(
                               "var_key = ?", $var_key
                               )->fetch()) {
                            $Form->forceErrorMessage('var_key', ftr('err_already_exists', array($var_key)));
                            $isvalid = false;
                        }
                    }

                    if ($isvalid == true) {
                        switch ($_GET['action']) {
                                case 'edit':
                                    $row->update($records);
                                    $Form->renderThanks();

                                    $display_options['redirect'] = true;
                                    $display_options['redirect_url'] = (isset($_GET['return']) == true) ?  $Webfairy->return_to('return', true) : $Webfairy->url('panel.html?case=langs');

                                break;

                                case 'create':
                                    $records['var_key'] = $var_key;
                                    if ($id = $Webfairy->db->langs()->insert($records)) {
                                        $Webfairy->go_to('panel.html?case=langs');
                                    }
                                break;
                            }
                    }
                }
                $Webfairy->smarty->assign('Form', $Form->renderForm());
            } else {
                $Webfairy->loadClass('pagination', 'tools');
                $Webfairy->loadClass('arabic', 'I18N');

                $db_rows = $Webfairy->db->langs();
                $strOrderBy = '`var_key`';

                if (isset($_GET['q']) == true && empty($_GET['q']) == false) {
                    $q = $Webfairy->plaintext($_GET['q']);

                    $Arabic_Query = new I18N_Arabic('Query');
                    $Arabic_Query->setArrFields(
                        array_merge(
                            array('var_key'),
                            array_keys($Webfairy->availableLangs())
                        )
                    );
                    $Arabic_Query->setMode(0);

                    $strCondition = $Arabic_Query->getWhereCondition($q);
                    $strOrderBy = $Arabic_Query->getOrderBy($q);

                    $db_rows->where($strCondition);
                }

                $db_rows->order($strOrderBy);

                $pagination = new pagination(
                    $db_rows, 25);

                $Webfairy->smarty->assign('langs',
                    $pagination->rows()
                );

                $Webfairy->smarty->assign('pagination', $pagination->display());
            }
            $tpl = 'panel-langs.tpl';
        break;

        case 'messages':

             if (isset($_GET['action']) == true) {
                 $action = $_GET['action'];

                 if ($action == 'delete') {
                     $messages = (isset($_GET['messages']) == true) ? array_map('intval', $_GET['messages']) : array();

                     if (count($messages) == 0) {
                         $Webfairy->redirect(
                            tr('select_then_delete'),
                            $Webfairy->url('panel.html?case=messages')
                        );
                     }

                     $messages_array = array();

                     foreach ($Webfairy->db->messages('id', $messages)->order("`id` DESC")->fetchPairs('id', 'content') as $message_id => $message_content) {
                         $messages_array[$message_id] = Webfairy::limit_words($message_content, 5);
                     }

                     $Form = new FormBuilder('messages', tr('delete'), tr('messages'), true);

                     $Form->addField(array(
                            'id' => 'messages',
                            'type' => 'checkbox',
                            'label' => tr('messages'),
                            'required' => true,
                            'checkboxlabels' => array_values($messages_array),
                            'checkboxvalues' => array_keys($messages_array),
                            'checkboxchecked' => array_fill(0, count($messages_array), true),
                        )
                    );

                     if ($Form->formSuccess()) {
                         $isvalid = true;

                         $messages = (array) $_POST['messages_arr'];

                         if ($isvalid == true) {
                             foreach ($messages as $message_id) {
                                 if ($msg = $Webfairy->db->messages('id', $message_id)->where('user_id', $Webfairy->Userid())) {
                                     $msg->delete();
                                 }
                             }
                             $Webfairy->go_to('panel.html?case=messages');
                         }
                     }
                 } elseif ($action == 'read' && isset($_GET['id'])) {
                     $message = array();

                     $id = (int) $_GET['id'];
                     if (($row = $Webfairy->db->messages('id', $id)->where('user_id', $Webfairy->Userid())->fetch()) == false) {
                         $Webfairy->go_to('panel.html?case=messages');
                     }

                     $row['sender_data'] = json_decode($row['sender_data'], true);
                     $row->update(array('unread' => 0));

                     $message = array(
                        'sender' => array(
                            'email' => $row['sender_data']['email'],
                            'ip' => long2ip($row['sender_data']['ip']),
                            'agent' => $row['sender_data']['user_agent'],
                        ),
                        'content' => nl2br($row['content']),
                        'time' => $Webfairy->TimeFormat($row['msgtime']),
                    );

                     $Form = new FormBuilder('messages', tr('send'), tr('replay'), true);

                     $Form->addField(array(
                            'id' => 'replay',
                            'type' => 'textarea',
                            'label' => tr('replay'),
                            'required' => true,
                            'minlength' => 15,
                        )
                    );

                     if ($Form->formSuccess()) {
                         $replay = $Webfairy->plaintext($_POST['replay']);

                         $email_body = sprintf("replay_body", array($replay, $message['content']));

                         $Webfairy->mail(
                            array('email' => $message['sender']['email'], 'name' => $message['sender']['email']),
                            tr('replay').' '.$Webfairy->getOption('site_name'),
                            $email_body
                        );

                         $Webfairy->redirect(
                            tr('message_sent'),
                            $Webfairy->url('panel.html?case=messages')
                        );
                     }
                     $Webfairy->smarty->assign('message', $message);
                 }

                 $Webfairy->smarty->assign('Form', $Form->renderForm());
             } else {
                 $Webfairy->loadClass('pagination', 'tools');

                 $pagination = new pagination(
                    $Webfairy->db->messages('user_id', $Webfairy->Userid())->order("`id` DESC"), 10);

                 $Webfairy->smarty->assign('messages',
                    $pagination->rows()
                );

                 $Webfairy->smarty->assign('pagination', $pagination->display());
             }

            $tpl = 'panel-messages.tpl';
        break;

        case 'ads':

            if (isset($_GET['action']) == true) {
                $action = $_GET['action'];

                if ($action == 'delete') {
                    $ads = (isset($_GET['ads']) == true) ? array_map('intval', $_GET['ads']) : array();

                    if (count($ads) == 0) {
                        $Webfairy->redirect(
                            tr('select_then_delete'),
                            $Webfairy->url('panel.html?case=ads')
                        );
                    }

                    $ads_array = array();

                    foreach ($Webfairy->db->ads('id', $ads)->order("`id` DESC")->fetchPairs('id', 'size') as $ad_id => $ad_size) {
                        $ads_array[$ad_id] = adTitle(explode('x', $ad_size));
                    }

                    $Form = new FormBuilder('ads', tr('delete'), tr('ads'), true);

                    $Form->addField(array(
                            'id' => 'ads',
                            'type' => 'checkbox',
                            'label' => 'ads',
                            'required' => true,
                            'checkboxlabels' => array_values($ads_array),
                            'checkboxvalues' => array_keys($ads_array),
                            'checkboxchecked' => array_fill(0, count($ads_array), true),
                        )
                    );

                    if ($Form->formSuccess()) {
                        foreach ((array) $_POST['ads_arr'] as $ad_id) {
                            $Webfairy->db->ads('id', $ad_id)->delete();
                        }
                        $Webfairy->go_to('panel.html?case=ads');
                    }
                } else {
                    $row = array(
                        'code' => '',
                        'size' => '',
                    );
                    if ($_GET['action'] == 'edit' && isset($_GET['id'])) {
                        $id = (int) $_GET['id'];
                        if (($row = $Webfairy->db->ads[$id]) == false) {
                            $Webfairy->go_to('panel.html?case=ads');
                        }
                    }

                    $Form = new FormBuilder('ads', tr('save'), 'ads', true);

                    $ad_sizes = array();
                    foreach ($Webfairy->ad_sizes as $size) {
                        $ad_sizes["{$size[0]}x{$size[1]}"] = adTitle($size);
                    }

                    $Form->addField(array(
                            'id' => 'size',
                            'type' => 'select',
                            'label' => tr('size'),
                            'required' => true,
                            'optionlabels' => array_values($ad_sizes),
                            'optionvalues' => array_keys($ad_sizes),
                            'defaultvalue' => $row['size'],
                        )
                    );

                    $Form->addField(array(
                            'id' => 'code',
                            'type' => 'textarea',
                            'label' => tr('code'),
                            'defaultvalue' => $row['code'],
                        )
                    );

                    if ($Form->formSuccess()) {
                        $isvalid = true;

                        $size = $Webfairy->plaintext($_POST['size']);

                        $records = array(
                            'size' => $size,
                            'code' => $_POST['code'],
                        );

                        if ($isvalid == true) {
                            $Webfairy->cache->remove('adsArray');
                            switch ($_GET['action']) {
                                case 'edit':
                                    $row->update($records);
                                    $Form->renderThanks();

                                    $display_options['redirect'] = true;
                                    $display_options['redirect_url'] = $Webfairy->url('panel.html?case=ads');
                                break;

                                case 'create':
                                    if ($id = $Webfairy->db->ads()->insert($records)) {
                                        $Webfairy->go_to('panel.html?case=ads');
                                    }
                                break;
                            }
                        }
                    }
                }

                $Webfairy->smarty->assign('Form', $Form->renderForm());
            } else {
                $Webfairy->loadClass('pagination', 'tools');

                $pagination = new pagination(
                    $Webfairy->db->ads()->order("`id` DESC"), 10);

                $ads = array();

                foreach ($pagination->rows() as $row) {
                    $ads[$row['id']] = array(
                        'id' => $row['id'],
                        'title' => adTitle(explode('x', $row['size'])),
                        'code' => $row['code'],
                        'views' => $Webfairy->Kformat($row['views']),
                        'clicks' => $Webfairy->Kformat($row['clicks']),
                    );
                }

                $Webfairy->smarty->assign('ads', $ads);

                $Webfairy->smarty->assign('pagination', $pagination->display());
            }
            $tpl = 'panel-ads.tpl';
        break;

        default :
            $info = array();
            $info['providers'] = $Webfairy->supported_providers();
            $info['version'] = Webfairy::VERSION;
            $info['php'] = (function_exists('phpversion') == true) ? phpversion() : tr('unkown');
            $info['db'] = strtoupper($Webfairy->driver_name);

            $Webfairy->smarty->assign('info', $info);

            $messages = array();

            $wating_approval_count = $Webfairy->db->posts(array('published' => 0, 'publishedon' => 0))->count('id');

            if ($wating_approval_count > 0) {
                $messages[] = $Webfairy->alert_html(
                    sprintf(
                        '<a href="%s">%s</a>',
                        'panel.html?case=posts&filter=wating_approval',
                        ftr('posts_wating_approval', array($wating_approval_count)
                    )
                ), 'warning');
            }

            try {
                $response = $Webfairy->loadUrl(Webfairy::VERSION_CHECKER);
                $data = json_decode($response, true);
                $last_version = (float) $data['version'];
                $current_version = Webfairy::VERSION;
                if ($current_version < $last_version) {
                    $messages[] = $Webfairy->alert_html(ftr('upgrade_last_version', array($last_version)), 'danger');
                } else {
                    $messages[] = $Webfairy->alert_html(tr('run_last_version'), 'success');
                }
            } catch (Exception $e) {
                $messages[] = $Webfairy->alert_html($e->getMessage(), 'danger');
            }

            if (is_dir($Webfairy->getOption('base_path').'install/')) {
                $messages[] = $Webfairy->alert_html(tr('delete_install_dir'));
            }

            $Webfairy->smarty->assign('messages', $messages);

            $tpl = 'panel.tpl';
    }

    $Webfairy->smarty->assign('breadcrumb', $breadcrumb);

    $Webfairy->display($tpl, array(tr('panel')), $display_options);
