Merge pull request #12010 from JMAConsulting/dev-core-70
[civicrm-core.git] / CRM / Admin / Page / CKEditorConfig.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2018
32 */
33
34 /**
35 * Page for configuring CKEditor options.
36 *
37 * Note that while this is implemented as a CRM_Core_Page, it is actually a form.
38 * Because the form needs to be submitted and refreshed via javascript, it seemed like
39 * Quickform and CRM_Core_Form/Controller might get in the way.
40 */
41 class CRM_Admin_Page_CKEditorConfig extends CRM_Core_Page {
42
43 const CONFIG_FILEPATH = '[civicrm.files]/persist/crm-ckeditor-';
44
45 /**
46 * Settings that cannot be configured in "advanced options"
47 *
48 * @var array
49 */
50 public $blackList = array(
51 'on',
52 'skin',
53 'extraPlugins',
54 'toolbarGroups',
55 'removeButtons',
56 'filebrowserBrowseUrl',
57 'filebrowserImageBrowseUrl',
58 'filebrowserFlashBrowseUrl',
59 'filebrowserUploadUrl',
60 'filebrowserImageUploadUrl',
61 'filebrowserFlashUploadUrl',
62 );
63
64 public $preset;
65
66 /**
67 * Run page.
68 *
69 * @return string
70 */
71 public function run() {
72 $this->preset = CRM_Utils_Array::value('preset', $_REQUEST, 'default');
73
74 // If the form was submitted, take appropriate action.
75 if (!empty($_POST['revert'])) {
76 self::deleteConfigFile($this->preset);
77 self::setConfigDefault();
78 }
79 elseif (!empty($_POST['config'])) {
80 $this->save($_POST);
81 }
82
83 $settings = $this->getConfigSettings();
84
85 CRM_Core_Resources::singleton()
86 ->addScriptFile('civicrm', 'bower_components/ckeditor/ckeditor.js', 0, 'page-header')
87 ->addScriptFile('civicrm', 'bower_components/ckeditor/samples/toolbarconfigurator/js/fulltoolbareditor.js', 1)
88 ->addScriptFile('civicrm', 'bower_components/ckeditor/samples/toolbarconfigurator/js/abstracttoolbarmodifier.js', 2)
89 ->addScriptFile('civicrm', 'bower_components/ckeditor/samples/toolbarconfigurator/js/toolbarmodifier.js', 3)
90 ->addScriptFile('civicrm', 'js/wysiwyg/admin.ckeditor-configurator.js', 10)
91 ->addStyleFile('civicrm', 'bower_components/ckeditor/samples/toolbarconfigurator/css/fontello.css')
92 ->addStyleFile('civicrm', 'bower_components/ckeditor/samples/css/samples.css')
93 ->addVars('ckConfig', array(
94 'plugins' => array_values($this->getCKPlugins()),
95 'blacklist' => $this->blackList,
96 'settings' => $settings,
97 ));
98
99 $configUrl = self::getConfigUrl($this->preset) ?: self::getConfigUrl('default');
100
101 $this->assign('preset', $this->preset);
102 $this->assign('presets', CRM_Core_OptionGroup::values('wysiwyg_presets', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name'));
103 $this->assign('skins', $this->getCKSkins());
104 $this->assign('skin', CRM_Utils_Array::value('skin', $settings));
105 $this->assign('extraPlugins', CRM_Utils_Array::value('extraPlugins', $settings));
106 $this->assign('configUrl', $configUrl);
107 $this->assign('revertConfirm', htmlspecialchars(ts('Are you sure you want to revert all changes?', array('escape' => 'js'))));
108
109 CRM_Utils_System::appendBreadCrumb(array(array(
110 'url' => CRM_Utils_System::url('civicrm/admin/setting/preferences/display', 'reset=1'),
111 'title' => ts('Display Preferences'),
112 )));
113
114 return parent::run();
115 }
116
117 /**
118 * Generate the config js file based on posted data.
119 *
120 * @param array $params
121 */
122 public function save($params) {
123 $config = self::fileHeader()
124 // Standardize line-endings
125 . preg_replace('~\R~u', "\n", $params['config']);
126
127 // Use all params starting with config_
128 foreach ($params as $key => $val) {
129 $val = trim($val);
130 if (strpos($key, 'config_') === 0 && strlen($val)) {
131 if ($val != 'true' && $val != 'false' && $val != 'null' && $val[0] != '{' && $val[0] != '[' && !is_numeric($val)) {
132 $val = json_encode($val, JSON_UNESCAPED_SLASHES);
133 }
134 elseif ($val[0] == '{' || $val[0] == '[') {
135 if (!is_array(json_decode($val, TRUE))) {
136 // Invalid JSON. Do not save.
137 continue;
138 }
139 }
140 $pos = strrpos($config, '};');
141 $key = preg_replace('/^config_/', 'config.', $key);
142 $setting = "\n\t{$key} = {$val};\n";
143 $config = substr_replace($config, $setting, $pos, 0);
144 }
145 }
146 self::saveConfigFile($this->preset, $config);
147 if (!empty($params['save'])) {
148 CRM_Core_Session::setStatus(ts("You may need to clear your browser's cache to see the changes in CiviCRM."), ts('CKEditor Saved'), 'success');
149 }
150 }
151
152 /**
153 * Get available CKEditor plugin list.
154 *
155 * @return array
156 */
157 private function getCKPlugins() {
158 $plugins = array();
159 $pluginDir = Civi::paths()->getPath('[civicrm.root]/bower_components/ckeditor/plugins');
160
161 foreach (glob($pluginDir . '/*', GLOB_ONLYDIR) as $dir) {
162 $dir = rtrim(str_replace('\\', '/', $dir), '/');
163 $name = substr($dir, strrpos($dir, '/') + 1);
164 $dir = CRM_Utils_file::addTrailingSlash($dir, '/');
165 if (is_file($dir . 'plugin.js')) {
166 $plugins[$name] = array(
167 'id' => $name,
168 'text' => ucfirst($name),
169 'icon' => NULL,
170 );
171 if (is_dir($dir . "icons")) {
172 if (is_file($dir . "icons/$name.png")) {
173 $plugins[$name]['icon'] = "bower_components/ckeditor/plugins/$name/icons/$name.png";
174 }
175 elseif (glob($dir . "icons/*.png")) {
176 $icon = CRM_Utils_Array::first(glob($dir . "icons/*.png"));
177 $icon = rtrim(str_replace('\\', '/', $icon), '/');
178 $plugins[$name]['icon'] = "bower_components/ckeditor/plugins/$name/icons/" . substr($icon, strrpos($icon, '/') + 1);
179 }
180 }
181 }
182 }
183
184 return $plugins;
185 }
186
187 /**
188 * Get available CKEditor skins.
189 *
190 * @return array
191 */
192 private function getCKSkins() {
193 $skins = array();
194 $skinDir = Civi::paths()->getPath('[civicrm.root]/bower_components/ckeditor/skins');
195 foreach (glob($skinDir . '/*', GLOB_ONLYDIR) as $dir) {
196 $dir = rtrim(str_replace('\\', '/', $dir), '/');
197 $skins[] = substr($dir, strrpos($dir, '/') + 1);
198 }
199 return $skins;
200 }
201
202 /**
203 * @return array
204 */
205 private function getConfigSettings() {
206 $matches = $result = array();
207 $file = self::getConfigFile($this->preset) ?: self::getConfigFile('default');
208 $result['skin'] = 'moono';
209 if ($file) {
210 $contents = file_get_contents($file);
211 preg_match_all("/\sconfig\.(\w+)\s?=\s?([^;]*);/", $contents, $matches);
212 foreach ($matches[1] as $i => $match) {
213 $result[$match] = trim($matches[2][$i], ' "\'');
214 }
215 }
216 return $result;
217 }
218
219 /**
220 * @param string $preset
221 * Omit to get an array of all presets
222 * @return array|null|string
223 */
224 public static function getConfigUrl($preset = NULL) {
225 $items = array();
226 $presets = CRM_Core_OptionGroup::values('wysiwyg_presets', FALSE, FALSE, FALSE, NULL, 'name');
227 foreach ($presets as $key => $name) {
228 if (self::getConfigFile($name)) {
229 $items[$name] = Civi::paths()->getUrl(self::CONFIG_FILEPATH . $name . '.js', 'absolute');
230 }
231 }
232 return $preset ? CRM_Utils_Array::value($preset, $items) : $items;
233 }
234
235 /**
236 * @param string $preset
237 *
238 * @return null|string
239 */
240 public static function getConfigFile($preset = 'default') {
241 $fileName = Civi::paths()->getPath(self::CONFIG_FILEPATH . $preset . '.js');
242 return is_file($fileName) ? $fileName : NULL;
243 }
244
245 /**
246 * @param string $contents
247 */
248 public static function saveConfigFile($preset, $contents) {
249 $file = Civi::paths()->getPath(self::CONFIG_FILEPATH . $preset . '.js');
250 file_put_contents($file, $contents);
251 }
252
253 /**
254 * Delete config file.
255 */
256 public static function deleteConfigFile($preset) {
257 $file = self::getConfigFile($preset);
258 if ($file) {
259 unlink($file);
260 }
261 }
262
263 /**
264 * Create default config file if it doesn't exist
265 */
266 public static function setConfigDefault() {
267 if (!self::getConfigFile()) {
268 $config = self::fileHeader() . "CKEDITOR.editorConfig = function( config ) {\n\tconfig.allowedContent = true;\n};\n";
269 // Make sure directories exist
270 if (!is_dir(Civi::paths()->getPath('[civicrm.files]/persist'))) {
271 mkdir(Civi::paths()->getPath('[civicrm.files]/persist'));
272 }
273 $newFileName = Civi::paths()->getPath(self::CONFIG_FILEPATH . 'default.js');
274 file_put_contents($newFileName, $config);
275 }
276 }
277
278 /**
279 * @return string
280 */
281 public static function fileHeader() {
282 return "/**\n"
283 . " * CKEditor config file auto-generated by CiviCRM (" . date('Y-m-d H:i:s') . ").\n"
284 . " *\n"
285 . " * Note: This file will be overwritten if settings are modified at:\n"
286 . " * @link " . CRM_Utils_System::url('civicrm/admin/ckeditor', NULL, TRUE, NULL, FALSE) . "\n"
287 . " */\n";
288 }
289
290 }