settings.lib.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Library of the settings.php file
  5. *
  6. * @author Julio Montoya <gugli100@gmail.com>
  7. * @author Guillaume Viguier <guillaume@viguierjust.com>
  8. *
  9. * @since Chamilo 1.8.7
  10. * @package chamilo.admin
  11. */
  12. /**
  13. * The function that retrieves all the possible settings for a certain config setting
  14. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  15. */
  16. function get_settings_options($var) {
  17. $table_settings_options = Database :: get_main_table(TABLE_MAIN_SETTINGS_OPTIONS);
  18. $sql = "SELECT * FROM $table_settings_options WHERE variable='$var'";
  19. $result = Database::query($sql);
  20. while ($row = Database::fetch_array($result)) {
  21. $temp_array = array ('value' => $row['value'], 'display_text' => $row['display_text']);
  22. $settings_options_array[] = $temp_array;
  23. }
  24. return $settings_options_array;
  25. }
  26. /**
  27. * This function allows easy activating and inactivating of plugins
  28. * @todo: a similar function needs to be written to activate or inactivate additional tools.
  29. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  30. */
  31. function handle_plugins() {
  32. global $SettingsStored;
  33. $userplugins = array();
  34. $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  35. if (isset($_POST['submit_plugins'])) {
  36. store_plugins();
  37. // Add event to the system log.
  38. $user_id = api_get_user_id();
  39. $category = $_GET['category'];
  40. event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
  41. Display :: display_confirmation_message(get_lang('SettingsStored'));
  42. }
  43. //echo get_lang('AvailablePlugins').'<br />';
  44. echo '<br />';
  45. /* We scan the plugin directory. Each folder is a potential plugin. */
  46. $pluginpath = api_get_path(SYS_PLUGIN_PATH);
  47. $handle = @opendir($pluginpath);
  48. while (false !== ($file = readdir($handle))) {
  49. if ($file != '.' && $file != '..' && is_dir(api_get_path(SYS_PLUGIN_PATH).$file)) {
  50. $possibleplugins[] = $file;
  51. }
  52. }
  53. @closedir($handle);
  54. /* For each of the possible plugin directories we check whether a file named "plugin.php" exists
  55. (it contains all the needed information about this plugin).
  56. This "plugin.php" file looks like:
  57. $plugin_info['title'] = 'The title of the plugin';
  58. $plugin_info['comment'] = 'Some comment about the plugin';
  59. $plugin_info['location'] = array('loginpage_menu', 'campushomepage_menu', 'banner'); // The possible locations where the plugins can be used.
  60. $plugin_info['version'] = '0.1 alpha'; // The version number of the plugin.
  61. $plugin_info['author'] = 'Patrick Cool'; // The author of the plugin.
  62. */
  63. echo '<form name="plugins" method="post" action="'.api_get_self().'?category='.$_GET['category'].'">';
  64. echo '<table class="data_table">';
  65. echo '<tr>';
  66. echo '<th>';
  67. echo get_lang('Plugin');
  68. echo '</th><th>';
  69. echo get_lang('LoginPageMainArea');
  70. echo '</th><th>';
  71. echo get_lang('LoginPageMenu');
  72. echo '</th><th>';
  73. echo get_lang('CampusHomepageMainArea');
  74. echo '</th><th>';
  75. echo get_lang('CampusHomepageMenu');
  76. echo '</th><th>';
  77. echo get_lang('MyCoursesMainArea');
  78. echo '</th><th>';
  79. echo get_lang('MyCoursesMenu');
  80. echo '</th><th>';
  81. echo get_lang('Header');
  82. echo '</th><th>';
  83. echo get_lang('Footer');
  84. echo '</th><th>';
  85. echo get_lang('CourseTool');
  86. echo '</th>';
  87. echo '</tr>';
  88. /* We retrieve all the active plugins. */
  89. //$sql = "SELECT * FROM $table_settings_current WHERE category='Plugins'";
  90. //$result = Database::query($sql);
  91. $result = api_get_settings('Plugins');
  92. //while ($row = Database::fetch_array($result))
  93. foreach ($result as $row) {
  94. $usedplugins[$row['variable']][] = $row['selected_value'];
  95. }
  96. /* We display all the possible plugins and the checkboxes */
  97. foreach ($possibleplugins as $testplugin) {
  98. $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$testplugin.'/plugin.php';
  99. if (file_exists($plugin_info_file)) {
  100. $plugin_info = array();
  101. include ($plugin_info_file);
  102. echo '<tr>';
  103. echo '<td>';
  104. foreach ($plugin_info as $key => $value) {
  105. if ($key != 'location') {
  106. if ($key == 'title') {
  107. $value = '<strong>'.$value.'</strong>';
  108. }
  109. echo get_lang(ucwords($key)).': '.$value.'<br />';
  110. }
  111. }
  112. if (file_exists(api_get_path(SYS_PLUGIN_PATH).$testplugin.'/readme.txt')) {
  113. echo "<a href='".api_get_path(WEB_PLUGIN_PATH).$testplugin."/readme.txt'>readme.txt</a>";
  114. }
  115. echo '</td>';
  116. // column: LoginPageMainArea
  117. if (empty($usedplugins)) {
  118. $usedplugins = array();
  119. }
  120. display_plugin_cell('loginpage_main', $plugin_info, $testplugin, $usedplugins);
  121. display_plugin_cell('loginpage_menu', $plugin_info, $testplugin, $usedplugins);
  122. display_plugin_cell('campushomepage_main', $plugin_info, $testplugin, $usedplugins);
  123. display_plugin_cell('campushomepage_menu', $plugin_info, $testplugin, $usedplugins);
  124. display_plugin_cell('mycourses_main', $plugin_info, $testplugin, $usedplugins);
  125. display_plugin_cell('mycourses_menu', $plugin_info, $testplugin, $usedplugins);
  126. display_plugin_cell('header', $plugin_info, $testplugin, $usedplugins);
  127. display_plugin_cell('footer', $plugin_info, $testplugin, $usedplugins);
  128. display_plugin_cell('course_tool_plugin', $plugin_info, $testplugin, $usedplugins);
  129. echo '</tr>';
  130. }
  131. }
  132. echo '</table>';
  133. echo '<br />';
  134. echo '<button class="save" type="submit" name="submit_plugins">'.get_lang('EnablePlugins').'</button></form>';
  135. echo '<br />';
  136. }
  137. function display_plugin_cell($location, $plugin_info, $current_plugin, $active_plugins) {
  138. echo '<td align="center">';
  139. if (in_array($location, $plugin_info['location'])) {
  140. if (isset($active_plugins[$location]) && is_array($active_plugins[$location])
  141. && in_array($current_plugin, $active_plugins[$location])) {
  142. $checked = 'checked';
  143. } else {
  144. $checked = '';
  145. }
  146. echo '<input type="checkbox" name="'.$current_plugin.'-'.$location.'" value="true" '.$checked.'/>';
  147. }
  148. echo "</td>";
  149. }
  150. /**
  151. * This function allows the platform admin to choose the default stylesheet
  152. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  153. * @author Julio Montoya <gugli100@gmail.com>, Chamilo
  154. */
  155. function handle_stylesheets() {
  156. global $_configuration;
  157. // Current style.
  158. $currentstyle = api_get_setting('stylesheets');
  159. $is_style_changeable = false;
  160. if ($_configuration['access_url'] != 1) {
  161. $style_info = api_get_settings('stylesheets', '', 1, 0);
  162. $url_info = api_get_access_url($_configuration['access_url']);
  163. if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
  164. $is_style_changeable = true;
  165. echo '<div class="actions" id="stylesheetuploadlink">';
  166. Display::display_icon('upload_stylesheets.png',get_lang('UploadNewStylesheet'),'','32');
  167. echo '<a href="" onclick="javascript: document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\'; return false; ">'.get_lang('UploadNewStylesheet').'</a>';
  168. echo '</div>';
  169. }
  170. } else {
  171. $is_style_changeable = true;
  172. echo '<div class="actions" id="stylesheetuploadlink">';
  173. Display::display_icon('upload_stylesheets.png',get_lang('UploadNewStylesheet'),'','32');
  174. echo '<a href="" onclick="javascript: document.getElementById(\'newstylesheetform\').style.display = \'block\'; document.getElementById(\'stylesheetuploadlink\').style.display = \'none\'; return false; ">'.get_lang('UploadNewStylesheet').'</a>';
  175. echo '</div>';
  176. }
  177. $form = new FormValidator('stylesheet_upload', 'post', 'settings.php?category=stylesheets&showuploadform=true');
  178. $form->addElement('text', 'name_stylesheet', get_lang('NameStylesheet'), array('size' => '40', 'maxlength' => '40'));
  179. $form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
  180. $form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
  181. $allowed_file_types = array('css', 'zip', 'jpeg', 'jpg', 'png', 'gif');
  182. $form->addRule('new_stylesheet', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types);
  183. $form->addRule('new_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
  184. $form->addElement('style_submit_button', 'stylesheet_upload', get_lang('Ok'), array('class'=>'save'));
  185. if ($form->validate() && is_writable(api_get_path(SYS_CODE_PATH).'css/')) {
  186. $values = $form->exportValues();
  187. $picture_element = & $form->getElement('new_stylesheet');
  188. $picture = $picture_element->getValue();
  189. upload_stylesheet($values, $picture);
  190. // Add event to the system log.
  191. $user_id = api_get_user_id();
  192. $category = $_GET['category'];
  193. event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
  194. Display::display_confirmation_message(get_lang('StylesheetAdded'));
  195. } else {
  196. if (!is_writable(api_get_path(SYS_CODE_PATH).'css/')) {
  197. Display::display_error_message(api_get_path(SYS_CODE_PATH).'css/'.get_lang('IsNotWritable'));
  198. } else {
  199. if ($_GET['showuploadform'] == 'true') {
  200. echo '<div id="newstylesheetform">';
  201. } else {
  202. echo '<div id="newstylesheetform" style="display: none;">';
  203. }
  204. // Uploading a new stylesheet.
  205. if ($_configuration['access_url'] == 1) {
  206. $form->display();
  207. } else {
  208. if ($is_style_changeable) {
  209. $form->display();
  210. }
  211. }
  212. echo '</div>';
  213. }
  214. }
  215. // Preview of the stylesheet.
  216. echo '<div><iframe src="style_preview.php" width="100%" height="300" name="preview"></iframe></div>';
  217. ?>
  218. <script type="text/javascript">
  219. function load_preview(selectobj){
  220. var style_dir = selectobj.options[selectobj.selectedIndex].value;
  221. parent.preview.location='style_preview.php?style=' + style_dir;
  222. }
  223. </script>
  224. <?php
  225. echo '<form name="stylesheets" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'">';
  226. echo '<br /><select name="style" onChange="load_preview(this)" >';
  227. $list_of_styles = array();
  228. $list_of_names = array();
  229. if ($handle = @opendir(api_get_path(SYS_PATH).'main/css/')) {
  230. $counter = 1;
  231. while (false !== ($style_dir = readdir($handle))) {
  232. if (substr($style_dir, 0, 1) == '.') { // Skip directories starting with a '.'
  233. continue;
  234. }
  235. $dirpath = api_get_path(SYS_PATH).'main/css/'.$style_dir;
  236. if (is_dir($dirpath)) {
  237. if ($style_dir != '.' && $style_dir != '..') {
  238. if ($currentstyle == $style_dir || ($style_dir == 'chamilo' && !$currentstyle)) {
  239. $selected = 'selected="true"';
  240. } else {
  241. $selected = '';
  242. }
  243. $show_name = ucwords(str_replace('_', ' ', $style_dir));
  244. if ($is_style_changeable) {
  245. $list_of_styles[$style_dir] = "<option value=\"".$style_dir."\" ".$selected." /> $show_name </option>";
  246. $list_of_names[$style_dir] = $show_name;
  247. //echo "<input type=\"radio\" name=\"style\" value=\"".$style_dir."\" ".$selected." onClick=\"parent.preview.location='style_preview.php?style=".$style_dir."';\"/>";
  248. //echo '<a href="style_preview.php?style='.$style_dir.'" target="preview">'.$show_name.'</a>';
  249. } else {
  250. echo '<a href="style_preview.php?style='.$style_dir.'" target="preview">'.$show_name.'</a>';
  251. }
  252. echo '<br />';
  253. $counter++;
  254. }
  255. }
  256. }
  257. @closedir($handle);
  258. }
  259. //Sort styles in alphabetical order
  260. asort($list_of_names);
  261. foreach($list_of_names as $style_dir=>$item) {
  262. echo $list_of_styles[$style_dir];
  263. }
  264. //echo '</select><br />';
  265. echo '</select>&nbsp;&nbsp;';
  266. if ($is_style_changeable){
  267. echo '<button class="save" type="submit" name="submit_stylesheets"> '.get_lang('SaveSettings').' </button></form>';
  268. }
  269. }
  270. /**
  271. * Creates the folder (if needed) and uploads the stylesheet in it
  272. *
  273. * @param array $values the values of the form
  274. * @param array $picture the values of the uploaded file
  275. *
  276. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  277. * @version May 2008
  278. * @since Dokeos 1.8.5
  279. */
  280. function upload_stylesheet($values, $picture) {
  281. // Valid name for the stylesheet folder.
  282. $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
  283. // Create the folder if needed.
  284. if (!is_dir(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/')) {
  285. mkdir(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/', api_get_permissions_for_new_directories());
  286. }
  287. $info = pathinfo($picture['name']);
  288. if ($info['extension'] == 'zip') {
  289. // Try to open the file and extract it in the theme.
  290. $zip = new ZipArchive();
  291. if ($zip->open($picture['tmp_name'])) {
  292. // Make sure all files inside the zip are images or css.
  293. $num_files = $zip->numFiles;
  294. $valid = true;
  295. $single_directory = true;
  296. $invalid_files = array();
  297. for ($i = 0; $i < $num_files; $i++) {
  298. $file = $zip->statIndex($i);
  299. if (substr($file['name'], -1) != '/') {
  300. $path_parts = pathinfo($file['name']);
  301. if (!in_array($path_parts['extension'], array('jpg', 'jpeg', 'png', 'gif', 'css'))) {
  302. $valid = false;
  303. $invalid_files[] = $file['name'];
  304. }
  305. }
  306. if (strpos($file['name'], '/') === false) {
  307. $single_directory = false;
  308. }
  309. }
  310. if (!$valid) {
  311. $error_string = '<ul>';
  312. foreach ($invalid_files as $invalid_file) {
  313. $error_string .= '<li>'.$invalid_file.'</li>';
  314. }
  315. $error_string .= '</ul>';
  316. Display::display_error_message(get_lang('ErrorStylesheetFilesExtensionsInsideZip').$error_string, false);
  317. } else {
  318. // If the zip does not contain a single directory, extract it.
  319. if (!$single_directory) {
  320. // Extract zip file.
  321. $zip->extractTo(api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/');
  322. } else {
  323. $extraction_path = api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/';
  324. for ($i = 0; $i < $num_files; $i++) {
  325. $entry = $zip->getNameIndex($i);
  326. if (substr($entry, -1) == '/') continue;
  327. $pos_slash = strpos($entry, '/');
  328. $entry_without_first_dir = substr($entry, $pos_slash + 1);
  329. // If there is still a slash, we need to make sure the directories are created.
  330. if (strpos($entry_without_first_dir, '/') !== false) {
  331. if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
  332. // Create it.
  333. @mkdir($extraction_path.dirname($entry_without_first_dir), $mode = 0777, true);
  334. }
  335. }
  336. $fp = $zip->getStream($entry);
  337. $ofp = fopen( $extraction_path. dirname($entry_without_first_dir).'/'.basename($entry), 'w');
  338. while (!feof($fp)) {
  339. fwrite($ofp, fread($fp, 8192));
  340. }
  341. fclose($fp);
  342. fclose($ofp);
  343. }
  344. }
  345. }
  346. $zip->close();
  347. } else {
  348. Display::display_error_message(get_lang('ErrorReadingZip').$info['extension'], false);
  349. }
  350. } else {
  351. // Simply move the file.
  352. move_uploaded_file($picture['tmp_name'], api_get_path(SYS_CODE_PATH).'css/'.$style_name.'/'.$picture['name']);
  353. }
  354. }
  355. /**
  356. * This function allows easy activating and inactivating of plugins
  357. * @todo: A similar function needs to be written to activate or inactivate additional tools.
  358. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  359. */
  360. function store_plugins() {
  361. $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  362. global $_configuration;
  363. // Get a list of all current 'Plugins' settings
  364. $installed_plugins = api_get_settings('Plugins','list',$_configuration['access_url']);
  365. $shortlist_installed = array();
  366. foreach ($installed_plugins as $plugin) {
  367. $shortlist_installed[] = $plugin['subkey'];
  368. }
  369. $shortlist_installed = array_flip(array_flip($shortlist_installed));
  370. // Step 1 : We remove all the plugins.
  371. //$sql = "DELETE FROM $table_settings_current WHERE category='Plugins'";
  372. //Database::query($sql);
  373. $r = api_delete_category_settings('Plugins', $_configuration['access_url']);
  374. $shortlist_required = array();
  375. // Step 2: Looping through all the post values we only store these which are really a valid plugin location.
  376. foreach ($_POST as $form_name => $formvalue) {
  377. $form_name_elements = explode('-', $form_name);
  378. if (is_valid_plugin_location($form_name_elements[1])) {
  379. $shortlist_required[] = $form_name_elements[0];
  380. //$sql = "INSERT into $table_settings_current (variable,category,selected_value) VALUES ('".$form_name_elements['1']."','Plugins','".$form_name_elements['0']."')";
  381. //Database::query($sql);
  382. api_add_setting($form_name_elements['0'], $form_name_elements['1'], $form_name_elements['0'], null, 'Plugins', $form_name_elements['0'], null, null, null, $_configuration['access_url'], 1);
  383. // check if there is an install procedure
  384. $pluginpath = api_get_path(SYS_PLUGIN_PATH).$form_name_elements[0].'/install.php';
  385. if (is_file($pluginpath) && is_readable($pluginpath)) {
  386. //execute the install procedure
  387. include $pluginpath;
  388. }
  389. }
  390. }
  391. foreach ($shortlist_installed as $plugin) {
  392. // if one plugin was really deleted, execute the uninstall script
  393. if (!in_array($plugin,$shortlist_required)) {
  394. // check if there is an install procedure
  395. $pluginpath = api_get_path(SYS_PLUGIN_PATH).$plugin.'/uninstall.php';
  396. if (is_file($pluginpath) && is_readable($pluginpath)) {
  397. //execute the install procedure
  398. include $pluginpath;
  399. }
  400. }
  401. }
  402. }
  403. /**
  404. * Check if the post information is really a valid plugin location.
  405. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  406. */
  407. function is_valid_plugin_location($location) {
  408. static $valid_locations = array('loginpage_main', 'loginpage_menu', 'campushomepage_main', 'campushomepage_menu', 'mycourses_main', 'mycourses_menu', 'header', 'footer', 'course_tool_plugin');
  409. return in_array($location, $valid_locations);
  410. }
  411. /**
  412. * This function allows the platform admin to choose which should be the default stylesheet
  413. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  414. */
  415. function store_stylesheets() {
  416. global $_configuration;
  417. // Database table definitions.
  418. $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  419. // Insert the stylesheet.
  420. $style = Database::escape_string($_POST['style']);
  421. if (is_style($style)) {
  422. /*
  423. $sql = 'UPDATE '.$table_settings_current.' SET
  424. selected_value = "'.$style.'"
  425. WHERE variable = "stylesheets"
  426. AND category = "stylesheets"';
  427. Database::query($sql);
  428. */
  429. api_set_setting('stylesheets', $style, null, 'stylesheets', $_configuration['access_url']);
  430. }
  431. return true;
  432. }
  433. /**
  434. * This function checks if the given style is a recognize style that exists in the css directory as
  435. * a standalone directory.
  436. * @param string Style
  437. * @return bool True if this style is recognized, false otherwise
  438. */
  439. function is_style($style) {
  440. $dir = api_get_path(SYS_PATH).'main/css/';
  441. $dirs = scandir($dir);
  442. $style = str_replace(array('/', '\\'), array('', ''), $style); // Avoid slashes or backslashes.
  443. if (in_array($style, $dirs) && is_dir($dir.$style)) {
  444. return true;
  445. }
  446. return false;
  447. }
  448. /**
  449. * Search options
  450. * TODO: support for multiple site. aka $_configuration['access_url'] == 1
  451. * @author Marco Villegas <marvil07@gmail.com>
  452. */
  453. function handle_search() {
  454. global $SettingsStored, $_configuration;
  455. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  456. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  457. $search_enabled = api_get_setting('search_enabled');
  458. $form = new FormValidator('search-options', 'post', api_get_self().'?category=Search');
  459. $renderer = & $form->defaultRenderer();
  460. //$renderer->setHeaderTemplate('<div class="sectiontitle">{header}</div>'."\n");
  461. //$renderer->setElementTemplate('<div class="sectioncomment">{label}</div>'."\n".'<div class="sectionvalue">{element}</div>'."\n");
  462. $renderer->setElementTemplate('<div class="row"><div class="label">{label}</div><div class="formw">{element}<!-- BEGIN label_2 --><span class="help-block">{label_2}</span><!-- END label_2 --></div></div>');
  463. $values = get_settings_options('search_enabled');
  464. $form->addElement('header', null, get_lang('SearchEnabledTitle'));
  465. $group = array ();
  466. if (is_array($values)) {
  467. foreach ($values as $key => $value) {
  468. $element = & $form->createElement('radio', 'search_enabled', '', get_lang($value['display_text']), $value['value']);
  469. /* $hide_element is not defined
  470. if ($hide_element) {
  471. $element->freeze();
  472. }
  473. */
  474. $group[] = $element;
  475. }
  476. }
  477. //SearchEnabledComment
  478. $form->addGroup($group, 'search_enabled', array(get_lang('SearchEnabledTitle'), get_lang('SearchEnabledComment')), '<br />', false);
  479. $search_enabled = api_get_setting('search_enabled');
  480. if ($form->validate()) {
  481. $formvalues = $form->exportValues();
  482. $r = api_set_settings_category('Search', 'false', $_configuration['access_url']);
  483. // Save the settings.
  484. foreach ($formvalues as $key => $value) {
  485. $result = api_set_setting($key, $value, null, null);
  486. }
  487. $search_enabled = $formvalues['search_enabled'];
  488. Display::display_confirmation_message($SettingsStored);
  489. }
  490. $specific_fields = get_specific_field_list();
  491. if ($search_enabled == 'true') {
  492. // Search_show_unlinked_results.
  493. //$form->addElement('header', null, get_lang('SearchShowUnlinkedResultsTitle'));
  494. //$form->addElement('label', null, get_lang('SearchShowUnlinkedResultsComment'));
  495. $values = get_settings_options('search_show_unlinked_results');
  496. $group = array ();
  497. foreach ($values as $key => $value) {
  498. $element = & $form->createElement('radio', 'search_show_unlinked_results', '', get_lang($value['display_text']), $value['value']);
  499. $group[] = $element;
  500. }
  501. $form->addGroup($group, 'search_show_unlinked_results', array(get_lang('SearchShowUnlinkedResultsTitle'),get_lang('SearchShowUnlinkedResultsComment')), '<div></div>', false);
  502. $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
  503. // Search_prefilter_prefix.
  504. //$form->addElement('header', null, get_lang('SearchPrefilterPrefix'));
  505. //$form->addElement('label', null, get_lang('SearchPrefilterPrefixComment'));
  506. $sf_values = array();
  507. foreach ($specific_fields as $sf) {
  508. $sf_values[$sf['code']] = $sf['name'];
  509. }
  510. $group = array();
  511. $url = Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'), array('class'=>'sectioncomment'));
  512. if (empty($sf_values)) {
  513. $form->addElement('html', get_lang('SearchPrefilterPrefix').$url);
  514. } else {
  515. $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url), $sf_values, '');
  516. $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
  517. }
  518. }
  519. $default_values['search_enabled'] = $search_enabled;
  520. //$form->addRule('search_show_unlinked_results', get_lang('ThisFieldIsRequired'), 'required');
  521. $form->addElement('style_submit_button', 'submit', get_lang('Save'),'class="save"');
  522. $form->setDefaults($default_values);
  523. echo '<div id="search-options-form">';
  524. $form->display();
  525. echo '</div>';
  526. if ($search_enabled == 'true') {
  527. require_once api_get_path(LIBRARY_PATH).'sortabletable.class.php';
  528. $xapian_path = api_get_path(SYS_PATH).'searchdb';
  529. /*
  530. @todo Test the Xapian connection
  531. if (extension_loaded('xapian')) {
  532. require_once 'xapian.php';
  533. try {
  534. $db = new XapianDatabase($xapian_path.'/');
  535. } catch (Exception $e) {
  536. var_dump($e->getMessage());
  537. }
  538. require_once api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php';
  539. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  540. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  541. $indexable = new IndexableChunk();
  542. $indexable->addValue("content", 'Test');
  543. $di = new DokeosIndexer();
  544. $di->connectDb(NULL, NULL, 'english');
  545. $di->addChunk($indexable);
  546. $did = $di->index();
  547. }
  548. */
  549. $xapian_loaded = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  550. $dir_exists = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  551. $dir_is_writable = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  552. $specific_fields_exists = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  553. //Testing specific fields
  554. if (empty($specific_fields)) {
  555. $specific_fields_exists = Display::return_icon('bullet_red.gif', get_lang('AddSpecificSearchField'));
  556. }
  557. //Testing xapian extension
  558. if (!extension_loaded('xapian')) {
  559. $xapian_loaded = Display::return_icon('bullet_red.gif', get_lang('Error'));
  560. }
  561. //Testing xapian searchdb path
  562. if (!is_dir($xapian_path)) {
  563. $dir_exists = Display::return_icon('bullet_red.gif', get_lang('Error'));
  564. }
  565. //Testing xapian searchdb path is writable
  566. if (!is_writable($xapian_path)) {
  567. $dir_is_writable = Display::return_icon('bullet_red.gif', get_lang('Error'));
  568. }
  569. $data[] = array(get_lang('XapianModuleInstalled'),$xapian_loaded);
  570. $data[] = array(get_lang('DirectoryExists').' - '.$xapian_path,$dir_exists);
  571. $data[] = array(get_lang('IsWritable').' - '.$xapian_path,$dir_is_writable);
  572. $data[] = array(get_lang('SpecificSearchFieldsAvailable') ,$specific_fields_exists);
  573. echo Display::tag('h3', get_lang('Settings'));
  574. $table = new SortableTableFromArray($data);
  575. $table->set_header(0, get_lang('Setting'), false);
  576. $table->set_header(1, get_lang('Status'), false);
  577. echo $table->display();
  578. //@todo windows support
  579. if (api_is_windows_os() == false) {
  580. $list_of_programs = array('pdftotext','ps2pdf', 'catdoc','html2text','unrtf', 'catppt', 'xls2csv');
  581. foreach($list_of_programs as $program) {
  582. $output = $ret_val = null;
  583. exec("which $program", $output, $ret_val);
  584. $icon = Display::return_icon('bullet_red.gif', get_lang('NotInstalled'));
  585. if (!empty($output[0])) {
  586. $icon = Display::return_icon('bullet_green.gif', get_lang('Installed'));
  587. }
  588. $data2[]= array($program, $output[0], $icon);
  589. }
  590. echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles'));
  591. $table = new SortableTableFromArray($data2);
  592. $table->set_header(0, get_lang('Program'), false);
  593. $table->set_header(1, get_lang('Path'), false);
  594. $table->set_header(2, get_lang('Status'), false);
  595. echo $table->display();
  596. } else {
  597. Display::display_warning_message(get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool'));
  598. }
  599. }
  600. }
  601. /**
  602. * Wrapper for the templates
  603. *
  604. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  605. * @version August 2008
  606. * @since Dokeos 1.8.6
  607. */
  608. function handle_templates() {
  609. if ($_GET['action'] != 'add') {
  610. echo '<div class="actions" style="margin-left: 1px;">';
  611. echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'','32').'</a>';
  612. echo '</div>';
  613. }
  614. if ($_GET['action'] == 'add' || ($_GET['action'] == 'edit' && is_numeric($_GET['id']))) {
  615. add_edit_template();
  616. // Add event to the system log.
  617. $user_id = api_get_user_id();
  618. $category = $_GET['category'];
  619. event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
  620. } else {
  621. if ($_GET['action'] == 'delete' && is_numeric($_GET['id'])) {
  622. delete_template($_GET['id']);
  623. // Add event to the system log
  624. $user_id = api_get_user_id();
  625. $category = $_GET['category'];
  626. event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
  627. }
  628. display_templates();
  629. }
  630. }
  631. /**
  632. * Display a sortable table with all the templates that the platform administrator has defined.
  633. *
  634. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  635. * @version August 2008
  636. * @since Dokeos 1.8.6
  637. */
  638. function display_templates() {
  639. $table = new SortableTable('templates', 'get_number_of_templates', 'get_template_data', 1);
  640. $table->set_additional_parameters(array('category' => Security::remove_XSS($_GET['category'])));
  641. $table->set_header(0, get_lang('Image'), true, array('style' => 'width: 101px;'));
  642. $table->set_header(1, get_lang('Title'));
  643. $table->set_header(2, get_lang('Actions'), false, array('style' => 'width:50px;'));
  644. $table->set_column_filter(2, 'actions_filter');
  645. $table->set_column_filter(0, 'image_filter');
  646. $table->display();
  647. }
  648. /**
  649. * Gets the number of templates that are defined by the platform admin.
  650. *
  651. * @return integer
  652. *
  653. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  654. * @version August 2008
  655. * @since Dokeos 1.8.6
  656. */
  657. function get_number_of_templates() {
  658. // Database table definition.
  659. $table_system_template = Database :: get_main_table('system_template');
  660. // The sql statement.
  661. $sql = "SELECT COUNT(id) AS total FROM $table_system_template";
  662. $result = Database::query($sql);
  663. $row = Database::fetch_array($result);
  664. // Returning the number of templates.
  665. return $row['total'];
  666. }
  667. /**
  668. * Gets all the template data for the sortable table.
  669. *
  670. * @param integer $from the start of the limit statement
  671. * @param integer $number_of_items the number of elements that have to be retrieved from the database
  672. * @param integer $column the column that is
  673. * @param string $direction the sorting direction (ASC or DESC�
  674. * @return array
  675. *
  676. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  677. * @version August 2008
  678. * @since Dokeos 1.8.6
  679. */
  680. function get_template_data($from, $number_of_items, $column, $direction) {
  681. // Database table definition.
  682. $table_system_template = Database :: get_main_table('system_template');
  683. // The sql statement.
  684. $sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
  685. $sql .= " ORDER BY col$column $direction ";
  686. $sql .= " LIMIT $from,$number_of_items";
  687. $result = Database::query($sql);
  688. while ($row = Database::fetch_array($result)) {
  689. $row['1'] = get_lang($row['1']);
  690. $return[] = $row;
  691. }
  692. // Returning all the information for the sortable table.
  693. return $return;
  694. }
  695. /**
  696. * display the edit and delete icons in the sortable table
  697. *
  698. * @param integer $id the id of the template
  699. * @return html code for the link to edit and delete the template
  700. *
  701. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  702. * @version August 2008
  703. * @since Dokeos 1.8.6
  704. */
  705. function actions_filter($id) {
  706. $return = '<a href="settings.php?category=Templates&amp;action=edit&amp;id='.Security::remove_XSS($id).'">'.Display::return_icon('edit.png', get_lang('Edit'),'',22).'</a>';
  707. $return .= '<a href="settings.php?category=Templates&amp;action=delete&amp;id='.Security::remove_XSS($id).'" onClick="javascript:if(!confirm('."'".get_lang('ConfirmYourChoice')."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'),'',22).'</a>';
  708. return $return;
  709. }
  710. /**
  711. * Display the image of the template in the sortable table
  712. *
  713. * @param string $image the image
  714. * @return html code for the image
  715. *
  716. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  717. * @version August 2008
  718. * @since Dokeos 1.8.6
  719. */
  720. function image_filter($image) {
  721. if (!empty($image)) {
  722. return '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/'.$image.'" alt="'.get_lang('TemplatePreview').'"/>';
  723. } else {
  724. return '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>';
  725. }
  726. }
  727. /**
  728. * Add (or edit) a template. This function displays the form and also takes care of uploading the image and storing the information in the database
  729. *
  730. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  731. * @version August 2008
  732. * @since Dokeos 1.8.6
  733. */
  734. function add_edit_template() {
  735. // Initialize the object.
  736. $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).'&id='.Security::remove_XSS($_GET['id']));
  737. // Settting the form elements: the header.
  738. if ($_GET['action'] == 'add') {
  739. $title = get_lang('AddTemplate');
  740. } else {
  741. $title = get_lang('EditTemplate');
  742. }
  743. $form->addElement('header', '', $title);
  744. // Settting the form elements: the title of the template.
  745. $form->add_textfield('title', get_lang('Title'), false);
  746. // Settting the form elements: the content of the template (wysiwyg editor).
  747. $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
  748. // Settting the form elements: the form to upload an image to be used with the template.
  749. $form->addElement('file','template_image',get_lang('Image'),'');
  750. // Settting the form elements: a little bit information about the template image.
  751. $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
  752. // Getting all the information of the template when editing a template.
  753. if ($_GET['action'] == 'edit') {
  754. // Database table definition.
  755. $table_system_template = Database :: get_main_table('system_template');
  756. $sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($_GET['id'])."'";
  757. $result = Database::query($sql);
  758. $row = Database::fetch_array($result);
  759. $defaults['template_id'] = intval($_GET['id']);
  760. $defaults['template_text'] = $row['content'];
  761. // Forcing get_lang().
  762. $defaults['title'] = get_lang($row['title']);
  763. // Adding an extra field: a hidden field with the id of the template we are editing.
  764. $form->addElement('hidden', 'template_id');
  765. // Adding an extra field: a preview of the image that is currently used.
  766. if (!empty($row['image'])) {
  767. $form->addElement('static', 'template_image_preview', '', '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/'.$row['image'].'" alt="'.get_lang('TemplatePreview').'"/>');
  768. } else {
  769. $form->addElement('static', 'template_image_preview', '', '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>');
  770. }
  771. // Setting the information of the template that we are editing.
  772. $form->setDefaults($defaults);
  773. }
  774. // Settting the form elements: the submit button.
  775. $form->addElement('style_submit_button' , 'submit', get_lang('Ok') ,'class="save"');
  776. // Setting the rules: the required fields.
  777. $form->addRule('title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
  778. $form->addRule('template_text', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
  779. // if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
  780. if ($form->validate()) {
  781. $check = Security::check_token('post');
  782. if ($check) {
  783. // Exporting the values.
  784. $values = $form->exportValues();
  785. // Upload the file.
  786. if (!empty($_FILES['template_image']['name'])) {
  787. require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
  788. $upload_ok = process_uploaded_file($_FILES['template_image']);
  789. if ($upload_ok) {
  790. // Try to add an extension to the file if it hasn't one.
  791. $new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
  792. // The upload directory.
  793. $upload_dir = api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/';
  794. // Create the directory if it does not exist.
  795. if (!is_dir($upload_dir)) {
  796. mkdir($upload_dir, api_get_permissions_for_new_directories());
  797. }
  798. // Resize the preview image to max default and upload.
  799. $temp = new Image($_FILES['template_image']['tmp_name']);
  800. $picture_info = $temp->get_image_info();
  801. $max_width_for_picture = 100;
  802. if ($picture_info['width'] > $max_width_for_picture) {
  803. $thumbwidth = $max_width_for_picture;
  804. if (empty($thumbwidth) || $thumbwidth == 0) {
  805. $thumbwidth = $max_width_for_picture;
  806. }
  807. $new_height = round(($thumbwidth / $picture_info['width']) * $picture_info['height']);
  808. $temp->resize($thumbwidth, $new_height, 0);
  809. }
  810. $temp->send_image($upload_dir.$new_file_name);
  811. }
  812. }
  813. // Store the information in the database (as insert or as update).
  814. $table_system_template = Database :: get_main_table('system_template');
  815. if ($_GET['action'] == 'add') {
  816. $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
  817. $sql = "INSERT INTO $table_system_template (title, content, image) VALUES ('".Database::escape_string($values['title'])."','".$content_template."','".Database::escape_string($new_file_name)."')";
  818. $result = Database::query($sql);
  819. // Display a feedback message.
  820. Display::display_confirmation_message(get_lang('TemplateAdded'));
  821. echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'','32').'</a>';
  822. } else {
  823. $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
  824. $sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."', content = '".$content_template."'";
  825. if (!empty($new_file_name)) {
  826. $sql .= ", image = '".Database::escape_string($new_file_name)."'";
  827. }
  828. $sql .= " WHERE id='".Database::escape_string($_GET['id'])."'";
  829. $result = Database::query($sql);
  830. // Display a feedback message.
  831. Display::display_confirmation_message(get_lang('TemplateEdited'));
  832. }
  833. }
  834. Security::clear_token();
  835. display_templates();
  836. } else {
  837. $token = Security::get_token();
  838. $form->addElement('hidden','sec_token');
  839. $form->setConstants(array('sec_token' => $token));
  840. // Display the form.
  841. $form->display();
  842. }
  843. }
  844. /**
  845. * Delete a template
  846. *
  847. * @param integer $id the id of the template that has to be deleted
  848. *
  849. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  850. * @version August 2008
  851. * @since Dokeos 1.8.6
  852. */
  853. function delete_template($id) {
  854. // First we remove the image.
  855. $table_system_template = Database :: get_main_table('system_template');
  856. $sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
  857. $result = Database::query($sql);
  858. $row = Database::fetch_array($result);
  859. if (!empty($row['image'])) {
  860. @unlink(api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
  861. }
  862. // Now we remove it from the database.
  863. $sql = "DELETE FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
  864. $result = Database::query($sql);
  865. // Display a feedback message.
  866. Display::display_confirmation_message(get_lang('TemplateDeleted'));
  867. }
  868. /**
  869. * Returns the list of timezone identifiers used to populate the select
  870. *
  871. * @return array List of timezone identifiers
  872. *
  873. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  874. * @since Chamilo 1.8.7
  875. */
  876. function select_timezone_value() {
  877. return api_get_timezones();
  878. }
  879. /**
  880. * Returns an array containing the list of options used to populate the gradebook_number_decimals variable
  881. *
  882. * @return array List of gradebook_number_decimals options
  883. *
  884. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  885. */
  886. function select_gradebook_number_decimals() {
  887. return array('0', '1', '2');
  888. }
  889. /**
  890. * Updates the gradebook score custom values using the scoredisplay class of the
  891. * gradebook module
  892. *
  893. * @param array List of gradebook score custom values
  894. *
  895. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  896. */
  897. function update_gradebook_score_display_custom_values($values) {
  898. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
  899. $scoredisplay = ScoreDisplay::instance();
  900. $scores = $values['gradebook_score_display_custom_values_endscore'];
  901. $displays = $values['gradebook_score_display_custom_values_displaytext'];
  902. $nr_displays = count($displays);
  903. $final = array();
  904. for ($i = 1; $i < $nr_displays; $i++) {
  905. if (!empty($scores[$i]) && !empty($displays[$i])) {
  906. $final[$i]['score'] = $scores[$i];
  907. $final[$i]['display'] = $displays[$i];
  908. }
  909. }
  910. $scoredisplay->update_custom_score_display_settings($final);
  911. }