<?php
/**
 * The control file of block module of ZDOO.
 *
 * @copyright   Copyright 2009-2018 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      Yidong Wang <yidong@cnezsoft.com>
 * @package     block
 * @version     $Id$
 * @link        http://www.zdoo.com
 */
class block extends control
{
    /**
     * Admin all blocks.
     *
     * @param  int    $id
     * @access public
     * @return void
     */
    public function admin($id = 0)
    {
        $entries = $this->dao->select('*')->from(TABLE_ENTRY)
            ->where('block')->ne('')
            ->orWhere('buildin')->eq(1)
            ->fetchAll('id');

        $allEntries[''] = '';
        foreach($entries as $i => $entry)
        {
            if(strpos($this->config->block->emptyEntries, ",{$entry->code},") !== false) continue;
            if(!commonModel::hasAppPriv($entry->code)) continue;
            $allEntries[$entry->code] = $entry->name;
        }

        //$allEntries['rss']  = 'RSS';
        $allEntries['html'] = 'HTML';
        $allEntries['allEntries'] = $this->lang->block->allEntries;
        $allEntries['dynamic']    = $this->lang->block->dynamic;

        $hiddenBlocks = $this->block->getHiddenBlocks();
        foreach($hiddenBlocks as $block) $allEntries['hiddenBlock' . $block->id] = $block->title;

        $title = $id == 0 ? $this->lang->block->createBlock : $this->lang->block->editBlock;

        $this->view->block      = $this->block->getByID($id);
        $this->view->entries    = $entries;
        $this->view->allEntries = $allEntries;
        $this->view->id         = $id;
        $this->view->title      = $title;
        $this->view->modalWidth = 384;
        $this->display();
    }

    /**
     * Set params when type is rss or html.
     *
     * @param  int    $id
     * @param  string $type
     * @access public
     * @return void
     */
    public function set($id, $type = '')
    {
        if($_POST)
        {
            $this->block->save($id, $type);
            if(dao::isError()) return $this->send(array('result' => 'fail', 'message' => dao::geterror()));
            return $this->send(array('result' => 'success', 'message' => $this->lang->saveSuccess, 'locate' => $this->createLink('index')));
        }

        $block = $this->block->getByID($id);
        if(dao::isError()) return $this->send(array('result' => 'fail', 'message' => dao::geterror()));

        $this->view->type  = !empty($block) ? $block->block : $type;
        $this->view->id    = $id;
        $this->view->block = $block;
        $this->display();
    }

    /**
     * Print block.
     *
     * @param  int    $id
     * @access public
     * @return void
     */
    public function printBlock($id)
    {
        $block = $this->block->getByID($id);

        if(empty($block)) return false;

        $html = '';
        if($block->block == 'html')
        {
            $html = "<div class='article-content'>" . htmlspecialchars_decode($block->params->html) .'</div>';
        }
        elseif($block->block == 'rss')
        {
            $html = $this->block->getRss($block);
        }
        elseif($block->source != '')
        {
            $html = $this->block->getEntry($block);
        }
        elseif($block->block == 'allEntries')
        {
            $html = $this->fetch('block', 'entries');
        }
        elseif($block->block == 'dynamic')
        {
            $html = $this->fetch('block', 'dynamic');
        }

        die($html);
    }

    /**
     * Sort block.
     *
     * @param  string    $orders
     * @param  string    $app
     * @access public
     * @return void
     */
    public function sort($orders, $app = 'sys')
    {
        $orders    = explode(',', $orders);
        $orderList = $this->block->getBlockList($app);
        $blockList = array();

        foreach($orderList as $block) $blockList[$block->id] = $block;

        foreach($orders as $order => $id)
        {
            if(!$id) continue;

            $block = $blockList[$id];
            if(!isset($block)) continue;

            unset($block->fixedSize);
            $block->order = $order;
            $this->dao->replace(TABLE_BLOCK)->data($block)->exec();
        }

        if(dao::isError()) return $this->send(array('result' => 'fail'));
        return $this->send(array('result' => 'success'));
    }

    /**
     * Resize block
     * @param  integer $id
     * @access public
     * @return void
     */
    public function resize($id, $type, $data)
    {
        $block = $this->block->getByID($id);
        if($block)
        {
            $field = '';
            if($type == 'vertical') $field = 'height';
            if($type == 'horizontal') $field = 'grid';
            if(empty($field)) return $this->send(array('result' => 'fail', 'code' => 400));

            $block->$field = $data;
            $block->params = helper::jsonEncode($block->params);
            $this->dao->replace(TABLE_BLOCK)->data($block)->exec();
            if(dao::isError()) return $this->send(array('result' => 'fail', 'code' => 500));
            return $this->send(array('result' => 'success'));
        }
        else
        {
            return $this->send(array('result' => 'fail', 'code' => 404));
        }
    }


    /**
     * Delete block
     *
     * @param  int    $id
     * @param  string $sys
     * @param  string $type
     * @access public
     * @return void
     */
    public function delete($id, $type = 'delete')
    {
        if($type == 'hidden')
        {
            $this->dao->update(TABLE_BLOCK)->set('hidden')->eq(1)->where('`id`')->eq($id)->exec();
        }
        else
        {
            $this->dao->delete()->from(TABLE_BLOCK)->where('`id`')->eq($id)->exec();
        }
        if(dao::isError()) return $this->send(array('result' => 'fail', 'message' => dao::getError()));
        return $this->send(array('result' => 'success'));
    }

    /**
     * Reset layout.
     * 
     * @param  string    $appName 
     * @access public
     * @return void
     */
    public function reset($appName)
    {
        $this->dao->delete()->from(TABLE_BLOCK)->where('app')->eq($appName)->andWhere('account')->eq($this->app->user->account)->exec();
        $this->dao->delete()->from(TABLE_CONFIG)->where('app')->eq($appName)->andWhere('owner')->eq($this->app->user->account)->andWhere('`key`')->eq('blockInited')->exec();

        if(dao::isError()) return $this->send(array('result' => 'fail', 'message' => dao::getError()));
        return $this->send(array('result' => 'success'));
    }

    /**
     * Display dashboard for app.
     *
     * @param  string    $appName
     * @access public
     * @return void
     */
    public function dashboard($appName)
    {
        $this->app->loadLang('index');
        $blocks = $this->block->getBlockList($appName);
        $inited = empty($this->config->personal->common->blockInited) ? '' : $this->config->personal->common->blockInited;

        /* Init block when vist index first. */
        if(empty($blocks) and !($inited and $inited->app == $appName and $inited->value))
        {
            if($this->block->initBlock($appName)) die(js::reload());
        }

        $shortBlocks = $longBlocks = array();
        foreach($blocks as $key => $block)
        {
            $block->params = json_decode($block->params);

            if(empty($block->params)) $block->params = new stdclass();
            $block->params->account = $this->app->user->account;
            $block->params->uid     = $this->app->user->id;

            $query              = array();
            $query['mode']      = 'getblockdata';
            $query['blockid']   = $block->block;
            $query['hash']      = '';
            $query['lang']      = $this->app->getClientLang();
            $query['sso']       = '';
            $query['app']       = $appName;
            $query['longblock'] = $this->block->isLongBlock($block);
            if(isset($block->params)) $query['param'] = base64_encode(json_encode($block->params));

            $query = http_build_query($query);
            $sign  = $this->config->requestType == 'PATH_INFO' ? '?' : '&';

            if($appName == 'sys')
            {
                $block->blockLink = $this->createLink('entry', 'printBlock', 'id=' . $block->id);
            }
            else
            {
                $block->blockLink = $this->createLink($appName . '.block', 'index') . $sign . $query;
            }

            $moduleName = $block->block;
            if((isset($block->params->type) or isset($block->params->status)) and isset($this->lang->block->moreLinkList->{$moduleName}) and is_array($this->lang->block->moreLinkList->{$moduleName}))
            {
                $type = isset($block->params->type) ? $block->params->type : $block->params->status;
                if(isset($this->lang->block->moreLinkList->{$moduleName}[$type]))
                {
                    list($label, $app, $module, $method, $vars) = explode('|', $this->lang->block->moreLinkList->{$moduleName}[$type]);
                    $block->moreLink = $this->createLink($app . '.' . $module, $method, $vars);
                    $block->appid    = $app == 'sys' ? 'dashboard' : $app;
                }
            }
            else
            {
                if(isset($this->lang->block->moreLinkList->{$moduleName}))
                {
                    if(isset($this->lang->block->moreLinkList->{$moduleName}) && is_string($this->lang->block->moreLinkList->{$moduleName}))
                    {
                        list($label, $app, $module, $method, $vars) = explode('|', $this->lang->block->moreLinkList->{$moduleName});
                        $block->moreLink = $this->createLink($app . '.' . $module, $method, $vars);
                        $block->appid    = $app == 'sys' ? 'dashboard' : $app;
                    }
                }
            }

            if($this->block->isLongBlock($block))
            {
                $longBlocks[$key] = $block;
            }
            else
            {
                $shortBlocks[$key] = $block;
            }
        }

        $this->view->appName     = $appName;
        $this->view->longBlocks  = $longBlocks;
        $this->view->shortBlocks = $shortBlocks;
        $this->display();
    }

    /**
     * Entries block
     *
     * @access public
     * @return void
     */
    public function entries()
    {
        $entries = $this->loadModel('entry')->getEntries($this->app->getViewType() == 'mhtml' ? 'mobile' : 'custom');
        $this->view->entries   = $entries;
        $this->display();
    }

    /**
     * latest dynamic.
     *
     * @access public
     * @return void
     */
    public function dynamic()
    {
        $this->app->loadClass('pager', $static = true);
        $pager = new pager(0, 30, 1);

        $this->view->actions = $this->loadModel('action')->getDynamic('all', 'today', 'date_desc', $pager);
        $this->view->users   = $this->loadModel('user')->getPairs('unofficial');
        $this->display();
    }
}
