settings.lib.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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. $values = get_settings_options('search_enabled');
  463. $form->addElement('header', null, get_lang('SearchEnabledTitle'));
  464. $group = array ();
  465. if (is_array($values)) {
  466. foreach ($values as $key => $value) {
  467. $element = & $form->createElement('radio', 'search_enabled', '', get_lang($value['display_text']), $value['value']);
  468. /* $hide_element is not defined
  469. if ($hide_element) {
  470. $element->freeze();
  471. }
  472. */
  473. $group[] = $element;
  474. }
  475. }
  476. $form->addGroup($group, 'search_enabled', get_lang('SearchEnabledComment'), '<br />', false);
  477. $search_enabled = api_get_setting('search_enabled');
  478. if ($form->validate()) {
  479. $formvalues = $form->exportValues();
  480. $r = api_set_settings_category('Search', 'false', $_configuration['access_url']);
  481. // Save the settings.
  482. foreach ($formvalues as $key => $value) {
  483. $result = api_set_setting($key, $value, null, null);
  484. }
  485. $search_enabled = $formvalues['search_enabled'];
  486. Display::display_confirmation_message($SettingsStored);
  487. }
  488. $specific_fields = get_specific_field_list();
  489. if ($search_enabled == 'true') {
  490. // Search_show_unlinked_results.
  491. $form->addElement('header', null, get_lang('SearchShowUnlinkedResultsTitle'));
  492. //$form->addElement('label', null, get_lang('SearchShowUnlinkedResultsComment'));
  493. $values = get_settings_options('search_show_unlinked_results');
  494. $group = array ();
  495. foreach ($values as $key => $value) {
  496. $element = & $form->createElement('radio', 'search_show_unlinked_results', '', get_lang($value['display_text']), $value['value']);
  497. $group[] = $element;
  498. }
  499. $form->addGroup($group, 'search_show_unlinked_results', get_lang('SearchShowUnlinkedResultsComment'), '<br />', false);
  500. $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
  501. // Search_prefilter_prefix.
  502. $form->addElement('header', null, get_lang('SearchPrefilterPrefix'));
  503. //$form->addElement('label', null, get_lang('SearchPrefilterPrefixComment'));
  504. $sf_values = array();
  505. foreach ($specific_fields as $sf) {
  506. $sf_values[$sf['code']] = $sf['name'];
  507. }
  508. $group = array();
  509. $url = Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'), array('class'=>'sectioncomment'));
  510. if (empty($sf_values)) {
  511. $form->addElement('html', get_lang('SearchPrefilterPrefix'));
  512. } else {
  513. $form->addElement('select', 'search_prefilter_prefix', get_lang('SearchPrefilterPrefix'), $sf_values, '');
  514. $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
  515. }
  516. $form->addElement('html', $url);
  517. }
  518. $default_values['search_enabled'] = $search_enabled;
  519. //$form->addRule('search_show_unlinked_results', get_lang('ThisFieldIsRequired'), 'required');
  520. $form->addElement('style_submit_button', 'submit', get_lang('Save'),'class="save"');
  521. $form->setDefaults($default_values);
  522. echo '<div id="search-options-form">';
  523. $form->display();
  524. echo '</div>';
  525. if ($search_enabled == 'true') {
  526. require_once api_get_path(LIBRARY_PATH).'sortabletable.class.php';
  527. $xapian_path = api_get_path(SYS_PATH).'searchdb';
  528. /*
  529. @todo Test the Xapian connection
  530. if (extension_loaded('xapian')) {
  531. require_once 'xapian.php';
  532. try {
  533. $db = new XapianDatabase($xapian_path.'/');
  534. } catch (Exception $e) {
  535. var_dump($e->getMessage());
  536. }
  537. require_once api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php';
  538. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  539. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  540. $indexable = new IndexableChunk();
  541. $indexable->addValue("content", 'Test');
  542. $di = new DokeosIndexer();
  543. $di->connectDb(NULL, NULL, 'english');
  544. $di->addChunk($indexable);
  545. $did = $di->index();
  546. }
  547. */
  548. $xapian_loaded = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  549. $dir_exists = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  550. $dir_is_writable = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  551. $specific_fields_exists = Display::return_icon('bullet_green.gif', get_lang('Ok'));
  552. //Testing specific fields
  553. if (empty($specific_fields)) {
  554. $specific_fields_exists = Display::return_icon('bullet_red.gif', get_lang('AddSpecificSearchField'));
  555. }
  556. //Testing xapian extension
  557. if (!extension_loaded('xapian')) {
  558. $xapian_loaded = Display::return_icon('bullet_red.gif', get_lang('Error'));
  559. }
  560. //Testing xapian searchdb path
  561. if (!is_dir($xapian_path)) {
  562. $dir_exists = Display::return_icon('bullet_red.gif', get_lang('Error'));
  563. }
  564. //Testing xapian searchdb path is writable
  565. if (!is_writable($xapian_path)) {
  566. $dir_is_writable = Display::return_icon('bullet_red.gif', get_lang('Error'));
  567. }
  568. $data[] = array(get_lang('XapianModuleInstalled'),$xapian_loaded);
  569. $data[] = array(get_lang('DirectoryExists').' - '.$xapian_path,$dir_exists);
  570. $data[] = array(get_lang('IsWritable').' - '.$xapian_path,$dir_is_writable);
  571. $data[] = array(get_lang('SpecificSearchFieldsAvailable') ,$specific_fields_exists);
  572. echo Display::tag('h3', get_lang('Settings'));
  573. $table = new SortableTableFromArray($data);
  574. $table->set_header(0, get_lang('Setting'), false);
  575. $table->set_header(1, get_lang('Status'), false);
  576. echo $table->display();
  577. //@todo windows support
  578. if (api_is_windows_os() == false) {
  579. $list_of_programs = array('pdftotext','ps2pdf', 'catdoc','html2text','unrtf', 'catppt', 'xls2csv');
  580. foreach($list_of_programs as $program) {
  581. $output = $ret_val = null;
  582. exec("which $program", $output, $ret_val);
  583. $icon = Display::return_icon('bullet_red.gif', get_lang('NotInstalled'));
  584. if (!empty($output[0])) {
  585. $icon = Display::return_icon('bullet_green.gif', get_lang('Installed'));
  586. }
  587. $data2[]= array($program, $output[0], $icon);
  588. }
  589. echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles'));
  590. $table = new SortableTableFromArray($data2);
  591. $table->set_header(0, get_lang('Program'), false);
  592. $table->set_header(1, get_lang('Path'), false);
  593. $table->set_header(2, get_lang('Status'), false);
  594. echo $table->display();
  595. } else {
  596. Display::display_warning_message(get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool'));
  597. }
  598. }
  599. }
  600. /**
  601. * Wrapper for the templates
  602. *
  603. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  604. * @version August 2008
  605. * @since Dokeos 1.8.6
  606. */
  607. function handle_templates() {
  608. if ($_GET['action'] != 'add') {
  609. echo '<div class="actions" style="margin-left: 1px;">';
  610. echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'','32').'</a>';
  611. echo '</div>';
  612. }
  613. if ($_GET['action'] == 'add' || ($_GET['action'] == 'edit' && is_numeric($_GET['id']))) {
  614. add_edit_template();
  615. // Add event to the system log.
  616. $user_id = api_get_user_id();
  617. $category = $_GET['category'];
  618. event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
  619. } else {
  620. if ($_GET['action'] == 'delete' && is_numeric($_GET['id'])) {
  621. delete_template($_GET['id']);
  622. // Add event to the system log
  623. $user_id = api_get_user_id();
  624. $category = $_GET['category'];
  625. event_system(LOG_CONFIGURATION_SETTINGS_CHANGE, LOG_CONFIGURATION_SETTINGS_CATEGORY, $category, api_get_utc_datetime(), $user_id);
  626. }
  627. display_templates();
  628. }
  629. }
  630. /**
  631. * Display a sortable table with all the templates that the platform administrator has defined.
  632. *
  633. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  634. * @version August 2008
  635. * @since Dokeos 1.8.6
  636. */
  637. function display_templates() {
  638. $table = new SortableTable('templates', 'get_number_of_templates', 'get_template_data', 1);
  639. $table->set_additional_parameters(array('category' => Security::remove_XSS($_GET['category'])));
  640. $table->set_header(0, get_lang('Image'), true, array('style' => 'width: 101px;'));
  641. $table->set_header(1, get_lang('Title'));
  642. $table->set_header(2, get_lang('Actions'), false, array('style' => 'width:50px;'));
  643. $table->set_column_filter(2, 'actions_filter');
  644. $table->set_column_filter(0, 'image_filter');
  645. $table->display();
  646. }
  647. /**
  648. * Gets the number of templates that are defined by the platform admin.
  649. *
  650. * @return integer
  651. *
  652. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  653. * @version August 2008
  654. * @since Dokeos 1.8.6
  655. */
  656. function get_number_of_templates() {
  657. // Database table definition.
  658. $table_system_template = Database :: get_main_table('system_template');
  659. // The sql statement.
  660. $sql = "SELECT COUNT(id) AS total FROM $table_system_template";
  661. $result = Database::query($sql);
  662. $row = Database::fetch_array($result);
  663. // Returning the number of templates.
  664. return $row['total'];
  665. }
  666. /**
  667. * Gets all the template data for the sortable table.
  668. *
  669. * @param integer $from the start of the limit statement
  670. * @param integer $number_of_items the number of elements that have to be retrieved from the database
  671. * @param integer $column the column that is
  672. * @param string $direction the sorting direction (ASC or DESC�
  673. * @return array
  674. *
  675. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  676. * @version August 2008
  677. * @since Dokeos 1.8.6
  678. */
  679. function get_template_data($from, $number_of_items, $column, $direction) {
  680. // Database table definition.
  681. $table_system_template = Database :: get_main_table('system_template');
  682. // The sql statement.
  683. $sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
  684. $sql .= " ORDER BY col$column $direction ";
  685. $sql .= " LIMIT $from,$number_of_items";
  686. $result = Database::query($sql);
  687. while ($row = Database::fetch_array($result)) {
  688. $row['1'] = get_lang($row['1']);
  689. $return[] = $row;
  690. }
  691. // Returning all the information for the sortable table.
  692. return $return;
  693. }
  694. /**
  695. * display the edit and delete icons in the sortable table
  696. *
  697. * @param integer $id the id of the template
  698. * @return html code for the link to edit and delete the template
  699. *
  700. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  701. * @version August 2008
  702. * @since Dokeos 1.8.6
  703. */
  704. function actions_filter($id) {
  705. $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>';
  706. $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>';
  707. return $return;
  708. }
  709. /**
  710. * Display the image of the template in the sortable table
  711. *
  712. * @param string $image the image
  713. * @return html code for the image
  714. *
  715. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  716. * @version August 2008
  717. * @since Dokeos 1.8.6
  718. */
  719. function image_filter($image) {
  720. if (!empty($image)) {
  721. return '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/'.$image.'" alt="'.get_lang('TemplatePreview').'"/>';
  722. } else {
  723. return '<img src="'.api_get_path(WEB_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>';
  724. }
  725. }
  726. /**
  727. * 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
  728. *
  729. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  730. * @version August 2008
  731. * @since Dokeos 1.8.6
  732. */
  733. function add_edit_template() {
  734. // Initialize the object.
  735. $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).'&id='.Security::remove_XSS($_GET['id']));
  736. // Settting the form elements: the header.
  737. if ($_GET['action'] == 'add') {
  738. $title = get_lang('AddTemplate');
  739. } else {
  740. $title = get_lang('EditTemplate');
  741. }
  742. $form->addElement('header', '', $title);
  743. // Settting the form elements: the title of the template.
  744. $form->add_textfield('title', get_lang('Title'), false);
  745. // Settting the form elements: the content of the template (wysiwyg editor).
  746. $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
  747. // Settting the form elements: the form to upload an image to be used with the template.
  748. $form->addElement('file','template_image',get_lang('Image'),'');
  749. // Settting the form elements: a little bit information about the template image.
  750. $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
  751. // Getting all the information of the template when editing a template.
  752. if ($_GET['action'] == 'edit') {
  753. // Database table definition.
  754. $table_system_template = Database :: get_main_table('system_template');
  755. $sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($_GET['id'])."'";
  756. $result = Database::query($sql);
  757. $row = Database::fetch_array($result);
  758. $defaults['template_id'] = intval($_GET['id']);
  759. $defaults['template_text'] = $row['content'];
  760. // Forcing get_lang().
  761. $defaults['title'] = get_lang($row['title']);
  762. // Adding an extra field: a hidden field with the id of the template we are editing.
  763. $form->addElement('hidden', 'template_id');
  764. // Adding an extra field: a preview of the image that is currently used.
  765. if (!empty($row['image'])) {
  766. $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').'"/>');
  767. } else {
  768. $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').'"/>');
  769. }
  770. // Setting the information of the template that we are editing.
  771. $form->setDefaults($defaults);
  772. }
  773. // Settting the form elements: the submit button.
  774. $form->addElement('style_submit_button' , 'submit', get_lang('Ok') ,'class="save"');
  775. // Setting the rules: the required fields.
  776. $form->addRule('title', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
  777. $form->addRule('template_text', '<div class="required">'.get_lang('ThisFieldIsRequired'), 'required');
  778. // if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
  779. if ($form->validate()) {
  780. $check = Security::check_token('post');
  781. if ($check) {
  782. // Exporting the values.
  783. $values = $form->exportValues();
  784. // Upload the file.
  785. if (!empty($_FILES['template_image']['name'])) {
  786. require_once api_get_path(LIBRARY_PATH).'fileUpload.lib.php';
  787. $upload_ok = process_uploaded_file($_FILES['template_image']);
  788. if ($upload_ok) {
  789. // Try to add an extension to the file if it hasn't one.
  790. $new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
  791. // The upload directory.
  792. $upload_dir = api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/';
  793. // Create the directory if it does not exist.
  794. if (!is_dir($upload_dir)) {
  795. mkdir($upload_dir, api_get_permissions_for_new_directories());
  796. }
  797. // Resize the preview image to max default and upload.
  798. $temp = new Image($_FILES['template_image']['tmp_name']);
  799. $picture_info = $temp->get_image_info();
  800. $max_width_for_picture = 100;
  801. if ($picture_info['width'] > $max_width_for_picture) {
  802. $thumbwidth = $max_width_for_picture;
  803. if (empty($thumbwidth) || $thumbwidth == 0) {
  804. $thumbwidth = $max_width_for_picture;
  805. }
  806. $new_height = round(($thumbwidth / $picture_info['width']) * $picture_info['height']);
  807. $temp->resize($thumbwidth, $new_height, 0);
  808. }
  809. $temp->send_image($upload_dir.$new_file_name);
  810. }
  811. }
  812. // Store the information in the database (as insert or as update).
  813. $table_system_template = Database :: get_main_table('system_template');
  814. if ($_GET['action'] == 'add') {
  815. $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
  816. $sql = "INSERT INTO $table_system_template (title, content, image) VALUES ('".Database::escape_string($values['title'])."','".$content_template."','".Database::escape_string($new_file_name)."')";
  817. $result = Database::query($sql);
  818. // Display a feedback message.
  819. Display::display_confirmation_message(get_lang('TemplateAdded'));
  820. echo '<a href="settings.php?category=Templates&amp;action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'','32').'</a>';
  821. } else {
  822. $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
  823. $sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."', content = '".$content_template."'";
  824. if (!empty($new_file_name)) {
  825. $sql .= ", image = '".Database::escape_string($new_file_name)."'";
  826. }
  827. $sql .= " WHERE id='".Database::escape_string($_GET['id'])."'";
  828. $result = Database::query($sql);
  829. // Display a feedback message.
  830. Display::display_confirmation_message(get_lang('TemplateEdited'));
  831. }
  832. }
  833. Security::clear_token();
  834. display_templates();
  835. } else {
  836. $token = Security::get_token();
  837. $form->addElement('hidden','sec_token');
  838. $form->setConstants(array('sec_token' => $token));
  839. // Display the form.
  840. $form->display();
  841. }
  842. }
  843. /**
  844. * Delete a template
  845. *
  846. * @param integer $id the id of the template that has to be deleted
  847. *
  848. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  849. * @version August 2008
  850. * @since Dokeos 1.8.6
  851. */
  852. function delete_template($id) {
  853. // First we remove the image.
  854. $table_system_template = Database :: get_main_table('system_template');
  855. $sql = "SELECT * FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
  856. $result = Database::query($sql);
  857. $row = Database::fetch_array($result);
  858. if (!empty($row['image'])) {
  859. @unlink(api_get_path(SYS_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
  860. }
  861. // Now we remove it from the database.
  862. $sql = "DELETE FROM $table_system_template WHERE id = '".Database::escape_string($id)."'";
  863. $result = Database::query($sql);
  864. // Display a feedback message.
  865. Display::display_confirmation_message(get_lang('TemplateDeleted'));
  866. }
  867. /**
  868. * Returns the list of timezone identifiers used to populate the select
  869. *
  870. * @return array List of timezone identifiers
  871. *
  872. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  873. * @since Chamilo 1.8.7
  874. */
  875. function select_timezone_value() {
  876. return api_get_timezones();
  877. }
  878. /**
  879. * Returns an array containing the list of options used to populate the gradebook_number_decimals variable
  880. *
  881. * @return array List of gradebook_number_decimals options
  882. *
  883. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  884. */
  885. function select_gradebook_number_decimals() {
  886. return array('0', '1', '2');
  887. }
  888. /**
  889. * Updates the gradebook score custom values using the scoredisplay class of the
  890. * gradebook module
  891. *
  892. * @param array List of gradebook score custom values
  893. *
  894. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  895. */
  896. function update_gradebook_score_display_custom_values($values) {
  897. require_once api_get_path(SYS_CODE_PATH).'gradebook/lib/scoredisplay.class.php';
  898. $scoredisplay = ScoreDisplay::instance();
  899. $scores = $values['gradebook_score_display_custom_values_endscore'];
  900. $displays = $values['gradebook_score_display_custom_values_displaytext'];
  901. $nr_displays = count($displays);
  902. $final = array();
  903. for ($i = 1; $i < $nr_displays; $i++) {
  904. if (!empty($scores[$i]) && !empty($displays[$i])) {
  905. $final[$i]['score'] = $scores[$i];
  906. $final[$i]['display'] = $displays[$i];
  907. }
  908. }
  909. $scoredisplay->update_custom_score_display_settings($final);
  910. }