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