settings.lib.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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. define('CSS_UPLOAD_PATH', api_get_path(SYS_APP_PATH).'Resources/public/css/themes/');
  13. use Symfony\Component\Filesystem\Filesystem;
  14. /**
  15. * This function allows easy activating and inactivating of regions
  16. * @author Julio Montoya <gugli100@gmail.com> Beeznest 2012
  17. */
  18. function handleRegions()
  19. {
  20. if (isset($_POST['submit_plugins'])) {
  21. storeRegions();
  22. // Add event to the system log.
  23. $user_id = api_get_user_id();
  24. $category = $_GET['category'];
  25. Event::addEvent(
  26. LOG_CONFIGURATION_SETTINGS_CHANGE,
  27. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  28. $category,
  29. api_get_utc_datetime(),
  30. $user_id
  31. );
  32. Display :: display_confirmation_message(get_lang('SettingsStored'));
  33. }
  34. $plugin_obj = new AppPlugin();
  35. $possible_plugins = $plugin_obj->read_plugins_from_path();
  36. $installed_plugins = $plugin_obj->get_installed_plugins();
  37. echo '<form name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'">';
  38. echo '<table class="data_table">';
  39. echo '<tr>';
  40. echo '<th width="400px">';
  41. echo get_lang('Plugin');
  42. echo '</th><th>';
  43. echo get_lang('Regions');
  44. echo '</th>';
  45. echo '</th>';
  46. echo '</tr>';
  47. /* We display all the possible plugins and the checkboxes */
  48. $plugin_region_list = array();
  49. $my_plugin_list = $plugin_obj->get_plugin_regions();
  50. foreach ($my_plugin_list as $plugin_item) {
  51. $plugin_region_list[$plugin_item] = $plugin_item;
  52. }
  53. // Removing course tool
  54. unset($plugin_region_list['course_tool_plugin']);
  55. foreach ($installed_plugins as $plugin) {
  56. $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$plugin.'/plugin.php';
  57. if (file_exists($plugin_info_file)) {
  58. $plugin_info = array();
  59. require $plugin_info_file;
  60. if (isset($_GET['name']) && $_GET['name'] == $plugin) {
  61. echo '<tr class="row_selected">';
  62. } else {
  63. echo '<tr>';
  64. }
  65. echo '<td>';
  66. echo '<h4>'.$plugin_info['title'].' <small>v'.$plugin_info['version'].'</small></h4>';
  67. echo '<p>'.$plugin_info['comment'].'</p>';
  68. echo '</td><td>';
  69. $selected_plugins = $plugin_obj->get_areas_by_plugin($plugin);
  70. if (isset($plugin_info['is_course_plugin']) && $plugin_info['is_course_plugin']) {
  71. $region_list = array('course_tool_plugin' => 'course_tool_plugin');
  72. } else {
  73. $region_list = $plugin_region_list;
  74. }
  75. echo Display::select('plugin_'.$plugin.'[]', $region_list, $selected_plugins, array('multiple' => 'multiple', 'style' => 'width:500px'), true, get_lang('None'));
  76. echo '</td></tr>';
  77. }
  78. }
  79. echo '</table>';
  80. echo '<br />';
  81. echo '<button class="btn btn-success" type="submit" name="submit_plugins">'.get_lang('EnablePlugins').'</button></form>';
  82. }
  83. function handleExtensions()
  84. {
  85. echo Display::page_subheader(get_lang('ConfigureExtensions'));
  86. echo '<a class="btn btn-success" href="configure_extensions.php?display=ppt2lp" role="button">'.get_lang('Ppt2lp').'</a>';
  87. }
  88. /**
  89. * This function allows easy activating and inactivating of plugins
  90. * @todo: a similar function needs to be written to activate or inactivate additional tools.
  91. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  92. * @author Julio Montoya <gugli100@gmail.com> Beeznest 2012
  93. */
  94. function handlePlugins()
  95. {
  96. $plugin_obj = new AppPlugin();
  97. $token = Security::get_token();
  98. if (isset($_POST['submit_plugins'])) {
  99. storePlugins();
  100. // Add event to the system log.
  101. $user_id = api_get_user_id();
  102. $category = $_GET['category'];
  103. Event::addEvent(
  104. LOG_CONFIGURATION_SETTINGS_CHANGE,
  105. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  106. $category,
  107. api_get_utc_datetime(),
  108. $user_id
  109. );
  110. Display :: display_confirmation_message(get_lang('SettingsStored'));
  111. }
  112. $all_plugins = $plugin_obj->read_plugins_from_path();
  113. $installed_plugins = $plugin_obj->get_installed_plugins();
  114. //Plugins NOT installed
  115. echo Display::page_subheader(get_lang('Plugins'));
  116. echo '<form class="form-horizontal" name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'&sec_token=' . $token . '">';
  117. echo '<table class="data_table">';
  118. echo '<tr>';
  119. echo '<th width="20px">';
  120. echo get_lang('Action');
  121. echo '</th><th>';
  122. echo get_lang('Description');
  123. echo '</th>';
  124. echo '</tr>';
  125. $plugin_list = array();
  126. $my_plugin_list = $plugin_obj->get_plugin_regions();
  127. foreach($my_plugin_list as $plugin_item) {
  128. $plugin_list[$plugin_item] = $plugin_item;
  129. }
  130. foreach ($all_plugins as $plugin) {
  131. $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$plugin.'/plugin.php';
  132. if (file_exists($plugin_info_file)) {
  133. $plugin_info = array();
  134. require $plugin_info_file;
  135. if (in_array($plugin, $installed_plugins)) {
  136. echo '<tr class="row_selected">';
  137. } else {
  138. echo '<tr>';
  139. }
  140. echo '<td>';
  141. //Checkbox
  142. if (in_array($plugin, $installed_plugins)) {
  143. echo '<input type="checkbox" name="plugin_'.$plugin.'[]" checked="checked">';
  144. } else {
  145. echo '<input type="checkbox" name="plugin_'.$plugin.'[]">';
  146. }
  147. echo '</td><td>';
  148. echo '<h4>'.$plugin_info['title'].' <small>v '.$plugin_info['version'].'</small></h4>';
  149. echo '<p>'.$plugin_info['comment'].'</p>';
  150. echo '<p>'.get_lang('Author').': '.$plugin_info['author'].'</p>';
  151. echo '<div class="btn-group">';
  152. if (in_array($plugin, $installed_plugins)) {
  153. echo Display::url('<em class="fa fa-cogs"></em> '.get_lang('Configure'), 'configure_plugin.php?name='.$plugin, array('class' => 'btn btn-default'));
  154. echo Display::url('<em class="fa fa-th-large"></em> '.get_lang('Regions'), 'settings.php?category=Regions&name='.$plugin, array('class' => 'btn btn-default'));
  155. }
  156. if (file_exists(api_get_path(SYS_PLUGIN_PATH).$plugin.'/readme.txt')) {
  157. echo Display::url(
  158. "<em class='fa fa-file-text-o'></em> readme.txt",
  159. api_get_path(WEB_PLUGIN_PATH) . $plugin . "/readme.txt",
  160. [
  161. 'class' => 'btn btn-default ajax',
  162. 'data-title' => $plugin_info['title'],
  163. 'data-size' => 'lg',
  164. '_target' => '_blank'
  165. ]
  166. );
  167. }
  168. $readmeFile = api_get_path(SYS_PLUGIN_PATH).$plugin.'/README.md';
  169. if (file_exists($readmeFile)) {
  170. echo Display::url(
  171. "<em class='fa fa-file-text-o'></em> README.md",
  172. api_get_path(WEB_AJAX_PATH).'plugin.ajax.php?a=md_to_html&plugin='.$plugin,
  173. [
  174. 'class' => 'btn btn-default ajax',
  175. 'data-title' => $plugin_info['title'],
  176. 'data-size' => 'lg',
  177. '_target' => '_blank'
  178. ]
  179. );
  180. }
  181. echo '</div>';
  182. echo '</td></tr>';
  183. }
  184. }
  185. echo '</table>';
  186. echo '<div class="form-actions bottom_actions">';
  187. echo '<button class="btn btn-success" type="submit" name="submit_plugins">'.
  188. get_lang('EnablePlugins').'</button>';
  189. echo '</div>';
  190. echo '</form>';
  191. }
  192. /**
  193. * This function allows the platform admin to choose the default stylesheet
  194. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  195. * @author Julio Montoya <gugli100@gmail.com>, Chamilo
  196. */
  197. function handleStylesheets()
  198. {
  199. global $_configuration;
  200. // Current style.
  201. $currentstyle = api_get_setting('stylesheets');
  202. $is_style_changeable = isStyleChangeable();
  203. $form = new FormValidator(
  204. 'stylesheet_upload',
  205. 'post',
  206. 'settings.php?category=Stylesheets#tabs-3'
  207. );
  208. $form->addElement('text', 'name_stylesheet', get_lang('NameStylesheet'),
  209. array('size' => '40', 'maxlength' => '40'));
  210. $form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
  211. $form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
  212. $allowed_file_types = getAllowedFileTypes();
  213. $form->addRule('new_stylesheet', get_lang('InvalidExtension') . ' (' . implode(',', $allowed_file_types) . ')',
  214. 'filetype', $allowed_file_types);
  215. $form->addRule('new_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
  216. $form->addButtonUpload(get_lang('Upload'), 'stylesheet_upload');
  217. $show_upload_form = false;
  218. if (!is_writable(CSS_UPLOAD_PATH)) {
  219. Display::display_error_message(CSS_UPLOAD_PATH.get_lang('IsNotWritable'));
  220. } else {
  221. // Uploading a new stylesheet.
  222. if ($_configuration['access_url'] == 1) {
  223. $show_upload_form = true;
  224. } else {
  225. if ($is_style_changeable) {
  226. $show_upload_form = true;
  227. }
  228. }
  229. }
  230. // Stylesheet upload.
  231. if (isset($_POST['stylesheet_upload'])) {
  232. if ($form->validate()) {
  233. $values = $form->exportValues();
  234. $picture_element = $form->getElement('new_stylesheet');
  235. $picture = $picture_element->getValue();
  236. $result = uploadStylesheet($values, $picture);
  237. // Add event to the system log.
  238. $user_id = api_get_user_id();
  239. $category = $_GET['category'];
  240. Event::addEvent(
  241. LOG_CONFIGURATION_SETTINGS_CHANGE,
  242. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  243. $category,
  244. api_get_utc_datetime(),
  245. $user_id
  246. );
  247. if ($result) {
  248. Display::display_confirmation_message(get_lang('StylesheetAdded'));
  249. }
  250. }
  251. }
  252. $form_change = new FormValidator(
  253. 'stylesheet_upload',
  254. 'post',
  255. api_get_self().'?category=Stylesheets',
  256. null,
  257. array('id' => 'stylesheets_id')
  258. );
  259. $list_of_names = array();
  260. $selected = '';
  261. $dirpath = '';
  262. $safe_style_dir = '';
  263. if ($handle = @opendir(CSS_UPLOAD_PATH)) {
  264. $counter = 1;
  265. while (false !== ($style_dir = readdir($handle))) {
  266. if (substr($style_dir, 0, 1) == '.') {
  267. // Skip directories starting with a '.'
  268. continue;
  269. }
  270. $dirpath = CSS_UPLOAD_PATH.$style_dir;
  271. if (is_dir($dirpath)) {
  272. if ($style_dir != '.' && $style_dir != '..') {
  273. if (isset($_POST['style']) &&
  274. (isset($_POST['preview']) || isset($_POST['download'])) &&
  275. $_POST['style'] == $style_dir
  276. ) {
  277. $safe_style_dir = $style_dir;
  278. } else {
  279. if ($currentstyle == $style_dir || ($style_dir == 'chamilo' && !$currentstyle)) {
  280. if (isset($_POST['style'])) {
  281. $selected = Database::escape_string($_POST['style']);
  282. } else {
  283. $selected = $style_dir;
  284. }
  285. }
  286. }
  287. $show_name = ucwords(str_replace('_', ' ', $style_dir));
  288. if ($is_style_changeable) {
  289. $list_of_names[$style_dir] = $show_name;
  290. }
  291. $counter++;
  292. }
  293. }
  294. }
  295. closedir($handle);
  296. }
  297. // Sort styles in alphabetical order.
  298. asort($list_of_names);
  299. $select_list = array();
  300. foreach ($list_of_names as $style_dir => $item) {
  301. $select_list[$style_dir] = $item;
  302. }
  303. $styles = &$form_change->addElement('select', 'style', get_lang('NameStylesheet'), $select_list);
  304. $styles->setSelected($selected);
  305. if ($form_change->validate()) {
  306. // Submit stylesheets.
  307. if (isset($_POST['save'])) {
  308. storeStylesheets();
  309. Display::display_normal_message(get_lang('Saved'));
  310. }
  311. if (isset($_POST['download'])) {
  312. generateCSSDownloadLink($safe_style_dir);
  313. }
  314. }
  315. $logoForm = new FormValidator(
  316. 'logo_upload',
  317. 'post',
  318. 'settings.php?category=Stylesheets#tabs-2'
  319. );
  320. $logoForm->addHtml(Display::return_message(sprintf(get_lang('TheLogoMustBeSizeXAndFormatY'), '250 x 70', 'PNG'), 'info'));
  321. $dir = api_get_path(SYS_PUBLIC_PATH).'css/themes/' . $selected . '/images/';
  322. $url = api_get_path(WEB_CSS_PATH).'themes/' . $selected . '/images/';
  323. $logoFileName = 'header-logo.png';
  324. $newLogoFileName = 'header-logo-custom.png';
  325. if (is_file($dir.$newLogoFileName)) {
  326. $logoForm->addLabel(get_lang('CurrentLogo'), '<img id="header-logo-custom" src="'. $url . $newLogoFileName .'?'. time() . '">');
  327. } else {
  328. $logoForm->addLabel(get_lang('CurrentLogo'), '<img id="header-logo-custom" src="'. $url . $logoFileName .'?'. time() . '">');
  329. }
  330. $logoForm->addFile('new_logo', get_lang('UpdateLogo'));
  331. $allowedFileTypes = ['png'];
  332. if (isset($_POST['logo_reset'])) {
  333. if (is_file($dir.$newLogoFileName)) {
  334. unlink($dir.$newLogoFileName);
  335. Display::display_normal_message(get_lang('ResetToTheOriginalLogo'));
  336. echo '<script>'
  337. . '$("#header-logo").attr("src","'.$url.$logoFileName.'");'
  338. . '</script>';
  339. }
  340. } elseif (isset($_POST['logo_upload'])) {
  341. $logoForm->addRule('new_logo', get_lang('InvalidExtension').' ('.implode(',', $allowedFileTypes).')', 'filetype', $allowedFileTypes);
  342. $logoForm->addRule('new_logo', get_lang('ThisFieldIsRequired'), 'required');
  343. if ($logoForm->validate()) {
  344. $imageInfo = getimagesize($_FILES['new_logo']['tmp_name']);
  345. $width = $imageInfo[0];
  346. $height = $imageInfo[1];
  347. if ($width <= 250 && $height <= 70 ) {
  348. if (is_file($dir.$newLogoFileName)) {
  349. unlink($dir.$newLogoFileName);
  350. }
  351. $status = move_uploaded_file($_FILES['new_logo']['tmp_name'], $dir.$newLogoFileName);
  352. if ($status) {
  353. Display::display_normal_message(get_lang('NewLogoUpdated'));
  354. echo '<script>'
  355. . '$("#header-logo").attr("src","'.$url.$newLogoFileName.'");'
  356. . '</script>';
  357. } else {
  358. Display::display_error_message('Error - '.get_lang('UplNoFileUploaded'));
  359. }
  360. } else {
  361. Display::display_error_message('Error - '.get_lang('InvalidImageDimensions'));
  362. }
  363. }
  364. }
  365. if ($is_style_changeable) {
  366. $group = [
  367. $form_change->addButtonSave(get_lang('SaveSettings'), 'save', true),
  368. $form_change->addButtonPreview(get_lang('Preview'), 'preview', true),
  369. $form_change->addButtonDownload(get_lang('Download'), 'download', true)
  370. ];
  371. $form_change->addGroup($group);
  372. $logoGroup = [
  373. $logoForm->addButtonUpload(get_lang('Upload'), 'logo_upload', true),
  374. $logoForm->addButtonCancel(get_lang('Reset'), 'logo_reset', true)
  375. ];
  376. $logoForm->addGroup($logoGroup);
  377. if ($show_upload_form) {
  378. echo '<script>
  379. $(function() {
  380. $( "#tabs" ).tabs();
  381. });
  382. </script>';
  383. echo Display::tabs(
  384. array(get_lang('Update'),get_lang('UpdateLogo'), get_lang('UploadNewStylesheet')),
  385. array($form_change->return_form(), $logoForm->return_form(), $form->return_form())
  386. );
  387. } else {
  388. $form_change->display();
  389. }
  390. //Little hack to update the logo image in update form when submiting
  391. if (isset($_POST['logo_reset'])) {
  392. echo '<script>'
  393. . '$("#header-logo-custom").attr("src","'.$url.$logoFileName.'");'
  394. . '</script>';
  395. } elseif (isset($_POST['logo_upload']) && is_file($dir.$newLogoFileName)) {
  396. echo '<script>'
  397. . '$("#header-logo-custom").attr("src","'.$url.$newLogoFileName.'");'
  398. . '</script>';
  399. }
  400. } else {
  401. $form_change->freeze();
  402. }
  403. }
  404. /**
  405. * Creates the folder (if needed) and uploads the stylesheet in it
  406. * @param array $values the values of the form
  407. * @param array $picture the values of the uploaded file
  408. * @return bool
  409. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  410. * @version May 2008
  411. * @since v1.8.5
  412. */
  413. function uploadStylesheet($values, $picture)
  414. {
  415. $result = false;
  416. // Valid name for the stylesheet folder.
  417. $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
  418. $cssToUpload = CSS_UPLOAD_PATH;
  419. // Create the folder if needed.
  420. if (!is_dir($cssToUpload.$style_name.'/')) {
  421. mkdir($cssToUpload.$style_name.'/', api_get_permissions_for_new_directories());
  422. }
  423. $info = pathinfo($picture['name']);
  424. if ($info['extension'] == 'zip') {
  425. // Try to open the file and extract it in the theme.
  426. $zip = new ZipArchive();
  427. if ($zip->open($picture['tmp_name'])) {
  428. // Make sure all files inside the zip are images or css.
  429. $num_files = $zip->numFiles;
  430. $valid = true;
  431. $single_directory = true;
  432. $invalid_files = array();
  433. $allowedFiles = getAllowedFileTypes();
  434. for ($i = 0; $i < $num_files; $i++) {
  435. $file = $zip->statIndex($i);
  436. if (substr($file['name'], -1) != '/') {
  437. $path_parts = pathinfo($file['name']);
  438. if (!in_array($path_parts['extension'], $allowedFiles)) {
  439. $valid = false;
  440. $invalid_files[] = $file['name'];
  441. }
  442. }
  443. if (strpos($file['name'], '/') === false) {
  444. $single_directory = false;
  445. }
  446. }
  447. if (!$valid) {
  448. $error_string = '<ul>';
  449. foreach ($invalid_files as $invalid_file) {
  450. $error_string .= '<li>'.$invalid_file.'</li>';
  451. }
  452. $error_string .= '</ul>';
  453. Display::display_error_message(
  454. get_lang('ErrorStylesheetFilesExtensionsInsideZip').$error_string,
  455. false
  456. );
  457. } else {
  458. // If the zip does not contain a single directory, extract it.
  459. if (!$single_directory) {
  460. // Extract zip file.
  461. $zip->extractTo($cssToUpload.$style_name.'/');
  462. $result = true;
  463. } else {
  464. $extraction_path = $cssToUpload.$style_name.'/';
  465. for ($i = 0; $i < $num_files; $i++) {
  466. $entry = $zip->getNameIndex($i);
  467. if (substr($entry, -1) == '/') {
  468. continue;
  469. }
  470. $pos_slash = strpos($entry, '/');
  471. $entry_without_first_dir = substr($entry, $pos_slash + 1);
  472. // If there is still a slash, we need to make sure the directories are created.
  473. if (strpos($entry_without_first_dir, '/') !== false) {
  474. if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
  475. // Create it.
  476. @mkdir($extraction_path.dirname($entry_without_first_dir), $mode = 0777, true);
  477. }
  478. }
  479. $fp = $zip->getStream($entry);
  480. $ofp = fopen($extraction_path.dirname($entry_without_first_dir).'/'.basename($entry), 'w');
  481. while (!feof($fp)) {
  482. fwrite($ofp, fread($fp, 8192));
  483. }
  484. fclose($fp);
  485. fclose($ofp);
  486. }
  487. $result = true;
  488. }
  489. }
  490. $zip->close();
  491. } else {
  492. Display::display_error_message(get_lang('ErrorReadingZip').$info['extension'], false);
  493. }
  494. } else {
  495. // Simply move the file.
  496. move_uploaded_file($picture['tmp_name'], $cssToUpload.$style_name.'/'.$picture['name']);
  497. $result = true;
  498. }
  499. if ($result) {
  500. $fs = new Filesystem();
  501. $fs->mirror($cssToUpload, api_get_path(SYS_PATH).'web/css/themes/');
  502. }
  503. return $result;
  504. }
  505. /**
  506. * Store plugin regions.
  507. */
  508. function storeRegions()
  509. {
  510. $plugin_obj = new AppPlugin();
  511. // Get a list of all current 'Plugins' settings
  512. $installed_plugins = $plugin_obj->get_installed_plugins();
  513. $shortlist_installed = array();
  514. if (!empty($installed_plugins)) {
  515. foreach ($installed_plugins as $plugin) {
  516. if (isset($plugin['subkey'])) {
  517. $shortlist_installed[] = $plugin['subkey'];
  518. }
  519. }
  520. }
  521. $shortlist_installed = array_flip(array_flip($shortlist_installed));
  522. $plugin_list = $plugin_obj->read_plugins_from_path();
  523. foreach ($plugin_list as $plugin) {
  524. if (isset($_POST['plugin_'.$plugin])) {
  525. $areas_to_installed = $_POST['plugin_'.$plugin];
  526. if (!empty($areas_to_installed)) {
  527. $plugin_obj->remove_all_regions($plugin);
  528. foreach ($areas_to_installed as $region) {
  529. if (!empty($region) && $region != '-1' ) {
  530. $plugin_obj->add_to_region($plugin, $region);
  531. }
  532. }
  533. }
  534. }
  535. }
  536. }
  537. /**
  538. * This function allows easy activating and inactivating of plugins
  539. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  540. */
  541. function storePlugins()
  542. {
  543. $appPlugin = new AppPlugin();
  544. // Get a list of all current 'Plugins' settings
  545. $plugin_list = $appPlugin->read_plugins_from_path();
  546. $installed_plugins = array();
  547. foreach ($plugin_list as $plugin) {
  548. if (isset($_POST['plugin_'.$plugin])) {
  549. $appPlugin->install($plugin);
  550. $installed_plugins[] = $plugin;
  551. }
  552. }
  553. if (!empty($installed_plugins)) {
  554. $remove_plugins = array_diff($plugin_list, $installed_plugins);
  555. } else {
  556. $remove_plugins = $plugin_list;
  557. }
  558. foreach ($remove_plugins as $plugin) {
  559. $appPlugin->uninstall($plugin);
  560. }
  561. }
  562. /**
  563. * This function allows the platform admin to choose which should be the default stylesheet
  564. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  565. */
  566. function storeStylesheets()
  567. {
  568. // Insert the stylesheet.
  569. if (isStyle($_POST['style'])) {
  570. api_set_setting(
  571. 'stylesheets',
  572. $_POST['style'],
  573. null,
  574. 'stylesheets',
  575. api_get_current_access_url_id()
  576. );
  577. }
  578. return true;
  579. }
  580. /**
  581. * This function checks if the given style is a recognize style that exists in the css directory as
  582. * a standalone directory.
  583. * @param string Style
  584. * @return bool True if this style is recognized, false otherwise
  585. */
  586. function isStyle($style)
  587. {
  588. $dir = CSS_UPLOAD_PATH;
  589. $dirs = scandir($dir);
  590. $style = str_replace(array('/', '\\'), array('', ''), $style); // Avoid slashes or backslashes.
  591. if (in_array($style, $dirs) && is_dir($dir.$style)) {
  592. return true;
  593. }
  594. return false;
  595. }
  596. /**
  597. * Search options
  598. * TODO: support for multiple site. aka $_configuration['access_url'] == 1
  599. * @author Marco Villegas <marvil07@gmail.com>
  600. */
  601. function handleSearch()
  602. {
  603. global $SettingsStored, $_configuration;
  604. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  605. $search_enabled = api_get_setting('search_enabled');
  606. $form = new FormValidator('search-options', 'post', api_get_self().'?category=Search');
  607. $values = api_get_settings_options('search_enabled');
  608. $form->addElement('header', null, get_lang('SearchEnabledTitle'));
  609. $group = formGenerateElementsGroup($form, $values, 'search_enabled');
  610. //SearchEnabledComment
  611. $form->addGroup($group, 'search_enabled', array(get_lang('SearchEnabledTitle'), get_lang('SearchEnabledComment')), '<br />', false);
  612. $search_enabled = api_get_setting('search_enabled');
  613. if ($form->validate()) {
  614. $formValues = $form->exportValues();
  615. setConfigurationSettingsInDatabase($formValues, $_configuration['access_url']);
  616. $search_enabled = $formValues['search_enabled'];
  617. Display::display_confirmation_message($SettingsStored);
  618. }
  619. $specific_fields = get_specific_field_list();
  620. if ($search_enabled == 'true') {
  621. $values = api_get_settings_options('search_show_unlinked_results');
  622. $group = formGenerateElementsGroup($form, $values, 'search_show_unlinked_results');
  623. $form->addGroup($group, 'search_show_unlinked_results', array(get_lang('SearchShowUnlinkedResultsTitle'),get_lang('SearchShowUnlinkedResultsComment')), '', false);
  624. $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
  625. $sf_values = array();
  626. foreach ($specific_fields as $sf) {
  627. $sf_values[$sf['code']] = $sf['name'];
  628. }
  629. $url = Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'), array('class'=>'sectioncomment'));
  630. if (empty($sf_values)) {
  631. $form->addElement('label', [get_lang('SearchPrefilterPrefix'), $url]);
  632. } else {
  633. $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url), $sf_values, '');
  634. $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
  635. }
  636. }
  637. $default_values['search_enabled'] = $search_enabled;
  638. $form->addButtonSave(get_lang('Save'));
  639. $form->setDefaults($default_values);
  640. echo '<div id="search-options-form">';
  641. $form->display();
  642. echo '</div>';
  643. if ($search_enabled == 'true') {
  644. $xapianPath = api_get_path(SYS_UPLOAD_PATH).'plugins/xapian/searchdb';
  645. /*
  646. @todo Test the Xapian connection
  647. if (extension_loaded('xapian')) {
  648. require_once 'xapian.php';
  649. try {
  650. $db = new XapianDatabase($xapianPath.'/');
  651. } catch (Exception $e) {
  652. var_dump($e->getMessage());
  653. }
  654. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
  655. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  656. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  657. $indexable = new IndexableChunk();
  658. $indexable->addValue("content", 'Test');
  659. $di = new ChamiloIndexer();
  660. $di->connectDb(NULL, NULL, 'english');
  661. $di->addChunk($indexable);
  662. $did = $di->index();
  663. }
  664. */
  665. $xapianLoaded = Display::return_icon('bullet_green.png', get_lang('Ok'));
  666. $dir_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
  667. $dir_is_writable = Display::return_icon('bullet_green.png', get_lang('Ok'));
  668. $specific_fields_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
  669. //Testing specific fields
  670. if (empty($specific_fields)) {
  671. $specific_fields_exists = Display::return_icon('bullet_red.png', get_lang('AddSpecificSearchField'));
  672. }
  673. //Testing xapian extension
  674. if (!extension_loaded('xapian')) {
  675. $xapianLoaded = Display::return_icon('bullet_red.png', get_lang('Error'));
  676. }
  677. //Testing xapian searchdb path
  678. if (!is_dir($xapianPath)) {
  679. $dir_exists = Display::return_icon('bullet_red.png', get_lang('Error'));
  680. }
  681. //Testing xapian searchdb path is writable
  682. if (!is_writable($xapianPath)) {
  683. $dir_is_writable = Display::return_icon('bullet_red.png', get_lang('Error'));
  684. }
  685. $data = array();
  686. $data[] = array(get_lang('XapianModuleInstalled'), $xapianLoaded);
  687. $data[] = array(get_lang('DirectoryExists').' - '.$xapianPath, $dir_exists);
  688. $data[] = array(get_lang('IsWritable').' - '.$xapianPath, $dir_is_writable);
  689. $data[] = array(get_lang('SpecificSearchFieldsAvailable'), $specific_fields_exists);
  690. showSearchSettingsTable($data);
  691. showSearchToolsStatusTable();
  692. }
  693. }
  694. /**
  695. * Wrapper for the templates
  696. *
  697. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  698. * @author Julio Montoya.
  699. * @version August 2008
  700. * @since v1.8.6
  701. */
  702. function handleTemplates()
  703. {
  704. /* Drive-by fix to avoid undefined var warnings, without repeating
  705. * isset() combos all over the place. */
  706. $action = isset($_GET['action']) ? $_GET['action'] : "invalid";
  707. if ($action != 'add') {
  708. echo '<div class="actions" style="margin-left: 1px;">';
  709. echo '<a href="settings.php?category=Templates&action=add">'.
  710. Display::return_icon('new_template.png', get_lang('AddTemplate'),'',ICON_SIZE_MEDIUM).'</a>';
  711. echo '</div>';
  712. }
  713. if ($action == 'add' || ($action == 'edit' && is_numeric($_GET['id']))) {
  714. addEditTemplate();
  715. // Add event to the system log.
  716. $user_id = api_get_user_id();
  717. $category = $_GET['category'];
  718. Event::addEvent(
  719. LOG_CONFIGURATION_SETTINGS_CHANGE,
  720. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  721. $category,
  722. api_get_utc_datetime(),
  723. $user_id
  724. );
  725. } else {
  726. if ($action == 'delete' && is_numeric($_GET['id'])) {
  727. deleteTemplate($_GET['id']);
  728. // Add event to the system log
  729. $user_id = api_get_user_id();
  730. $category = $_GET['category'];
  731. Event::addEvent(
  732. LOG_CONFIGURATION_SETTINGS_CHANGE,
  733. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  734. $category,
  735. api_get_utc_datetime(),
  736. $user_id
  737. );
  738. }
  739. displayTemplates();
  740. }
  741. }
  742. /**
  743. * Display a sortable table with all the templates that the platform administrator has defined.
  744. *
  745. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  746. * @version August 2008
  747. * @since v1.8.6
  748. */
  749. function displayTemplates()
  750. {
  751. $table = new SortableTable('templates', 'getNumberOfTemplates', 'getTemplateData', 1);
  752. $table->set_additional_parameters(array('category' => Security::remove_XSS($_GET['category'])));
  753. $table->set_header(0, get_lang('Image'), true, array('style' => 'width: 101px;'));
  754. $table->set_header(1, get_lang('Title'));
  755. $table->set_header(2, get_lang('Actions'), false, array('style' => 'width:50px;'));
  756. $table->set_column_filter(2, 'actionsFilter');
  757. $table->set_column_filter(0, 'searchImageFilter');
  758. $table->display();
  759. }
  760. /**
  761. * Gets the number of templates that are defined by the platform admin.
  762. *
  763. * @return integer
  764. *
  765. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  766. * @version August 2008
  767. * @since v1.8.6
  768. */
  769. function getNumberOfTemplates()
  770. {
  771. // Database table definition.
  772. $table_system_template = Database :: get_main_table('system_template');
  773. // The sql statement.
  774. $sql = "SELECT COUNT(id) AS total FROM $table_system_template";
  775. $result = Database::query($sql);
  776. $row = Database::fetch_array($result);
  777. // Returning the number of templates.
  778. return $row['total'];
  779. }
  780. /**
  781. * Gets all the template data for the sortable table.
  782. *
  783. * @param integer $from the start of the limit statement
  784. * @param integer $number_of_items the number of elements that have to be retrieved from the database
  785. * @param integer $column the column that is
  786. * @param string $direction the sorting direction (ASC or DESC�
  787. * @return array
  788. *
  789. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  790. * @version August 2008
  791. * @since v1.8.6
  792. */
  793. function getTemplateData($from, $number_of_items, $column, $direction)
  794. {
  795. // Database table definition.
  796. $table_system_template = Database :: get_main_table('system_template');
  797. // The sql statement.
  798. $sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
  799. $sql .= " ORDER BY col$column $direction ";
  800. $sql .= " LIMIT $from,$number_of_items";
  801. $result = Database::query($sql);
  802. $return = array();
  803. while ($row = Database::fetch_array($result)) {
  804. $row['1'] = get_lang($row['1']);
  805. $return[] = $row;
  806. }
  807. // Returning all the information for the sortable table.
  808. return $return;
  809. }
  810. /**
  811. * display the edit and delete icons in the sortable table
  812. *
  813. * @param integer $id the id of the template
  814. * @return string code for the link to edit and delete the template
  815. *
  816. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  817. * @version August 2008
  818. * @since v1.8.6
  819. */
  820. function actionsFilter($id) {
  821. $return = '<a href="settings.php?category=Templates&action=edit&id='.Security::remove_XSS($id).'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
  822. $return .= '<a href="settings.php?category=Templates&action=delete&id='.Security::remove_XSS($id).'" onClick="javascript:if(!confirm('."'".get_lang('ConfirmYourChoice')."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
  823. return $return;
  824. }
  825. /**
  826. * Display the image of the template in the sortable table
  827. *
  828. * @param string $image the image
  829. * @return string code for the image
  830. *
  831. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  832. * @version August 2008
  833. * @since v1.8.6
  834. */
  835. function searchImageFilter($image)
  836. {
  837. if (!empty($image)) {
  838. return '<img src="'.api_get_path(WEB_APP_PATH).'home/default_platform_document/template_thumb/'.$image.'" alt="'.get_lang('TemplatePreview').'"/>';
  839. } else {
  840. return '<img src="'.api_get_path(WEB_APP_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>';
  841. }
  842. }
  843. /**
  844. * Add (or edit) a template. This function displays the form and also takes
  845. * care of uploading the image and storing the information in the database
  846. *
  847. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  848. * @version August 2008
  849. * @since v1.8.6
  850. */
  851. function addEditTemplate()
  852. {
  853. // Initialize the object.
  854. $id = isset($_GET['id']) ? '&id='.Security::remove_XSS($_GET['id']) : '';
  855. $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).$id);
  856. // Setting the form elements: the header.
  857. if ($_GET['action'] == 'add') {
  858. $title = get_lang('AddTemplate');
  859. } else {
  860. $title = get_lang('EditTemplate');
  861. }
  862. $form->addElement('header', '', $title);
  863. // Setting the form elements: the title of the template.
  864. $form->addText('title', get_lang('Title'), false);
  865. // Setting the form elements: the content of the template (wysiwyg editor).
  866. $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
  867. // Setting the form elements: the form to upload an image to be used with the template.
  868. $form->addElement('file','template_image',get_lang('Image'),'');
  869. // Setting the form elements: a little bit information about the template image.
  870. $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
  871. // Getting all the information of the template when editing a template.
  872. if ($_GET['action'] == 'edit') {
  873. // Database table definition.
  874. $table_system_template = Database :: get_main_table('system_template');
  875. $sql = "SELECT * FROM $table_system_template WHERE id = ".intval($_GET['id'])."";
  876. $result = Database::query($sql);
  877. $row = Database::fetch_array($result);
  878. $defaults['template_id'] = intval($_GET['id']);
  879. $defaults['template_text'] = $row['content'];
  880. // Forcing get_lang().
  881. $defaults['title'] = get_lang($row['title']);
  882. // Adding an extra field: a hidden field with the id of the template we are editing.
  883. $form->addElement('hidden', 'template_id');
  884. // Adding an extra field: a preview of the image that is currently used.
  885. if (!empty($row['image'])) {
  886. $form->addElement('static', 'template_image_preview', '',
  887. '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/' . $row['image'] . '" alt="' . get_lang('TemplatePreview') . '"/>');
  888. } else {
  889. $form->addElement('static', 'template_image_preview', '',
  890. '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/noimage.gif" alt="' . get_lang('NoTemplatePreview') . '"/>');
  891. }
  892. // Setting the information of the template that we are editing.
  893. $form->setDefaults($defaults);
  894. }
  895. // Setting the form elements: the submit button.
  896. $form->addButtonSave(get_lang('Ok'), 'submit');
  897. // Setting the rules: the required fields.
  898. $form->addRule('template_image', get_lang('ThisFieldIsRequired'), 'required');
  899. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  900. $form->addRule('template_text', get_lang('ThisFieldIsRequired'), 'required');
  901. // if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
  902. if ($form->validate()) {
  903. $check = Security::check_token('post');
  904. if ($check) {
  905. // Exporting the values.
  906. $values = $form->exportValues();
  907. // Upload the file.
  908. if (!empty($_FILES['template_image']['name'])) {
  909. $upload_ok = process_uploaded_file($_FILES['template_image']);
  910. if ($upload_ok) {
  911. // Try to add an extension to the file if it hasn't one.
  912. $new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
  913. // The upload directory.
  914. $upload_dir = api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/';
  915. // Create the directory if it does not exist.
  916. if (!is_dir($upload_dir)) {
  917. mkdir($upload_dir, api_get_permissions_for_new_directories());
  918. }
  919. // Resize the preview image to max default and upload.
  920. $temp = new Image($_FILES['template_image']['tmp_name']);
  921. $picture_info = $temp->get_image_info();
  922. $max_width_for_picture = 100;
  923. if ($picture_info['width'] > $max_width_for_picture) {
  924. $temp->resize($max_width_for_picture);
  925. }
  926. $temp->send_image($upload_dir.$new_file_name);
  927. }
  928. }
  929. // Store the information in the database (as insert or as update).
  930. $table_system_template = Database :: get_main_table('system_template');
  931. if ($_GET['action'] == 'add') {
  932. $content_template = Security::remove_XSS($values['template_text'], COURSEMANAGERLOWSECURITY);
  933. $params = [
  934. 'title' => $values['title'],
  935. 'content' => $content_template,
  936. 'image' => $new_file_name
  937. ];
  938. Database::insert($table_system_template, $params);
  939. // Display a feedback message.
  940. Display::display_confirmation_message(get_lang('TemplateAdded'));
  941. echo '<a href="settings.php?category=Templates&action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'',ICON_SIZE_MEDIUM).'</a>';
  942. } else {
  943. $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
  944. $sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."', content = '".$content_template."'";
  945. if (!empty($new_file_name)) {
  946. $sql .= ", image = '".Database::escape_string($new_file_name)."'";
  947. }
  948. $sql .= " WHERE id = ".intval($_GET['id'])."";
  949. Database::query($sql);
  950. // Display a feedback message.
  951. Display::display_confirmation_message(get_lang('TemplateEdited'));
  952. }
  953. }
  954. Security::clear_token();
  955. displayTemplates();
  956. } else {
  957. $token = Security::get_token();
  958. $form->addElement('hidden','sec_token');
  959. $form->setConstants(array('sec_token' => $token));
  960. // Display the form.
  961. $form->display();
  962. }
  963. }
  964. /**
  965. * Delete a template
  966. *
  967. * @param integer $id the id of the template that has to be deleted
  968. *
  969. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  970. * @version August 2008
  971. * @since v1.8.6
  972. */
  973. function deleteTemplate($id)
  974. {
  975. // First we remove the image.
  976. $table_system_template = Database :: get_main_table('system_template');
  977. $sql = "SELECT * FROM $table_system_template WHERE id = ".intval($id)."";
  978. $result = Database::query($sql);
  979. $row = Database::fetch_array($result);
  980. if (!empty($row['image'])) {
  981. @unlink(api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
  982. }
  983. // Now we remove it from the database.
  984. $sql = "DELETE FROM $table_system_template WHERE id = ".intval($id)."";
  985. Database::query($sql);
  986. // Display a feedback message.
  987. Display::display_confirmation_message(get_lang('TemplateDeleted'));
  988. }
  989. /**
  990. * @param array $settings
  991. * @param array $settings_by_access_list
  992. *
  993. * @return FormValidator
  994. *
  995. * @throws \Doctrine\ORM\ORMException
  996. * @throws \Doctrine\ORM\OptimisticLockException
  997. * @throws \Doctrine\ORM\TransactionRequiredException
  998. */
  999. function generateSettingsForm($settings, $settings_by_access_list)
  1000. {
  1001. global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
  1002. $em = Database::getManager();
  1003. $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1004. $form = new FormValidator('settings', 'post', 'settings.php?category='.Security::remove_XSS($_GET['category']));
  1005. $form->addElement(
  1006. 'hidden',
  1007. 'search_field',
  1008. (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null)
  1009. );
  1010. $url_id = api_get_current_access_url_id();
  1011. if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) {
  1012. $group = array();
  1013. $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
  1014. $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
  1015. $form->addGroup($group, 'buttons_in_action_right');
  1016. }
  1017. $default_values = array();
  1018. $url_info = api_get_access_url($url_id);
  1019. $i = 0;
  1020. $addedSettings = [];
  1021. foreach ($settings as $row) {
  1022. if (in_array($row['variable'], array_keys($settings_to_avoid))) {
  1023. continue;
  1024. }
  1025. if (in_array($row['variable'], $addedSettings)) {
  1026. continue;
  1027. }
  1028. $addedSettings[] = $row['variable'];
  1029. if (!empty($_configuration['multiple_access_urls'])) {
  1030. if (api_is_global_platform_admin()) {
  1031. if ($row['access_url_locked'] == 0) {
  1032. if ($url_id == 1) {
  1033. if ($row['access_url_changeable'] == '1') {
  1034. $form->addElement(
  1035. 'html',
  1036. '<div style="float: right;"><a class="share_this_setting" data_status = "0" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
  1037. Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting')).'</a></div>'
  1038. );
  1039. } else {
  1040. $form->addElement(
  1041. 'html',
  1042. '<div style="float: right;"><a class="share_this_setting" data_status = "1" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
  1043. Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting')).'</a></div>'
  1044. );
  1045. }
  1046. } else {
  1047. if ($row['access_url_changeable'] == '1') {
  1048. $form->addElement(
  1049. 'html',
  1050. '<div style="float: right;">'.
  1051. Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting')).'</div>'
  1052. );
  1053. } else {
  1054. $form->addElement(
  1055. 'html',
  1056. '<div style="float: right;">'.
  1057. Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting')).'</div>'
  1058. );
  1059. }
  1060. }
  1061. }
  1062. }
  1063. }
  1064. $hideme = array();
  1065. $hide_element = false;
  1066. if ($_configuration['access_url'] != 1) {
  1067. if ($row['access_url_changeable'] == 0) {
  1068. // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
  1069. $hide_element = true;
  1070. $hideme = array('disabled');
  1071. } elseif ($url_info['active'] == 1) {
  1072. // We show the elements.
  1073. if (empty($row['variable'])) {
  1074. $row['variable'] = 0;
  1075. }
  1076. if (empty($row['subkey'])) {
  1077. $row['subkey'] = 0;
  1078. }
  1079. if (empty($row['category'])) {
  1080. $row['category'] = 0;
  1081. }
  1082. if (is_array($settings_by_access_list[ $row['variable'] ] [ $row['subkey'] ] [ $row['category'] ])) {
  1083. // We are sure that the other site have a selected value.
  1084. if ($settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']]['selected_value'] != '') {
  1085. $row['selected_value'] = $settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']]['selected_value'];
  1086. }
  1087. }
  1088. // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
  1089. }
  1090. }
  1091. switch ($row['type']) {
  1092. case 'textfield':
  1093. if (in_array($row['variable'], $convert_byte_to_mega_list)) {
  1094. $form->addElement(
  1095. 'text',
  1096. $row['variable'],
  1097. array(
  1098. get_lang($row['title']),
  1099. get_lang($row['comment']),
  1100. get_lang('MB')
  1101. ),
  1102. array('maxlength' => '8')
  1103. );
  1104. $form->applyFilter($row['variable'], 'html_filter');
  1105. $default_values[$row['variable']] = round($row['selected_value']/1024/1024, 1);
  1106. } elseif ($row['variable'] == 'account_valid_duration') {
  1107. $form->addElement(
  1108. 'text',
  1109. $row['variable'],
  1110. array(
  1111. get_lang($row['title']),
  1112. get_lang($row['comment']),
  1113. ),
  1114. array('maxlength' => '5')
  1115. );
  1116. $form->applyFilter($row['variable'], 'html_filter');
  1117. $default_values[$row['variable']] = $row['selected_value'];
  1118. // For platform character set selection: Conversion of the textfield to a select box with valid values.
  1119. } elseif ($row['variable'] == 'platform_charset') {
  1120. continue;
  1121. } else {
  1122. $hideme['class'] = 'col-md-4';
  1123. $form->addElement(
  1124. 'text',
  1125. $row['variable'],
  1126. array(
  1127. get_lang($row['title']),
  1128. get_lang($row['comment'])
  1129. ),
  1130. $hideme
  1131. );
  1132. $form->applyFilter($row['variable'],'html_filter');
  1133. $default_values[$row['variable']] = $row['selected_value'];
  1134. }
  1135. break;
  1136. case 'textarea':
  1137. if ($row['variable'] == 'header_extra_content') {
  1138. $file = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt';
  1139. $value = '';
  1140. if (file_exists($file)) {
  1141. $value = file_get_contents($file);
  1142. }
  1143. $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
  1144. $default_values[$row['variable']] = $value;
  1145. } elseif ($row['variable'] == 'footer_extra_content') {
  1146. $file = api_get_path(SYS_PATH).api_get_home_path().'footer_extra_content.txt';
  1147. $value = '';
  1148. if (file_exists($file)) {
  1149. $value = file_get_contents($file);
  1150. }
  1151. $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
  1152. $default_values[$row['variable']] = $value;
  1153. } else {
  1154. $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
  1155. $default_values[$row['variable']] = $row['selected_value'];
  1156. }
  1157. break;
  1158. case 'radio':
  1159. $values = api_get_settings_options($row['variable']);
  1160. $group = array ();
  1161. if (is_array($values)) {
  1162. foreach ($values as $key => $value) {
  1163. $element = &$form->createElement(
  1164. 'radio',
  1165. $row['variable'],
  1166. '',
  1167. $value['display_text'],
  1168. $value['value']
  1169. );
  1170. if ($hide_element) {
  1171. $element->freeze();
  1172. }
  1173. $group[] = $element;
  1174. }
  1175. }
  1176. $form->addGroup(
  1177. $group,
  1178. $row['variable'],
  1179. array(get_lang($row['title']), get_lang($row['comment'])),
  1180. '',
  1181. false
  1182. );
  1183. $default_values[$row['variable']] = $row['selected_value'];
  1184. break;
  1185. case 'checkbox';
  1186. // 1. We collect all the options of this variable.
  1187. $sql = "SELECT * FROM $table_settings_current
  1188. WHERE variable='".$row['variable']."' AND access_url = 1";
  1189. $result = Database::query($sql);
  1190. $group = array ();
  1191. while ($rowkeys = Database::fetch_array($result)) {
  1192. // Profile tab option should be hidden when the social tool is enabled.
  1193. if (api_get_setting('allow_social_tool') == 'true') {
  1194. if ($rowkeys['variable'] === 'show_tabs' && $rowkeys['subkey'] === 'my_profile') {
  1195. continue;
  1196. }
  1197. }
  1198. // Hiding the gradebook option.
  1199. if ($rowkeys['variable'] === 'show_tabs' && $rowkeys['subkey'] === 'my_gradebook') {
  1200. continue;
  1201. }
  1202. $element = &$form->createElement(
  1203. 'checkbox',
  1204. $rowkeys['subkey'],
  1205. '',
  1206. get_lang($rowkeys['subkeytext'])
  1207. );
  1208. if ($row['access_url_changeable'] == 1) {
  1209. // 2. We look into the DB if there is a setting for a specific access_url.
  1210. $access_url = $_configuration['access_url'];
  1211. if (empty($access_url)) {
  1212. $access_url = 1;
  1213. }
  1214. $sql = "SELECT selected_value FROM $table_settings_current
  1215. WHERE
  1216. variable='".$rowkeys['variable']."' AND
  1217. subkey='".$rowkeys['subkey']."' AND
  1218. subkeytext='".$rowkeys['subkeytext']."' AND
  1219. access_url = $access_url";
  1220. $result_access = Database::query($sql);
  1221. $row_access = Database::fetch_array($result_access);
  1222. if ($row_access['selected_value'] === 'true' && !$form->isSubmitted()) {
  1223. $element->setChecked(true);
  1224. }
  1225. } else {
  1226. if ($rowkeys['selected_value'] === 'true' && !$form->isSubmitted()) {
  1227. $element->setChecked(true);
  1228. }
  1229. }
  1230. if ($hide_element) {
  1231. $element->freeze();
  1232. }
  1233. $group[] = $element;
  1234. }
  1235. $form->addGroup(
  1236. $group,
  1237. $row['variable'],
  1238. array(get_lang($row['title']), get_lang($row['comment'])),
  1239. ''
  1240. );
  1241. break;
  1242. case 'link':
  1243. $form->addElement('static', null, array(get_lang($row['title']), get_lang($row['comment'])),
  1244. get_lang('CurrentValue') . ' : ' . $row['selected_value'], $hideme);
  1245. break;
  1246. case 'select':
  1247. /*
  1248. * To populate the list of options, the select type dynamically calls a function that must be called select_ + the name of the variable being displayed.
  1249. * The functions being called must be added to the file settings.lib.php.
  1250. */
  1251. $form->addElement('select', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])), call_user_func('select_'.$row['variable']), $hideme);
  1252. $default_values[$row['variable']] = $row['selected_value'];
  1253. break;
  1254. case 'custom':
  1255. break;
  1256. case 'select_course':
  1257. $courseSelectOptions = [];
  1258. if (!empty($row['selected_value'])) {
  1259. $course = $em->find('ChamiloCoreBundle:Course', $row['selected_value']);
  1260. $courseSelectOptions[$course->getId()] = $course->getTitle();
  1261. }
  1262. $form->addElement(
  1263. 'select_ajax',
  1264. $row['variable'],
  1265. [get_lang($row['title']), get_lang($row['comment'])],
  1266. $courseSelectOptions,
  1267. ['url' => api_get_path(WEB_AJAX_PATH) . 'course.ajax.php?a=search_course']
  1268. );
  1269. $default_values[$row['variable']] = $row['selected_value'];
  1270. break;
  1271. }
  1272. switch ($row['variable']) {
  1273. case 'pdf_export_watermark_enable':
  1274. $url = PDF::get_watermark(null);
  1275. if ($url != false) {
  1276. $delete_url = '<a href="?delete_watermark">'.get_lang('DelImage').' '.Display::return_icon('delete.png',get_lang('DelImage')).'</a>';
  1277. $form->addElement('html', '<div style="max-height:100px; max-width:100px; margin-left:162px; margin-bottom:10px; clear:both;"><img src="'.$url.'" style="margin-bottom:10px;" />'.$delete_url.'</div>');
  1278. }
  1279. $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark'));
  1280. $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
  1281. $form->addRule('pdf_export_watermark_path', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
  1282. break;
  1283. case 'timezone_value':
  1284. $timezone = $row['selected_value'];
  1285. if (empty($timezone)) {
  1286. $timezone = _api_get_timezone();
  1287. }
  1288. $form->addElement('html', sprintf(get_lang('LocalTimeUsingPortalTimezoneXIsY'), $timezone, api_get_local_time()));
  1289. break;
  1290. }
  1291. } // end for
  1292. if (!empty($settings)) {
  1293. $form->setDefaults($default_values);
  1294. }
  1295. $form->addHtml('<div class="bottom_actions">');
  1296. $form->addButtonSave(get_lang('SaveSettings'));
  1297. $form->addHtml('</div>');
  1298. return $form;
  1299. }
  1300. /**
  1301. * Searches a platform setting in all categories except from the Plugins category
  1302. * @param string $search
  1303. * @return array
  1304. */
  1305. function searchSetting($search)
  1306. {
  1307. if (empty($search)) {
  1308. return array();
  1309. }
  1310. $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1311. $sql = "SELECT * FROM $table_settings_current
  1312. WHERE category <> 'Plugins' ORDER BY id ASC ";
  1313. $result = Database::store_result(Database::query($sql), 'ASSOC');
  1314. $settings = array();
  1315. $search = api_strtolower($search);
  1316. if (!empty($result)) {
  1317. foreach ($result as $setting) {
  1318. $found = false;
  1319. $title = api_strtolower(get_lang($setting['title']));
  1320. // try the title
  1321. if (strpos($title, $search) === false) {
  1322. $comment = api_strtolower(get_lang($setting['comment']));
  1323. //Try the comment
  1324. if (strpos($comment, $search) === false) {
  1325. //Try the variable name
  1326. if (strpos($setting['variable'], $search) === false) {
  1327. continue;
  1328. } else {
  1329. $found = true;
  1330. }
  1331. } else {
  1332. $found = true;
  1333. }
  1334. } else {
  1335. $found = true;
  1336. }
  1337. if ($found) {
  1338. $settings[] = $setting;
  1339. }
  1340. }
  1341. }
  1342. return $settings;
  1343. }
  1344. /**
  1345. * Helper function to generates a form elements group
  1346. * @param object $form The form where the elements group has to be added
  1347. * @param array $values Values to browse through
  1348. * @return array
  1349. */
  1350. function formGenerateElementsGroup($form, $values = array(), $elementName)
  1351. {
  1352. $group = array();
  1353. if (is_array($values)) {
  1354. foreach ($values as $key => $value) {
  1355. $element = &$form->createElement('radio', $elementName, '', $value['display_text'], $value['value']);
  1356. $group[] = $element;
  1357. }
  1358. }
  1359. return $group;
  1360. }
  1361. /**
  1362. * Helper function with allowed file types for CSS
  1363. * @return array Array of file types (no indexes)
  1364. */
  1365. function getAllowedFileTypes()
  1366. {
  1367. $allowedFiles = array(
  1368. 'css',
  1369. 'zip',
  1370. 'jpeg',
  1371. 'jpg',
  1372. 'png',
  1373. 'gif',
  1374. 'ico',
  1375. 'psd',
  1376. 'xcf',
  1377. 'svg',
  1378. 'webp',
  1379. 'woff',
  1380. 'woff2'
  1381. );
  1382. return $allowedFiles;
  1383. }
  1384. /**
  1385. * Helper function to set settings in the database
  1386. * @param array $parameters List of values
  1387. * @param int $accessUrl The current access URL
  1388. * @return void
  1389. */
  1390. function setConfigurationSettingsInDatabase($parameters, $accessUrl)
  1391. {
  1392. $r = api_set_settings_category('Search', 'false', $accessUrl);
  1393. // Save the settings.
  1394. foreach ($parameters as $key => $value) {
  1395. $result = api_set_setting($key, $value, null, null);
  1396. }
  1397. }
  1398. /**
  1399. * Helper function to show the status of the search settings table
  1400. * @param array $data Data to show
  1401. * @return void
  1402. */
  1403. function showSearchSettingsTable($data)
  1404. {
  1405. echo Display::tag('h3', get_lang('Settings'));
  1406. $table = new SortableTableFromArray($data);
  1407. $table->set_header(0, get_lang('Setting'), false);
  1408. $table->set_header(1, get_lang('Status'), false);
  1409. echo $table->display();
  1410. }
  1411. /**
  1412. * Helper function to show status table for each command line tool installed
  1413. * @return void
  1414. */
  1415. function showSearchToolsStatusTable()
  1416. {
  1417. //@todo windows support
  1418. if (api_is_windows_os() == false) {
  1419. $list_of_programs = array('pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv');
  1420. foreach($list_of_programs as $program) {
  1421. $output = [];
  1422. $ret_val = null;
  1423. exec("which $program", $output, $ret_val);
  1424. if (!$output) {
  1425. $output[] = '';
  1426. }
  1427. $icon = Display::return_icon('bullet_red.png', get_lang('NotInstalled'));
  1428. if (!empty($output[0])) {
  1429. $icon = Display::return_icon('bullet_green.png', get_lang('Installed'));
  1430. }
  1431. $data2[]= array($program, $output[0], $icon);
  1432. }
  1433. echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles'));
  1434. $table = new SortableTableFromArray($data2);
  1435. $table->set_header(0, get_lang('Program'), false);
  1436. $table->set_header(1, get_lang('Path'), false);
  1437. $table->set_header(2, get_lang('Status'), false);
  1438. echo $table->display();
  1439. } else {
  1440. Display::display_warning_message(
  1441. get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool')
  1442. );
  1443. }
  1444. }
  1445. /**
  1446. * Helper function to generate and show CSS Zip download message
  1447. * @param string $style Style path
  1448. * @return void
  1449. */
  1450. function generateCSSDownloadLink($style)
  1451. {
  1452. $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
  1453. $dir = api_get_path(SYS_CSS_PATH).'themes/'.$style;
  1454. if (is_dir($dir)) {
  1455. $zip = new PclZip($arch);
  1456. // Remove path prefix except the style name and put file on disk
  1457. $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir,0,-strlen($style)));
  1458. //@TODO: use more generic script to download.
  1459. $str = '<a class="btn btn-primary btn-large" href="' . api_get_path(WEB_CODE_PATH) . 'course_info/download.php?archive=' . str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch) . '">'.get_lang('ClickHereToDownloadTheFile').'</a>';
  1460. Display::display_normal_message($str, false);
  1461. } else {
  1462. Display::addFlash(Display::return_message(get_lang('FileNotFound'), 'warning'));
  1463. }
  1464. }
  1465. /**
  1466. * Helper function to tell if the style is changeable in the current URL
  1467. * @return bool $changeable Whether the style can be changed in this URL or not
  1468. */
  1469. function isStyleChangeable() {
  1470. global $_configuration;
  1471. $changeable = false;
  1472. if ($_configuration['access_url'] != 1) {
  1473. $style_info = api_get_settings('stylesheets', '', 1, 0);
  1474. $url_info = api_get_access_url($_configuration['access_url']);
  1475. if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
  1476. $changeable = true;
  1477. }
  1478. } else {
  1479. $changeable = true;
  1480. }
  1481. return $changeable;
  1482. }