<?PHP

/**
 * CWIS plugin that provides functionality for displaying AddThis sharing
 * buttons
 */
class AddThis extends Plugin
{

    /**
     * Register information about this plugin.
     * @return void
     */
    public function Register()
    {
        $this->Name = "AddThis";
        $this->Version = "1.0.1";
        $this->Description = "Functionality for displaying 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 array the events this plugin provides
     */
    public function DeclareEvents()
    {
        return array(
            "ADDTHIS_PRINT_SIMPLE_BUTTON"
              => ApplicationFramework::EVENTTYPE_DEFAULT,

            # these events are no longer used but are here to avoid
            # generating exceptions
            "ADDTHIS_GET_GLOBAL_USERNAME"
               => ApplicationFramework::EVENTTYPE_FIRST,
            "ADDTHIS_PRINT_WIDGET_JAVASCRIPT"
               => ApplicationFramework::EVENTTYPE_DEFAULT);
    }

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

    /**
     * Print the required Javascript script element to load the AddThis code.
     * Uses the global username if it is set and an user name isn't passed to
     * this method.
     * @param string $Username optional username for analytics purposes
     * @return void
     */
    public function PrintWidgetJavascript($Username=NULL)
    {
        $GlobalUsername = $this->GetGlobalUsername();

        $Src = OurHttpProtocol() . "//";
        $Src .= "s7.addthis.com/js/250/addthis_widget.js";

        # AddThis user name given as a parameter, so add it
        if (!is_null($Username) && strlen($Username))
        {
            $Src .= "#" . $Username;
        }

        # global AddThis user name is set
        else if (!is_null($GlobalUsername) && strlen($GlobalUsername))
        {
            $Src .= "#" . $GlobalUsername;
        }

?>
        <script type="text/javascript"  src="<?PHP print $Src; ?>"></script>
<?PHP
    }

    /**
     * Print a simple AddThis sharing button along with the required widget
     * Javascript include. Uses the global username if it is set and an user
     * name isn't passed to this method.
     * @param string $Username optional username for analytics purposes
     * @param boolean $TrackClickback set the datatrackclickback option if TRUE
     * @return void
     */
    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();
        }
    }

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

}

# 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) . '}';
        }
    }
}
