<?php
require_once 'library/CE/NE_Plugin.php';

/**
 * DashboardPlugin Model Class
 *
 * @category Model
 * @package  Admin
 * @author   Alberto Vasquez <alberto@clientexec.com>
 * @license  ClientExec License
 * @link     http://www.clientexec.com
 */
class DashboardPlugin extends NE_Plugin
{
    var $name = "Set \$name var";

    /**
     * If set this is used on left bar when viewing plugin names.  Use in the event the above
     * name is to long if left as default CE will use name and concat x number of strings
     * @var string
     */
    var $smallName = false;

    var $description = "Set \$description var";

    /**
     * Used when we have a default setting but we don't want to show in settings
     * If hidefromSettings is set true the plugin will be enabled to all users
     * @var boolean
     */
    var $hideFromSettings = false;

    /**
     * Order of plugin on left panel.
     * @var integer
     */
    var $order = 100;

    /**
     * Bootstrap icon class name to identify the plugin in the left plugin panel
     * defaults to icon-th-large.  Default icon can be changed by updating parent class
     * @var string
     */
    var $iconName = "icon-question-sign";

    /**
     * Determine if this plugin is set as default plugin if admin does not have any other
     * plugins installed
     * @var boolean
     */
    var $default = false;

    /**
     * Determine if each user has ability to customize plugin settings for themselves.
     * False = each user has their own settings
     * True = settings are used for all users
     * Note: if shared plugin is true and plugin is active then all users will have the plugin
     * active.
     * @var boolean
     */
    var $sharedSettings = false;

    /**
     * roleids of staff available to edit this plugin.  This setting is used ONLY if sharedSettings is set to true.
     * example: var $roleIds = array(2);
     * @var array
     */
    var $roleIds = array();

    /**
     * Determine if this plugin should be visible in the sidebar
     * @var boolean
     */
    var $sidebarPlugin = false;

    /**
     * Determine if you want to use the plugin systems cache system by setting this to true
     * If this is false then plugin developer will need to handle their own caching.  For basic
     * plugin usage this should be turned on by setting this value true.
     * @var boolean
     */
    var $cache = false;

    /**
     * Array of config options that can be configured in customize plugin window
     * i.e. var $defaultConfig = array("token" => '',"room" => '');
     * @var array
     */
    var $defaultConfig = array();

    /**
     * JS method to call every time the plugin is selected from the left plugin panel
     * This is useful to bind links that might be cached
     * @var boolean
     */
    var $activeMethod = false;

    /**
     * Additional css style sheets to load for the given plugin
     * i.e. var $cssPages = array('plugins/dashboard/pluginname/somefile.css');
     * @var array
     */
    var $cssPages = array();

    /**
     * Additional js scripts to load for the given plugin
     * i.e. var $jsLibs = array( 'plugins/dashboard/pluginname/somefile.js' );
     * @var array
     */
    var $jsLibs = array();


    /**
    * List of actions available to public without the Action string .. so instead
    * of somemethodAction it would be somemethod
    * i.e. var $jsLibs = array( 'somemethod' );
    * @var array
    */
    var $publicActions = array();

    /**
     * When calling a plugin. When not a view we can supress output.
     * @var string
     */
    var $outputData = true;

    /**
     * Variable used to store plugin data
     * @var array
     */
    private $data = array();

    function __construct($user, $typeOfFetch = 1) {
        parent::__construct($user,$typeOfFetch);
    }

    /**
     * unregister events we are listening to
     * @return void
     */
    public function unregisterevents()
    {

    }

    /**
    * Output generated by the plugin (don't echo it, just return it).
    * These requests are always done through AJAX and the content
    * is returned to fill in the dashboard panel.
    *
    * @return string Plugin's HTML
    */
    public function getPanel()
    {

        if (!$this->sidebarPlugin) {
            return;
        }

        //let's add some text to cache content if this is cachable
        $html = "";

        if ($this->cache) {
            $html .= "<script type='text/javascript'>";
            $html .= "$(document).ready(function(){";
            $html .= "if(clientexec.pluginMgr) clientexec.pluginMgr.setContent('".$this->internalName."',undefined,true);";
            $html .= "});";
            $html .= "</script>";
        }
        return $this->view->render('index.phtml').$html;
    }

    /**
     * Process GET/POST parameters for this plugin to do an action.
     * Return any output from this function so it can be output by the parent class.
     *
     * @return void
     */
    public function callAction($callback = false)
    {

        if (isset($_GET['pluginaction'])) {
            $_REQUEST['pluginaction'] = $_GET['pluginaction'];
        } else if (isset($_GET['pluginAction'])) {
            $_REQUEST['pluginaction'] = $_GET['pluginAction'];
        }

        //do not allow calling methods in public section
        //unless it is set to be public
        if ( !$this->user->isAdmin(true) && ( !in_array($_REQUEST['pluginaction'], $this->publicActions) )) {
            CE_Lib::log(1,"Running ".$_REQUEST['pluginaction']." on plugin ".$this->name." without admin rights");
            return;
        } else {
            $methodtocall = strtolower($_REQUEST['pluginaction'])."Action";
        }

        if (method_exists($this,$methodtocall)) {
            $returnData = $this->$methodtocall();
            if ($callback) {
                return $returnData;
            } else {
                if (!isset($_GET['view'])) {
                    // $returnData contains stuff coming from the client-side that might
                    // not be properlly encoded, so let's swallow any errors
                    // e.g. https://app.getsentry.com/clientexec/clientexec-beta/group/13914855
                    if ($this->outputData) echo @Zend_Json::encode($returnData);
                }
            }
        } else {
            CE_Lib::log(1,'Calling a plugin action, '.$_REQUEST['pluginaction'].', that does not exist');
        }

    }

    /**
     * Loads api information and if not found uses the configuration arrays
     *
     * @return void
     */
    function loadConfigSettings()
    {

        $setting = $this->retrieveData("apiinfo");

        $configChanged = false;
        if ($setting == "") {
            //create default api settings
            $configSettings = array();
            $configSettings['vars'] = $this->defaultConfig;
        } else {
            $configSettings = unserialize($setting);

            //let's compare the config values
            //in the event they were updated by a later version
            foreach($configSettings['vars'] as $key => $setting) {
                if (!isset($this->defaultConfig[$key])) {
                    $configChanged = true;
                } else {
                    $this->defaultConfig[$key] = $configSettings['vars'][$key];
                }
            }

            if ($configChanged) {
                $configSettings['vars'] = $this->defaultConfig;
            }

        }

        return $configSettings;
    }

    function getAPISettings()
    {
        $configSettings = $this->loadConfigSettings();
        $dataArray["error"] = false;
        $dataArray["success"] = true;
        $dataArray["message"] = "";
        $dataArray["data"] = $configSettings;
        return $dataArray;
    }

    function saveAPISettings()
    {

        $configSettings = array(); //clear out anything we had before
        $pluginsettings = $_GET['pluginfields'];

        $aSettings = array();
        foreach($pluginsettings as $key => $value) {
            $aSettings[$key] = $value;
        }

        $configSettings['vars'] = $aSettings;

        $this->storeData('apiinfo', serialize($configSettings));

        $dataArray["error"] = false;
        $dataArray["success"] = true;
        $dataArray["message"] = "";
        return $dataArray;
    }

    /**
     * Get Css Pages array to show for plugin
     *
     * @return array
     */
    function getCssPages()
    {
        return $this->cssPages;
    }

    /**
     * Get JS Pages array to show for plugin
     *
     * @return array
     */
    function getJsLibs()
    {
        return $this->jsLibs;
    }

    /**
     * Return if plugin is the default
     *
     * @return bool
     */
    function isDefault()
    {
        return $this->default;
    }


    /**
     * Use this function to store data for the currently logged in user
     * and this plugin.  Other users and plugins will not be able to see
     * the data stored here.
     *
     * @param string $key   The key used to store this data.
     * @param string $value The value to be stored.
     *
     * @return void
     */
    function storeData($key, $value)
    {
        $this->_loadStoredData();

        //if plugin is shared then userid should be 0 (shared)
        $userid = $this->user->getId();
        if ($this->sharedSettings) {
           $userid = 0;
        }

        if (isset($this->data[$key])) {
            $query = "UPDATE plugin_custom_data SET value=? WHERE name=? AND plugin_name=? AND plugin_type=? AND user_id=?";
        } else {
            $query = "INSERT INTO plugin_custom_data (value, name, plugin_name, plugin_type, user_id) VALUES (?,?,?,?,?)";
        }
        $this->db->query($query, $value, $key, $this->internalName, 'dashboard', $userid);

        $this->data[$key] = $value;
    }

    /**
     * Use this function to retrieve stored data for the currently logged
     * in user and this plugin.  Data stored for other users and other plugins
     * will not be available here.
     *
     * @param string $key The key used to store the data.
     *
     * @return The value that was prevously stored for this plugin and user.  The empty string is returned if data is not available.
     */
    function retrieveData($key)
    {
        $this->_loadStoredData();
        if (isset($this->data[$key])) return $this->data[$key];

        return '';
    }

    /**
     * Use this function to determine if stored data exists for this user/plugin/key combination.
     *
     * @param string $key The key to check for.
     *
     * @return boolean true if the key exists, false otherwise.
     */
    function storedDataExists($key)
    {
        $this->_loadStoredData();
        return isset($this->data[$key]);
    }

    /**
     * Load stored data
     *
     * @return void
     */
    private function _loadStoredData()
    {
        // only load the data if not already loaded
        if (sizeof($this->data) > 0) return;

        //if plugin is shared then userid should be 0 (shared)
        $userid = $this->user->getId();
        if ($this->sharedSettings) {
           $userid = 0;
        }

        $query = "SELECT name, value FROM plugin_custom_data WHERE user_id=? AND plugin_type=? AND plugin_name=?";
        $result = $this->db->query($query, $userid, 'dashboard', $this->internalName);

        while ($row = $result->fetch()) {
            $this->data[$row['name']] = $row['value'];
        }
    }
}

?>
