<?PHP

class AddThis extends Plugin
{

    /**
     * Register information about this plugin.
     */
    public function Register()
    {
        $this->Name = "AddThis";
        $this->Version = "1.0.0";
        $this->Description = "Functionality for printing AddThis sharing buttons.";
        $this->Author = "Internet Scout";
        $this->Url = "http://scout.wisc.edu/cwis/";
        $this->Email = "scout@scout.wisc.edu";
        $this->Requires = array("CWISCore" => "2.1.0");
        $this->EnabledByDefault = FALSE;

        $this->CfgSetup["GlobalUsername"] = array(
          "Type" => "Text",
          "Label" => "Global Username",
          "Help" => "Global AddThis account username");
    }

    /**
     * Declare the events this plugin provides to the application framework.
     * @return an array of the events this plugin provides
     */
    public function DeclareEvents()
    {
        return array(
            "ADDTHIS_GET_GLOBAL_USERNAME"
              => ApplicationFramework::EVENTTYPE_FIRST,
            "ADDTHIS_PRINT_WIDGET_JAVASCRIPT"
              => ApplicationFramework::EVENTTYPE_DEFAULT,
            "ADDTHIS_PRINT_SIMPLE_BUTTON"
              => ApplicationFramework::EVENTTYPE_DEFAULT);
    }

    /**
     * Hook the events into the application framework.
     * @return an array of events to be hooked into the application framework
     */
    public function HookEvents()
    {
        return array(
            "ADDTHIS_PRINT_WIDGET_JAVASCRIPT" => "PrintWidgetJavascript",
            "ADDTHIS_PRINT_SIMPLE_BUTTON" => "PrintSimpleButton");
    }

    /**
     * Get the global AddThis username.
     * @return AddThis username
     */
    public function GetGlobalUsername()
    {
        return $this->ConfigSetting("GlobalUsername");
    }

    /**
     * Print the required Javascript script tag to load the AddThis code. Uses
     * the global username if it is set and no parameters are passed to this
     * method.
     * @param $Username optional username for analytics purposes
     */
    public function PrintWidgetJavascript($Username=NULL)
    {
        $GlobalUsername = $this->GetGlobalUsername();
        $ParameterCount = func_num_args();

        print '<script type="text/javascript"';
        print ' src="http://s7.addthis.com/js/250/addthis_widget.js';

        if (!is_null($Username))
        {
            print "#".$Username;
        }

        else if (!is_null($GlobalUsername)
            && strlen($GlobalUsername)
            && $ParameterCount < 1)
        {
            print "#".$GlobalUsername;
        }

        print '"></script>';
    }

    /**
     * Print a simple AddThis sharing button along with the required widget
     * Javascript include. Uses the global username if it is set and no
     * the username parameter is null.
     * @param $Username optional username for analytics purposes
     * @param $TrackClickback set the datatrackclickback option if TRUE
     */
    public function PrintSimpleButton($Username=NULL, $TrackClickback=FALSE)
    {
        $Button = new AddThis_Button;
        $Button->PrintHtml();

        if (TRUE === $TrackClickback)
        {
            $UiConfig = new AddThis_UiConfig;
            $UiConfig->DataTrackClickback = TRUE;
            $UiConfig->PrintJavascript();
        }

        # username is set
        if (FALSE === is_null($Username))
        {
            $this->PrintWidgetJavascript($Username);
        }

        # otherwise allow the global username to be used
        else
        {
            $this->PrintWidgetJavascript();
        }
    }

}

# If we're running under an older version of PHP which doesn't ship
# with a json_encode, provide a workaround.
if (!function_exists('json_encode'))
{
    function json_encode($a=false)
    {
        if (is_null($a)) return 'null';
        if ($a === false) return 'false';
        if ($a === true) return 'true';
        if (is_scalar($a))
        {
            if (is_float($a))
            {
                // Always use "." for floats.
                return floatval(str_replace(",", ".", strval($a)));
            }

            if (is_string($a))
            {
                static $jsonReplaces = array(
                    array("\\",    "/","\n", "\t", "\r", "\b", "\f", '"'),
                    array('\\\\','\\/','\\n','\\t','\\r','\\b','\\f','\"'));
                return '"' . str_replace($jsonReplaces[0],
                                         $jsonReplaces[1], $a) . '"';
            }
            else
                return $a;
        }
        $isList = true;
        for ($i = 0, reset($a); $i < count($a); $i++, next($a))
        {
            if (key($a) !== $i)
            {
                $isList = false;
                break;
            }
        }
        $result = array();
        if ($isList)
        {
            foreach ($a as $v) $result[] = json_encode($v);
            return '[' . join(',', $result) . ']';
        }
        else
        {
            foreach ($a as $k => $v) $result[] =
                json_encode($k).':'.json_encode($v);
            return '{' . join(',', $result) . '}';
        }
    }
}
