settings.lib.php 65 KB

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