PageRenderTime 26ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/documentrepository/protected/extensions/tinymce/assets/tiny_mce/tiny_mce_gzip.php

https://github.com/ereslibre/documentrepository
PHP | 328 lines | 159 code | 58 blank | 111 comment | 39 complexity | 35f362621218cb128d979292a36a27d0 MD5 | raw file
  1. <?php
  2. /**
  3. * tiny_mce_gzip.php
  4. *
  5. * Copyright 2010, Moxiecode Systems AB
  6. * Released under LGPL License.
  7. *
  8. * License: http://tinymce.moxiecode.com/license
  9. * Contributing: http://tinymce.moxiecode.com/contributing
  10. */
  11. // Handle incoming request if it's a script call
  12. if (TinyMCE_Compressor::getParam("js")) {
  13. // Default settings
  14. $tinyMCECompressor = new TinyMCE_Compressor(array(
  15. /*
  16. * Add any site-specific defaults here that you may wish to implement. For example:
  17. *
  18. * "languages" => "en",
  19. * "cache_dir" => realpath(dirname(__FILE__) . "/../../_cache"),
  20. * "files" => "somescript,anotherscript",
  21. * "expires" => "1m",
  22. */
  23. ));
  24. // Handle request, compress and stream to client
  25. $tinyMCECompressor->handleRequest();
  26. }
  27. /**
  28. * This class combines and compresses the TinyMCE core, plugins, themes and
  29. * language packs into one disk cached gzipped request. It improves the loading speed of TinyMCE dramatically but
  30. * still provides dynamic initialization.
  31. *
  32. * Example of direct usage:
  33. * require_once("../jscripts/tiny_mce/tiny_mce_gzip.php");
  34. *
  35. * // Renders script tag with compressed scripts
  36. * TinyMCE_Compressor::renderTag(array(
  37. * "url" => "../jscripts/tiny_mce/tiny_mce_gzip.php",
  38. * "plugins" => "pagebreak,style",
  39. * "themes" => "advanced",
  40. * "languages" => "en"
  41. * ));
  42. */
  43. class TinyMCE_Compressor {
  44. private $files, $settings;
  45. private static $defaultSettings = array(
  46. "plugins" => "",
  47. "themes" => "",
  48. "languages" => "",
  49. "disk_cache" => true,
  50. "expires" => "30d",
  51. "cache_dir" => "",
  52. "compress" => true,
  53. "suffix" => "",
  54. "files" => "",
  55. "source" => false,
  56. );
  57. /**
  58. * Constructs a new compressor instance.
  59. *
  60. * @param Array $settings Name/value array with non-default settings for the compressor instance.
  61. */
  62. public function __construct($settings = array()) {
  63. $this->settings = array_merge(self::$defaultSettings, $settings);
  64. if (empty($this->settings["cache_dir"]))
  65. $this->settings["cache_dir"] = dirname(__FILE__);
  66. }
  67. /**
  68. * Adds a file to the concatenation/compression process.
  69. *
  70. * @param String $path Path to the file to include in the compressed package/output.
  71. */
  72. public function &addFile($file) {
  73. $this->files .= ($this->files ? "," : "") . $file;
  74. return $this;
  75. }
  76. /**
  77. * Handles the incoming HTTP request and sends back a compressed script depending on settings and client support.
  78. */
  79. public function handleRequest() {
  80. $files = array();
  81. $supportsGzip = false;
  82. $expiresOffset = $this->parseTime($this->settings["expires"]);
  83. $tinymceDir = dirname(__FILE__);
  84. // Override settings with querystring params
  85. $plugins = self::getParam("plugins");
  86. if ($plugins)
  87. $this->settings["plugins"] = $plugins;
  88. $plugins = explode(',', $this->settings["plugins"]);
  89. $themes = self::getParam("themes");
  90. if ($themes)
  91. $this->settings["themes"] = $themes;
  92. $themes = explode(',', $this->settings["themes"]);
  93. $languages = self::getParam("languages");
  94. if ($languages)
  95. $this->settings["languages"] = $languages;
  96. $languages = explode(',', $this->settings["languages"]);
  97. $tagFiles = self::getParam("files");
  98. if ($tagFiles)
  99. $this->settings["files"] = $tagFiles;
  100. $diskCache = self::getParam("diskcache");
  101. if ($diskCache)
  102. $this->settings["disk_cache"] = ($diskCache === "true");
  103. $src = self::getParam("src");
  104. if ($src)
  105. $this->settings["source"] = ($src === "true");
  106. // Add core
  107. $files[] = "tiny_mce";
  108. foreach ($languages as $language)
  109. $files[] = "langs/$language";
  110. // Add plugins
  111. foreach ($plugins as $plugin) {
  112. $files[] = "plugins/$plugin/editor_plugin";
  113. foreach ($languages as $language)
  114. $files[] = "plugins/$plugin/langs/$language";
  115. }
  116. // Add themes
  117. foreach ($themes as $theme) {
  118. $files[] = "themes/$theme/editor_template";
  119. foreach ($languages as $language)
  120. $files[] = "themes/$theme/langs/$language";
  121. }
  122. // Add any specified files.
  123. $allFiles = array_merge($files, explode(',', $this->settings['files']));
  124. // Process source files
  125. for ($i = 0; $i < count($allFiles); $i++) {
  126. $file = $allFiles[$i];
  127. if ($this->settings["source"] && file_exists($file . "_src.js")) {
  128. $file .= "_src.js";
  129. } else if (file_exists($file . ".js")) {
  130. $file .= ".js";
  131. } else {
  132. $file = "";
  133. }
  134. $allFiles[$i] = $file;
  135. }
  136. // Generate hash for all files
  137. $hash = md5(implode('', $allFiles));
  138. // Check if it supports gzip
  139. $zlibOn = ini_get('zlib.output_compression') || (ini_set('zlib.output_compression', 0) === false);
  140. $encodings = (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) ? strtolower($_SERVER['HTTP_ACCEPT_ENCODING']) : "";
  141. $encoding = preg_match( '/\b(x-gzip|gzip)\b/', $encodings, $match) ? $match[1] : "";
  142. // Is northon antivirus header
  143. if (isset($_SERVER['---------------']))
  144. $encoding = "x-gzip";
  145. $supportsGzip = $this->settings['compress'] && !empty($encoding) && !$zlibOn && function_exists('gzencode');
  146. // Set cache file name
  147. $cacheFile = $this->settings["cache_dir"] . "/" . $hash . ($supportsGzip ? ".gz" : ".js");
  148. // Set headers
  149. header("Content-type: text/javascript");
  150. header("Vary: Accept-Encoding"); // Handle proxies
  151. header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
  152. header("Cache-Control: public, max-age=" . $expiresOffset);
  153. if ($supportsGzip)
  154. header("Content-Encoding: " . $encoding);
  155. // Use cached file
  156. if ($this->settings['disk_cache'] && file_exists($cacheFile)) {
  157. readfile($cacheFile);
  158. return;
  159. }
  160. // Set base URL for where tinymce is loaded from
  161. $buffer = "var tinyMCEPreInit={base:'" . dirname($_SERVER["SCRIPT_NAME"]) . "',suffix:''};";
  162. // Load all tinymce script files into buffer
  163. foreach ($allFiles as $file) {
  164. if ($file) {
  165. $fileContents = $this->getFileContents($tinymceDir . "/" . $file);
  166. // $buffer .= "\n//-FILE-$tinymceDir/$file (". strlen($fileContents) . " bytes)\n";
  167. $buffer .= $fileContents;
  168. }
  169. }
  170. // Mark all themes, plugins and languages as done
  171. $buffer .= 'tinymce.each("' . implode(',', $files) . '".split(","),function(f){tinymce.ScriptLoader.markDone(tinyMCE.baseURL+"/"+f+".js");});';
  172. // Compress data
  173. if ($supportsGzip)
  174. $buffer = gzencode($buffer, 9, FORCE_GZIP);
  175. // Write cached file
  176. if ($this->settings["disk_cache"])
  177. @file_put_contents($cacheFile, $buffer);
  178. // Stream contents to client
  179. echo $buffer;
  180. }
  181. /**
  182. * Renders a script tag that loads the TinyMCE script.
  183. *
  184. * @param Array $settings Name/value array with settings for the script tag.
  185. * @param Bool $return The script tag is return instead of being output if true
  186. * @return String the tag is returned if $return is true
  187. */
  188. public static function renderTag($tagSettings, $return = false) {
  189. $settings = array_merge(self::$defaultSettings, $tagSettings);
  190. if (empty($settings["cache_dir"]))
  191. $settings["cache_dir"] = dirname(__FILE__);
  192. $scriptSrc = $settings["url"] . "?js=1";
  193. // Add plugins
  194. if (isset($settings["plugins"]))
  195. $scriptSrc .= "&plugins=" . (is_array($settings["plugins"]) ? implode(',', $settings["plugins"]) : $settings["plugins"]);
  196. // Add themes
  197. if (isset($settings["themes"]))
  198. $scriptSrc .= "&themes=" . (is_array($settings["themes"]) ? implode(',', $settings["themes"]) : $settings["themes"]);
  199. // Add languages
  200. if (isset($settings["languages"]))
  201. $scriptSrc .= "&languages=" . (is_array($settings["languages"]) ? implode(',', $settings["languages"]) : $settings["languages"]);
  202. // Add disk_cache
  203. if (isset($settings["disk_cache"]))
  204. $scriptSrc .= "&diskcache=" . ($settings["disk_cache"] === true ? "true" : "false");
  205. // Add any explicitly specified files if the default settings have been overriden by the tag ones
  206. /*
  207. * Specifying tag files will override (rather than merge with) any site-specific ones set in the
  208. * TinyMCE_Compressor object creation. Note that since the parameter parser limits content to alphanumeric
  209. * only base filenames can be specified. The file extension is assumed to be ".js" and the directory is
  210. * the TinyMCE root directory. A typical use of this is to include a script which initiates the TinyMCE object.
  211. */
  212. if (isset($tagSettings["files"]))
  213. $scriptSrc .= "&files=" .(is_array($settings["files"]) ? implode(',', $settings["files"]) : $settings["files"]);
  214. // Add src flag
  215. if (isset($settings["source"]))
  216. $scriptSrc .= "&src=" . ($settings["source"] === true ? "true" : "false");
  217. $scriptTag = '<script type="text/javascript" src="' . htmlspecialchars($scriptSrc) . '"></script>';
  218. if ($return) {
  219. return $scriptTag;
  220. } else {
  221. echo $scriptTag;
  222. }
  223. }
  224. /**
  225. * Returns a sanitized query string parameter.
  226. *
  227. * @param String $name Name of the query string param to get.
  228. * @param String $default Default value if the query string item shouldn't exist.
  229. * @return String Sanitized query string parameter value.
  230. */
  231. public static function getParam($name, $default = "") {
  232. if (!isset($_GET[$name]))
  233. return $default;
  234. return preg_replace("/[^0-9a-z\-_,]+/i", "", $_GET[$name]); // Sanatize for security, remove anything but 0-9,a-z,-_,
  235. }
  236. /**
  237. * Parses the specified time format into seconds. Supports formats like 10h, 10d, 10m.
  238. *
  239. * @param String $time Time format to convert into seconds.
  240. * @return Int Number of seconds for the specified format.
  241. */
  242. private function parseTime($time) {
  243. $multipel = 1;
  244. // Hours
  245. if (strpos($time, "h") > 0)
  246. $multipel = 3600;
  247. // Days
  248. if (strpos($time, "d") > 0)
  249. $multipel = 86400;
  250. // Months
  251. if (strpos($time, "m") > 0)
  252. $multipel = 2592000;
  253. // Trim string
  254. return intval($time) * $multipel;
  255. }
  256. /**
  257. * Returns the contents of the script file if it exists and removes the UTF-8 BOM header if it exists.
  258. *
  259. * @param String $file File to load.
  260. * @return String File contents or empty string if it doesn't exist.
  261. */
  262. private function getFileContents($file) {
  263. $content = file_get_contents($file);
  264. // Remove UTF-8 BOM
  265. if (substr($content, 0, 3) === pack("CCC", 0xef, 0xbb, 0xbf))
  266. $content = substr($content, 3);
  267. return $content;
  268. }
  269. }
  270. ?>