Add IMP inline script handling functions.
authorMichael M Slusarz <slusarz@curecanti.org>
Thu, 16 Jul 2009 19:55:03 +0000 (13:55 -0600)
committerMichael M Slusarz <slusarz@curecanti.org>
Thu, 16 Jul 2009 19:55:03 +0000 (13:55 -0600)
Again, this will probably eventually need to be moved elsewhere, but
it needs to be moved out of IMP immediately since several things moving
to framework rely on this code.

framework/Core/lib/Horde.php

index 2caa803..e6a329f 100644 (file)
@@ -57,6 +57,13 @@ class Horde
     static protected $_hooksLoaded = array();
 
     /**
+     * Inline script cache.
+     *
+     * @var array
+     */
+    static protected $_inlineScript = array();
+
+    /**
      * Logs a message to the global Horde log backend.
      *
      * @param mixed $message     Either a string or an object with a
@@ -1866,4 +1873,68 @@ HTML;
         exit;
     }
 
+    /**
+     * Add inline javascript to the output buffer.
+     *
+     * @param mixed $script    The script text to add (can be stored in an
+     *                         array also).
+     * @param string $onload   Load the script after the page has loaded?
+     *                         Either 'dom' (on dom:loaded), 'load'.
+     */
+    static public function addInlineScript($script, $onload = false)
+    {
+        if (is_array($script)) {
+            $script = implode(';', $script);
+        }
+
+        $script = trim($script);
+        if (empty($script)) {
+            return;
+        }
+
+        switch ($onload) {
+        case 'dom':
+            $script = 'document.observe("dom:loaded", function() {' . $script . '});';
+            break;
+
+        case 'load':
+            $script = 'Event.observe(window, "load", function() {' . $script . '});';
+            break;
+        }
+
+        self::$_inlineScript[] = $script;
+
+        // If headers have already been sent, we need to output a
+        // <script> tag directly.
+        if (ob_get_length() || headers_sent()) {
+            self::outputInlineScript();
+        }
+    }
+
+    /**
+     * Print pending inline javascript to the output buffer.
+     */
+    static public function outputInlineScript()
+    {
+        if (!empty(self::$_inlineScript)) {
+            echo self::wrapInlineScript(self::$_inlineScript);
+        }
+
+        self::$_inlineScript = array();
+    }
+
+    /**
+     * Print inline javascript to output buffer after wrapping with necessary
+     * javascript tags.
+     *
+     * @param array $script  The script to output.
+     *
+     * @return string  The script with the necessary HTML javascript tags
+     *                 appended.
+     */
+    static public function wrapInlineScript($script)
+    {
+        return '<script type="text/javascript">//<![CDATA[' . "\n" . implode("\n", $script) . "\n//]]></script>\n";
+    }
+
 }