settings.lib.php 65 KB

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