settings.lib.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  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->return_form(), $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. Display::display_error_message(
  481. get_lang('ErrorStylesheetFilesExtensionsInsideZip').$error_string,
  482. false
  483. );
  484. } else {
  485. // If the zip does not contain a single directory, extract it.
  486. if (!$single_directory) {
  487. // Extract zip file.
  488. $zip->extractTo($cssToUpload.$style_name.'/');
  489. $result = true;
  490. } else {
  491. $extraction_path = $cssToUpload.$style_name.'/';
  492. for ($i = 0; $i < $num_files; $i++) {
  493. $entry = $zip->getNameIndex($i);
  494. if (substr($entry, -1) == '/') {
  495. continue;
  496. }
  497. $pos_slash = strpos($entry, '/');
  498. $entry_without_first_dir = substr($entry, $pos_slash + 1);
  499. // If there is still a slash, we need to make sure the directories are created.
  500. if (strpos($entry_without_first_dir, '/') !== false) {
  501. if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
  502. // Create it.
  503. @mkdir($extraction_path.dirname($entry_without_first_dir), $mode = 0777, true);
  504. }
  505. }
  506. $fp = $zip->getStream($entry);
  507. $ofp = fopen($extraction_path.dirname($entry_without_first_dir).'/'.basename($entry), 'w');
  508. while (!feof($fp)) {
  509. fwrite($ofp, fread($fp, 8192));
  510. }
  511. fclose($fp);
  512. fclose($ofp);
  513. }
  514. $result = true;
  515. }
  516. }
  517. $zip->close();
  518. } else {
  519. Display::addFlash(Display::return_message(get_lang('ErrorReadingZip').$info['extension'], 'error', false));
  520. }
  521. } else {
  522. // Simply move the file.
  523. move_uploaded_file($picture['tmp_name'], $cssToUpload.$style_name.'/'.$picture['name']);
  524. $result = true;
  525. }
  526. if ($result) {
  527. $fs = new Filesystem();
  528. $fs->mirror(
  529. CSS_UPLOAD_PATH,
  530. api_get_path(SYS_PATH).'web/css/themes/',
  531. null,
  532. ['override' => true]
  533. );
  534. }
  535. return $result;
  536. }
  537. /**
  538. * Store plugin regions.
  539. */
  540. function storeRegions()
  541. {
  542. $plugin_obj = new AppPlugin();
  543. // Get a list of all current 'Plugins' settings
  544. $installed_plugins = $plugin_obj->get_installed_plugins();
  545. $shortlist_installed = array();
  546. if (!empty($installed_plugins)) {
  547. foreach ($installed_plugins as $plugin) {
  548. if (isset($plugin['subkey'])) {
  549. $shortlist_installed[] = $plugin['subkey'];
  550. }
  551. }
  552. }
  553. $shortlist_installed = array_flip(array_flip($shortlist_installed));
  554. $plugin_list = $plugin_obj->read_plugins_from_path();
  555. foreach ($plugin_list as $plugin) {
  556. if (isset($_POST['plugin_'.$plugin])) {
  557. $areas_to_installed = $_POST['plugin_'.$plugin];
  558. if (!empty($areas_to_installed)) {
  559. $plugin_obj->remove_all_regions($plugin);
  560. foreach ($areas_to_installed as $region) {
  561. if (!empty($region) && $region != '-1' ) {
  562. $plugin_obj->add_to_region($plugin, $region);
  563. }
  564. }
  565. }
  566. }
  567. }
  568. }
  569. /**
  570. * This function allows easy activating and inactivating of plugins
  571. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  572. */
  573. function storePlugins()
  574. {
  575. $appPlugin = new AppPlugin();
  576. // Get a list of all current 'Plugins' settings
  577. $plugin_list = $appPlugin->read_plugins_from_path();
  578. $installed_plugins = array();
  579. foreach ($plugin_list as $plugin) {
  580. if (isset($_POST['plugin_'.$plugin])) {
  581. $appPlugin->install($plugin);
  582. $installed_plugins[] = $plugin;
  583. }
  584. }
  585. if (!empty($installed_plugins)) {
  586. $remove_plugins = array_diff($plugin_list, $installed_plugins);
  587. } else {
  588. $remove_plugins = $plugin_list;
  589. }
  590. foreach ($remove_plugins as $plugin) {
  591. $appPlugin->uninstall($plugin);
  592. }
  593. }
  594. /**
  595. * This function allows the platform admin to choose which should be the default stylesheet
  596. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  597. */
  598. function storeStylesheets()
  599. {
  600. // Insert the stylesheet.
  601. if (isStyle($_POST['style'])) {
  602. api_set_setting(
  603. 'stylesheets',
  604. $_POST['style'],
  605. null,
  606. 'stylesheets',
  607. api_get_current_access_url_id()
  608. );
  609. }
  610. return true;
  611. }
  612. /**
  613. * This function checks if the given style is a recognize style that exists in the css directory as
  614. * a standalone directory.
  615. * @param string $style
  616. * @return bool True if this style is recognized, false otherwise
  617. */
  618. function isStyle($style)
  619. {
  620. $themeList = api_get_themes();
  621. return in_array($style, array_keys($themeList));
  622. }
  623. /**
  624. * Search options
  625. * TODO: support for multiple site. aka $_configuration['access_url'] == 1
  626. * @author Marco Villegas <marvil07@gmail.com>
  627. */
  628. function handleSearch()
  629. {
  630. global $SettingsStored, $_configuration;
  631. require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
  632. $search_enabled = api_get_setting('search_enabled');
  633. $form = new FormValidator('search-options', 'post', api_get_self().'?category=Search');
  634. $values = api_get_settings_options('search_enabled');
  635. $form->addElement('header', null, get_lang('SearchEnabledTitle'));
  636. $group = formGenerateElementsGroup($form, $values, 'search_enabled');
  637. //SearchEnabledComment
  638. $form->addGroup($group, 'search_enabled', array(get_lang('SearchEnabledTitle'), get_lang('SearchEnabledComment')), null, false);
  639. $search_enabled = api_get_setting('search_enabled');
  640. if ($form->validate()) {
  641. $formValues = $form->exportValues();
  642. setConfigurationSettingsInDatabase($formValues, $_configuration['access_url']);
  643. $search_enabled = $formValues['search_enabled'];
  644. Display::addFlash(Display::return_message($SettingsStored, 'confirm'));
  645. }
  646. $specific_fields = get_specific_field_list();
  647. if ($search_enabled == 'true') {
  648. $values = api_get_settings_options('search_show_unlinked_results');
  649. $group = formGenerateElementsGroup($form, $values, 'search_show_unlinked_results');
  650. $form->addGroup($group, 'search_show_unlinked_results', array(get_lang('SearchShowUnlinkedResultsTitle'),get_lang('SearchShowUnlinkedResultsComment')), null, false);
  651. $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
  652. $sf_values = array();
  653. foreach ($specific_fields as $sf) {
  654. $sf_values[$sf['code']] = $sf['name'];
  655. }
  656. $url = Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'), array('class'=>'sectioncomment'));
  657. if (empty($sf_values)) {
  658. $form->addElement('label', [get_lang('SearchPrefilterPrefix'), $url]);
  659. } else {
  660. $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url), $sf_values, '');
  661. $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
  662. }
  663. }
  664. $default_values['search_enabled'] = $search_enabled;
  665. $form->addButtonSave(get_lang('Save'));
  666. $form->setDefaults($default_values);
  667. echo '<div id="search-options-form">';
  668. $form->display();
  669. echo '</div>';
  670. if ($search_enabled == 'true') {
  671. $xapianPath = api_get_path(SYS_UPLOAD_PATH).'plugins/xapian/searchdb';
  672. /*
  673. @todo Test the Xapian connection
  674. if (extension_loaded('xapian')) {
  675. require_once 'xapian.php';
  676. try {
  677. $db = new XapianDatabase($xapianPath.'/');
  678. } catch (Exception $e) {
  679. var_dump($e->getMessage());
  680. }
  681. require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
  682. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  683. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  684. $indexable = new IndexableChunk();
  685. $indexable->addValue("content", 'Test');
  686. $di = new ChamiloIndexer();
  687. $di->connectDb(NULL, NULL, 'english');
  688. $di->addChunk($indexable);
  689. $did = $di->index();
  690. }
  691. */
  692. $xapianLoaded = Display::return_icon('bullet_green.png', get_lang('Ok'));
  693. $dir_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
  694. $dir_is_writable = Display::return_icon('bullet_green.png', get_lang('Ok'));
  695. $specific_fields_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
  696. //Testing specific fields
  697. if (empty($specific_fields)) {
  698. $specific_fields_exists = Display::return_icon('bullet_red.png', get_lang('AddSpecificSearchField'));
  699. }
  700. //Testing xapian extension
  701. if (!extension_loaded('xapian')) {
  702. $xapianLoaded = Display::return_icon('bullet_red.png', get_lang('Error'));
  703. }
  704. //Testing xapian searchdb path
  705. if (!is_dir($xapianPath)) {
  706. $dir_exists = Display::return_icon('bullet_red.png', get_lang('Error'));
  707. }
  708. //Testing xapian searchdb path is writable
  709. if (!is_writable($xapianPath)) {
  710. $dir_is_writable = Display::return_icon('bullet_red.png', get_lang('Error'));
  711. }
  712. $data = array();
  713. $data[] = array(get_lang('XapianModuleInstalled'), $xapianLoaded);
  714. $data[] = array(get_lang('DirectoryExists').' - '.$xapianPath, $dir_exists);
  715. $data[] = array(get_lang('IsWritable').' - '.$xapianPath, $dir_is_writable);
  716. $data[] = array(get_lang('SpecificSearchFieldsAvailable'), $specific_fields_exists);
  717. showSearchSettingsTable($data);
  718. showSearchToolsStatusTable();
  719. }
  720. }
  721. /**
  722. * Wrapper for the templates
  723. *
  724. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  725. * @author Julio Montoya.
  726. * @version August 2008
  727. * @since v1.8.6
  728. */
  729. function handleTemplates()
  730. {
  731. /* Drive-by fix to avoid undefined var warnings, without repeating
  732. * isset() combos all over the place. */
  733. $action = isset($_GET['action']) ? $_GET['action'] : "invalid";
  734. if ($action != 'add') {
  735. echo '<div class="actions" style="margin-left: 1px;">';
  736. echo '<a href="settings.php?category=Templates&action=add">'.
  737. Display::return_icon('new_template.png', get_lang('AddTemplate'),'',ICON_SIZE_MEDIUM).'</a>';
  738. echo '</div>';
  739. }
  740. if ($action == 'add' || ($action == 'edit' && is_numeric($_GET['id']))) {
  741. addEditTemplate();
  742. // Add event to the system log.
  743. $user_id = api_get_user_id();
  744. $category = $_GET['category'];
  745. Event::addEvent(
  746. LOG_CONFIGURATION_SETTINGS_CHANGE,
  747. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  748. $category,
  749. api_get_utc_datetime(),
  750. $user_id
  751. );
  752. } else {
  753. if ($action == 'delete' && is_numeric($_GET['id'])) {
  754. deleteTemplate($_GET['id']);
  755. // Add event to the system log
  756. $user_id = api_get_user_id();
  757. $category = $_GET['category'];
  758. Event::addEvent(
  759. LOG_CONFIGURATION_SETTINGS_CHANGE,
  760. LOG_CONFIGURATION_SETTINGS_CATEGORY,
  761. $category,
  762. api_get_utc_datetime(),
  763. $user_id
  764. );
  765. }
  766. displayTemplates();
  767. }
  768. }
  769. /**
  770. * Display a sortable table with all the templates that the platform administrator has defined.
  771. *
  772. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  773. * @version August 2008
  774. * @since v1.8.6
  775. */
  776. function displayTemplates()
  777. {
  778. $table = new SortableTable('templates', 'getNumberOfTemplates', 'getTemplateData', 1);
  779. $table->set_additional_parameters(array('category' => Security::remove_XSS($_GET['category'])));
  780. $table->set_header(0, get_lang('Image'), true, array('style' => 'width: 101px;'));
  781. $table->set_header(1, get_lang('Title'));
  782. $table->set_header(2, get_lang('Actions'), false, array('style' => 'width:50px;'));
  783. $table->set_column_filter(2, 'actionsFilter');
  784. $table->set_column_filter(0, 'searchImageFilter');
  785. $table->display();
  786. }
  787. /**
  788. * Gets the number of templates that are defined by the platform admin.
  789. *
  790. * @return integer
  791. *
  792. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  793. * @version August 2008
  794. * @since v1.8.6
  795. */
  796. function getNumberOfTemplates()
  797. {
  798. // Database table definition.
  799. $table_system_template = Database::get_main_table('system_template');
  800. // The sql statement.
  801. $sql = "SELECT COUNT(id) AS total FROM $table_system_template";
  802. $result = Database::query($sql);
  803. $row = Database::fetch_array($result);
  804. // Returning the number of templates.
  805. return $row['total'];
  806. }
  807. /**
  808. * Gets all the template data for the sortable table.
  809. *
  810. * @param integer $from the start of the limit statement
  811. * @param integer $number_of_items the number of elements that have to be retrieved from the database
  812. * @param integer $column the column that is
  813. * @param string $direction the sorting direction (ASC or DESC�
  814. * @return array
  815. *
  816. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  817. * @version August 2008
  818. * @since v1.8.6
  819. */
  820. function getTemplateData($from, $number_of_items, $column, $direction)
  821. {
  822. // Database table definition.
  823. $table_system_template = Database::get_main_table('system_template');
  824. // The sql statement.
  825. $sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
  826. $sql .= " ORDER BY col$column $direction ";
  827. $sql .= " LIMIT $from,$number_of_items";
  828. $result = Database::query($sql);
  829. $return = array();
  830. while ($row = Database::fetch_array($result)) {
  831. $row['1'] = get_lang($row['1']);
  832. $return[] = $row;
  833. }
  834. // Returning all the information for the sortable table.
  835. return $return;
  836. }
  837. /**
  838. * display the edit and delete icons in the sortable table
  839. *
  840. * @param integer $id the id of the template
  841. * @return string code for the link to edit and delete the template
  842. *
  843. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  844. * @version August 2008
  845. * @since v1.8.6
  846. */
  847. function actionsFilter($id) {
  848. $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>';
  849. $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>';
  850. return $return;
  851. }
  852. /**
  853. * Display the image of the template in the sortable table
  854. *
  855. * @param string $image the image
  856. * @return string code for the image
  857. *
  858. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  859. * @version August 2008
  860. * @since v1.8.6
  861. */
  862. function searchImageFilter($image)
  863. {
  864. if (!empty($image)) {
  865. return '<img src="'.api_get_path(WEB_APP_PATH).'home/default_platform_document/template_thumb/'.$image.'" alt="'.get_lang('TemplatePreview').'"/>';
  866. } else {
  867. return '<img src="'.api_get_path(WEB_APP_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>';
  868. }
  869. }
  870. /**
  871. * Add (or edit) a template. This function displays the form and also takes
  872. * care of uploading the image and storing the information in the database
  873. *
  874. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  875. * @version August 2008
  876. * @since v1.8.6
  877. */
  878. function addEditTemplate()
  879. {
  880. // Initialize the object.
  881. $id = isset($_GET['id']) ? '&id='.Security::remove_XSS($_GET['id']) : '';
  882. $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).$id);
  883. // Setting the form elements: the header.
  884. if ($_GET['action'] == 'add') {
  885. $title = get_lang('AddTemplate');
  886. } else {
  887. $title = get_lang('EditTemplate');
  888. }
  889. $form->addElement('header', '', $title);
  890. // Setting the form elements: the title of the template.
  891. $form->addText('title', get_lang('Title'), false);
  892. // Setting the form elements: the content of the template (wysiwyg editor).
  893. $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
  894. // Setting the form elements: the form to upload an image to be used with the template.
  895. $form->addElement('file', 'template_image', get_lang('Image'), '');
  896. // Setting the form elements: a little bit information about the template image.
  897. $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
  898. // Getting all the information of the template when editing a template.
  899. if ($_GET['action'] == 'edit') {
  900. // Database table definition.
  901. $table_system_template = Database::get_main_table('system_template');
  902. $sql = "SELECT * FROM $table_system_template WHERE id = ".intval($_GET['id'])."";
  903. $result = Database::query($sql);
  904. $row = Database::fetch_array($result);
  905. $defaults['template_id'] = intval($_GET['id']);
  906. $defaults['template_text'] = $row['content'];
  907. // Forcing get_lang().
  908. $defaults['title'] = get_lang($row['title']);
  909. // Adding an extra field: a hidden field with the id of the template we are editing.
  910. $form->addElement('hidden', 'template_id');
  911. // Adding an extra field: a preview of the image that is currently used.
  912. if (!empty($row['image'])) {
  913. $form->addElement('static', 'template_image_preview', '',
  914. '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/' . $row['image'] . '" alt="' . get_lang('TemplatePreview') . '"/>');
  915. } else {
  916. $form->addElement('static', 'template_image_preview', '',
  917. '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/noimage.gif" alt="' . get_lang('NoTemplatePreview') . '"/>');
  918. }
  919. // Setting the information of the template that we are editing.
  920. $form->setDefaults($defaults);
  921. }
  922. // Setting the form elements: the submit button.
  923. $form->addButtonSave(get_lang('Ok'), 'submit');
  924. // Setting the rules: the required fields.
  925. $form->addRule('template_image', get_lang('ThisFieldIsRequired'), 'required');
  926. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  927. $form->addRule('template_text', get_lang('ThisFieldIsRequired'), 'required');
  928. // if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
  929. if ($form->validate()) {
  930. $check = Security::check_token('post');
  931. if ($check) {
  932. // Exporting the values.
  933. $values = $form->exportValues();
  934. // Upload the file.
  935. if (!empty($_FILES['template_image']['name'])) {
  936. $upload_ok = process_uploaded_file($_FILES['template_image']);
  937. if ($upload_ok) {
  938. // Try to add an extension to the file if it hasn't one.
  939. $new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
  940. // The upload directory.
  941. $upload_dir = api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/';
  942. // Create the directory if it does not exist.
  943. if (!is_dir($upload_dir)) {
  944. mkdir($upload_dir, api_get_permissions_for_new_directories());
  945. }
  946. // Resize the preview image to max default and upload.
  947. $temp = new Image($_FILES['template_image']['tmp_name']);
  948. $picture_info = $temp->get_image_info();
  949. $max_width_for_picture = 100;
  950. if ($picture_info['width'] > $max_width_for_picture) {
  951. $temp->resize($max_width_for_picture);
  952. }
  953. $temp->send_image($upload_dir.$new_file_name);
  954. }
  955. }
  956. // Store the information in the database (as insert or as update).
  957. $table_system_template = Database::get_main_table('system_template');
  958. if ($_GET['action'] == 'add') {
  959. $content_template = Security::remove_XSS($values['template_text'], COURSEMANAGERLOWSECURITY);
  960. $params = [
  961. 'title' => $values['title'],
  962. 'content' => $content_template,
  963. 'image' => $new_file_name
  964. ];
  965. Database::insert($table_system_template, $params);
  966. // Display a feedback message.
  967. Display::addFlash(Display::return_message(get_lang('TemplateAdded'), 'confirm'));
  968. echo '<a href="settings.php?category=Templates&action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'',ICON_SIZE_MEDIUM).'</a>';
  969. } else {
  970. $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
  971. $sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."', content = '".$content_template."'";
  972. if (!empty($new_file_name)) {
  973. $sql .= ", image = '".Database::escape_string($new_file_name)."'";
  974. }
  975. $sql .= " WHERE id = ".intval($_GET['id'])."";
  976. Database::query($sql);
  977. // Display a feedback message.
  978. Display::addFlash(Display::return_message(get_lang('TemplateEdited'), 'confirm'));
  979. }
  980. }
  981. Security::clear_token();
  982. displayTemplates();
  983. } else {
  984. $token = Security::get_token();
  985. $form->addElement('hidden', 'sec_token');
  986. $form->setConstants(array('sec_token' => $token));
  987. // Display the form.
  988. $form->display();
  989. }
  990. }
  991. /**
  992. * Delete a template
  993. *
  994. * @param integer $id the id of the template that has to be deleted
  995. *
  996. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
  997. * @version August 2008
  998. * @since v1.8.6
  999. */
  1000. function deleteTemplate($id)
  1001. {
  1002. // First we remove the image.
  1003. $table_system_template = Database::get_main_table('system_template');
  1004. $sql = "SELECT * FROM $table_system_template WHERE id = ".intval($id)."";
  1005. $result = Database::query($sql);
  1006. $row = Database::fetch_array($result);
  1007. if (!empty($row['image'])) {
  1008. @unlink(api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
  1009. }
  1010. // Now we remove it from the database.
  1011. $sql = "DELETE FROM $table_system_template WHERE id = ".intval($id)."";
  1012. Database::query($sql);
  1013. // Display a feedback message.
  1014. Display::addFlash(Display::return_message(get_lang('TemplateDeleted'), 'confirm'));
  1015. }
  1016. /**
  1017. * Returns the list of timezone identifiers used to populate the select
  1018. * This function is called through a call_user_func() in the generate_settings_form function.
  1019. * @return array List of timezone identifiers
  1020. *
  1021. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  1022. * @since Chamilo 1.8.7
  1023. */
  1024. function select_timezone_value()
  1025. {
  1026. return api_get_timezones();
  1027. }
  1028. /**
  1029. * Returns an array containing the list of options used to populate the gradebook_number_decimals variable
  1030. * This function is called through a call_user_func() in the generate_settings_form function.
  1031. * @return array List of gradebook_number_decimals options
  1032. *
  1033. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  1034. */
  1035. function select_gradebook_number_decimals() {
  1036. return array('0', '1', '2');
  1037. }
  1038. /**
  1039. * Get the options for a select element to select gradebook default grade model
  1040. * @return array
  1041. */
  1042. function select_gradebook_default_grade_model_id()
  1043. {
  1044. $grade_model = new GradeModel();
  1045. $models = $grade_model->get_all();
  1046. $options = array();
  1047. $options[-1] = get_lang('None');
  1048. if (!empty($models)) {
  1049. foreach ($models as $model) {
  1050. $options[$model['id']] = $model['name'];
  1051. }
  1052. }
  1053. return $options;
  1054. }
  1055. /**
  1056. * @param array $settings
  1057. * @param array $settings_by_access_list
  1058. *
  1059. * @return FormValidator
  1060. *
  1061. * @throws \Doctrine\ORM\ORMException
  1062. * @throws \Doctrine\ORM\OptimisticLockException
  1063. * @throws \Doctrine\ORM\TransactionRequiredException
  1064. */
  1065. function generateSettingsForm($settings, $settings_by_access_list)
  1066. {
  1067. global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
  1068. $em = Database::getManager();
  1069. $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1070. $form = new FormValidator('settings', 'post', 'settings.php?category='.Security::remove_XSS($_GET['category']));
  1071. $form->addElement(
  1072. 'hidden',
  1073. 'search_field',
  1074. (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null)
  1075. );
  1076. $url_id = api_get_current_access_url_id();
  1077. /*
  1078. if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) {
  1079. $group = array();
  1080. $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
  1081. $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
  1082. $form->addGroup($group, 'buttons_in_action_right');
  1083. }*/
  1084. $default_values = array();
  1085. $url_info = api_get_access_url($url_id);
  1086. $i = 0;
  1087. $addedSettings = [];
  1088. foreach ($settings as $row) {
  1089. if (in_array($row['variable'], array_keys($settings_to_avoid))) {
  1090. continue;
  1091. }
  1092. if (in_array($row['variable'], $addedSettings)) {
  1093. continue;
  1094. }
  1095. $addedSettings[] = $row['variable'];
  1096. if (!empty($_configuration['multiple_access_urls'])) {
  1097. if (api_is_global_platform_admin()) {
  1098. if ($row['access_url_locked'] == 0) {
  1099. if ($url_id == 1) {
  1100. if ($row['access_url_changeable'] == '1') {
  1101. $form->addElement(
  1102. 'html',
  1103. '<div class="pull-right"><a class="share_this_setting" data_status = "0" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
  1104. Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting') , null, ICON_SIZE_MEDIUM).'</a></div>'
  1105. );
  1106. } else {
  1107. $form->addElement(
  1108. 'html',
  1109. '<div class="pull-right"><a class="share_this_setting" data_status = "1" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
  1110. Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting'), null, ICON_SIZE_MEDIUM ).'</a></div>'
  1111. );
  1112. }
  1113. } else {
  1114. if ($row['access_url_changeable'] == '1') {
  1115. $form->addElement(
  1116. 'html',
  1117. '<div class="pull-right">'.
  1118. Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting'), null, ICON_SIZE_MEDIUM ).'</div>'
  1119. );
  1120. } else {
  1121. $form->addElement(
  1122. 'html',
  1123. '<div class="pull-right">'.
  1124. Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting'), null, ICON_SIZE_MEDIUM ).'</div>'
  1125. );
  1126. }
  1127. }
  1128. }
  1129. }
  1130. }
  1131. $hideme = array();
  1132. $hide_element = false;
  1133. if ($_configuration['access_url'] != 1) {
  1134. if ($row['access_url_changeable'] == 0) {
  1135. // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
  1136. $hide_element = true;
  1137. $hideme = array('disabled');
  1138. } elseif ($url_info['active'] == 1) {
  1139. // We show the elements.
  1140. if (empty($row['variable'])) {
  1141. $row['variable'] = 0;
  1142. }
  1143. if (empty($row['subkey'])) {
  1144. $row['subkey'] = 0;
  1145. }
  1146. if (empty($row['category'])) {
  1147. $row['category'] = 0;
  1148. }
  1149. if (isset($settings_by_access_list[$row['variable']]) &&
  1150. is_array($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']])) {
  1151. // We are sure that the other site have a selected value.
  1152. if ($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'] != '') {
  1153. $row['selected_value'] = $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'];
  1154. }
  1155. }
  1156. // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
  1157. }
  1158. }
  1159. switch ($row['type']) {
  1160. case 'textfield':
  1161. if (in_array($row['variable'], $convert_byte_to_mega_list)) {
  1162. $form->addElement(
  1163. 'text',
  1164. $row['variable'],
  1165. array(
  1166. get_lang($row['title']),
  1167. get_lang($row['comment']),
  1168. get_lang('MB')
  1169. ),
  1170. array('maxlength' => '8')
  1171. );
  1172. $form->applyFilter($row['variable'], 'html_filter');
  1173. $default_values[$row['variable']] = round($row['selected_value']/1024/1024, 1);
  1174. } elseif ($row['variable'] == 'account_valid_duration') {
  1175. $form->addElement(
  1176. 'text',
  1177. $row['variable'],
  1178. array(
  1179. get_lang($row['title']),
  1180. get_lang($row['comment']),
  1181. ),
  1182. array('maxlength' => '5')
  1183. );
  1184. $form->applyFilter($row['variable'], 'html_filter');
  1185. $default_values[$row['variable']] = $row['selected_value'];
  1186. // For platform character set selection: Conversion of the textfield to a select box with valid values.
  1187. } elseif ($row['variable'] == 'platform_charset') {
  1188. continue;
  1189. } else {
  1190. $hideme['class'] = 'col-md-4';
  1191. $form->addElement(
  1192. 'text',
  1193. $row['variable'],
  1194. array(
  1195. get_lang($row['title']),
  1196. get_lang($row['comment'])
  1197. ),
  1198. $hideme
  1199. );
  1200. $form->applyFilter($row['variable'],'html_filter');
  1201. $default_values[$row['variable']] = $row['selected_value'];
  1202. }
  1203. break;
  1204. case 'textarea':
  1205. if ($row['variable'] == 'header_extra_content') {
  1206. $file = api_get_home_path().'header_extra_content.txt';
  1207. $value = '';
  1208. if (file_exists($file)) {
  1209. $value = file_get_contents($file);
  1210. }
  1211. $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
  1212. $default_values[$row['variable']] = $value;
  1213. } elseif ($row['variable'] == 'footer_extra_content') {
  1214. $file = api_get_home_path().'footer_extra_content.txt';
  1215. $value = '';
  1216. if (file_exists($file)) {
  1217. $value = file_get_contents($file);
  1218. }
  1219. $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
  1220. $default_values[$row['variable']] = $value;
  1221. } else {
  1222. $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
  1223. $default_values[$row['variable']] = $row['selected_value'];
  1224. }
  1225. break;
  1226. case 'radio':
  1227. $values = api_get_settings_options($row['variable']);
  1228. $group = array ();
  1229. if (is_array($values)) {
  1230. foreach ($values as $key => $value) {
  1231. $element = &$form->createElement(
  1232. 'radio',
  1233. $row['variable'],
  1234. '',
  1235. get_lang($value['display_text']),
  1236. $value['value']
  1237. );
  1238. if ($hide_element) {
  1239. $element->freeze();
  1240. }
  1241. $group[] = $element;
  1242. }
  1243. }
  1244. $form->addGroup(
  1245. $group,
  1246. $row['variable'],
  1247. array(get_lang($row['title']), get_lang($row['comment'])),
  1248. null,
  1249. false
  1250. );
  1251. $default_values[$row['variable']] = $row['selected_value'];
  1252. break;
  1253. case 'checkbox':
  1254. // 1. We collect all the options of this variable.
  1255. $sql = "SELECT * FROM $table_settings_current
  1256. WHERE variable='".$row['variable']."' AND access_url = 1";
  1257. $result = Database::query($sql);
  1258. $group = array ();
  1259. while ($rowkeys = Database::fetch_array($result)) {
  1260. // Profile tab option should be hidden when the social tool is enabled.
  1261. if (api_get_setting('allow_social_tool') == 'true') {
  1262. if ($rowkeys['variable'] === 'show_tabs' && $rowkeys['subkey'] === 'my_profile') {
  1263. continue;
  1264. }
  1265. }
  1266. // Hiding the gradebook option.
  1267. if ($rowkeys['variable'] === 'show_tabs' && $rowkeys['subkey'] === 'my_gradebook') {
  1268. continue;
  1269. }
  1270. $element = &$form->createElement(
  1271. 'checkbox',
  1272. $rowkeys['subkey'],
  1273. '',
  1274. get_lang($rowkeys['subkeytext'])
  1275. );
  1276. if ($row['access_url_changeable'] == 1) {
  1277. // 2. We look into the DB if there is a setting for a specific access_url.
  1278. $access_url = $_configuration['access_url'];
  1279. if (empty($access_url)) {
  1280. $access_url = 1;
  1281. }
  1282. $sql = "SELECT selected_value FROM $table_settings_current
  1283. WHERE
  1284. variable='".$rowkeys['variable']."' AND
  1285. subkey='".$rowkeys['subkey']."' AND
  1286. subkeytext='".$rowkeys['subkeytext']."' AND
  1287. access_url = $access_url";
  1288. $result_access = Database::query($sql);
  1289. $row_access = Database::fetch_array($result_access);
  1290. if ($row_access['selected_value'] === 'true' && !$form->isSubmitted()) {
  1291. $element->setChecked(true);
  1292. }
  1293. } else {
  1294. if ($rowkeys['selected_value'] === 'true' && !$form->isSubmitted()) {
  1295. $element->setChecked(true);
  1296. }
  1297. }
  1298. if ($hide_element) {
  1299. $element->freeze();
  1300. }
  1301. $group[] = $element;
  1302. }
  1303. $form->addGroup(
  1304. $group,
  1305. $row['variable'],
  1306. array(get_lang($row['title']), get_lang($row['comment'])),
  1307. null
  1308. );
  1309. break;
  1310. case 'link':
  1311. $form->addElement('static', null, array(get_lang($row['title']), get_lang($row['comment'])),
  1312. get_lang('CurrentValue') . ' : ' . $row['selected_value'], $hideme);
  1313. break;
  1314. case 'select':
  1315. /*
  1316. * 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.
  1317. * The functions being called must be added to the file settings.lib.php.
  1318. */
  1319. $form->addElement(
  1320. 'select',
  1321. $row['variable'],
  1322. array(get_lang($row['title']), get_lang($row['comment'])),
  1323. call_user_func('select_'.$row['variable']),
  1324. $hideme
  1325. );
  1326. $default_values[$row['variable']] = $row['selected_value'];
  1327. break;
  1328. case 'custom':
  1329. break;
  1330. case 'select_course':
  1331. $courseSelectOptions = [];
  1332. if (!empty($row['selected_value'])) {
  1333. $course = $em->find('ChamiloCoreBundle:Course', $row['selected_value']);
  1334. $courseSelectOptions[$course->getId()] = $course->getTitle();
  1335. }
  1336. $form->addElement(
  1337. 'select_ajax',
  1338. $row['variable'],
  1339. [get_lang($row['title']), get_lang($row['comment'])],
  1340. $courseSelectOptions,
  1341. ['url' => api_get_path(WEB_AJAX_PATH) . 'course.ajax.php?a=search_course']
  1342. );
  1343. $default_values[$row['variable']] = $row['selected_value'];
  1344. break;
  1345. }
  1346. switch ($row['variable']) {
  1347. case 'pdf_export_watermark_enable':
  1348. $url = PDF::get_watermark(null);
  1349. if ($url != false) {
  1350. $delete_url = '<a href="?delete_watermark">'.get_lang('DelImage').' '.Display::return_icon('delete.png',get_lang('DelImage')).'</a>';
  1351. $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>');
  1352. }
  1353. $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark'));
  1354. $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
  1355. $form->addRule('pdf_export_watermark_path', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
  1356. break;
  1357. case 'timezone_value':
  1358. $timezone = $row['selected_value'];
  1359. if (empty($timezone)) {
  1360. $timezone = api_get_timezone();
  1361. }
  1362. $form->addLabel('', sprintf(get_lang('LocalTimeUsingPortalTimezoneXIsY'), $timezone, api_get_local_time()));
  1363. break;
  1364. }
  1365. } // end for
  1366. if (!empty($settings)) {
  1367. $form->setDefaults($default_values);
  1368. }
  1369. $form->addHtml('<div class="bottom_actions">');
  1370. $form->addButtonSave(get_lang('SaveSettings'));
  1371. $form->addHtml('</div>');
  1372. return $form;
  1373. }
  1374. /**
  1375. * Searches a platform setting in all categories except from the Plugins category
  1376. * @param string $search
  1377. * @return array
  1378. */
  1379. function searchSetting($search)
  1380. {
  1381. if (empty($search)) {
  1382. return array();
  1383. }
  1384. $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1385. $sql = "SELECT * FROM $table_settings_current
  1386. WHERE category <> 'Plugins' ORDER BY id ASC ";
  1387. $result = Database::store_result(Database::query($sql), 'ASSOC');
  1388. $settings = array();
  1389. $search = api_strtolower($search);
  1390. if (!empty($result)) {
  1391. foreach ($result as $setting) {
  1392. $found = false;
  1393. $title = api_strtolower(get_lang($setting['title']));
  1394. // try the title
  1395. if (strpos($title, $search) === false) {
  1396. $comment = api_strtolower(get_lang($setting['comment']));
  1397. //Try the comment
  1398. if (strpos($comment, $search) === false) {
  1399. //Try the variable name
  1400. if (strpos($setting['variable'], $search) === false) {
  1401. continue;
  1402. } else {
  1403. $found = true;
  1404. }
  1405. } else {
  1406. $found = true;
  1407. }
  1408. } else {
  1409. $found = true;
  1410. }
  1411. if ($found) {
  1412. $settings[] = $setting;
  1413. }
  1414. }
  1415. }
  1416. return $settings;
  1417. }
  1418. /**
  1419. * Helper function to generates a form elements group
  1420. * @param object $form The form where the elements group has to be added
  1421. * @param array $values Values to browse through
  1422. * @return array
  1423. */
  1424. function formGenerateElementsGroup($form, $values = array(), $elementName)
  1425. {
  1426. $group = array();
  1427. if (is_array($values)) {
  1428. foreach ($values as $key => $value) {
  1429. $element = &$form->createElement('radio', $elementName, '', get_lang($value['display_text']), $value['value']);
  1430. $group[] = $element;
  1431. }
  1432. }
  1433. return $group;
  1434. }
  1435. /**
  1436. * Helper function with allowed file types for CSS
  1437. * @return array Array of file types (no indexes)
  1438. */
  1439. function getAllowedFileTypes()
  1440. {
  1441. $allowedFiles = array(
  1442. 'css',
  1443. 'zip',
  1444. 'jpeg',
  1445. 'jpg',
  1446. 'png',
  1447. 'gif',
  1448. 'ico',
  1449. 'psd',
  1450. 'xcf',
  1451. 'svg',
  1452. 'webp',
  1453. 'woff',
  1454. 'woff2'
  1455. );
  1456. return $allowedFiles;
  1457. }
  1458. /**
  1459. * Helper function to set settings in the database
  1460. * @param array $parameters List of values
  1461. * @param int $accessUrl The current access URL
  1462. * @return void
  1463. */
  1464. function setConfigurationSettingsInDatabase($parameters, $accessUrl)
  1465. {
  1466. api_set_settings_category('Search', 'false', $accessUrl);
  1467. // Save the settings.
  1468. foreach ($parameters as $key => $value) {
  1469. api_set_setting($key, $value, null, null);
  1470. }
  1471. }
  1472. /**
  1473. * Helper function to show the status of the search settings table
  1474. * @param array $data Data to show
  1475. * @return void
  1476. */
  1477. function showSearchSettingsTable($data)
  1478. {
  1479. echo Display::tag('h3', get_lang('Settings'));
  1480. $table = new SortableTableFromArray($data);
  1481. $table->set_header(0, get_lang('Setting'), false);
  1482. $table->set_header(1, get_lang('Status'), false);
  1483. echo $table->display();
  1484. }
  1485. /**
  1486. * Helper function to show status table for each command line tool installed
  1487. * @return void
  1488. */
  1489. function showSearchToolsStatusTable()
  1490. {
  1491. //@todo windows support
  1492. if (api_is_windows_os() == false) {
  1493. $list_of_programs = array('pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv');
  1494. foreach($list_of_programs as $program) {
  1495. $output = [];
  1496. $ret_val = null;
  1497. exec("which $program", $output, $ret_val);
  1498. if (!$output) {
  1499. $output[] = '';
  1500. }
  1501. $icon = Display::return_icon('bullet_red.png', get_lang('NotInstalled'));
  1502. if (!empty($output[0])) {
  1503. $icon = Display::return_icon('bullet_green.png', get_lang('Installed'));
  1504. }
  1505. $data2[]= array($program, $output[0], $icon);
  1506. }
  1507. echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles'));
  1508. $table = new SortableTableFromArray($data2);
  1509. $table->set_header(0, get_lang('Program'), false);
  1510. $table->set_header(1, get_lang('Path'), false);
  1511. $table->set_header(2, get_lang('Status'), false);
  1512. echo $table->display();
  1513. } else {
  1514. Display::display_warning_message(
  1515. get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool')
  1516. );
  1517. }
  1518. }
  1519. /**
  1520. * Helper function to generate and show CSS Zip download message
  1521. * @param string $style Style path
  1522. * @return void
  1523. */
  1524. function generateCSSDownloadLink($style)
  1525. {
  1526. $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
  1527. $themeDir = Template::getThemeDir($style);
  1528. $dir = api_get_path(SYS_CSS_PATH).$themeDir;
  1529. $check = Security::check_abs_path(
  1530. $dir,
  1531. api_get_path(SYS_CSS_PATH).'themes'
  1532. );
  1533. if (is_dir($dir) && $check) {
  1534. $zip = new PclZip($arch);
  1535. // Remove path prefix except the style name and put file on disk
  1536. $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir,0,-strlen($style)));
  1537. $url = api_get_path(WEB_CODE_PATH) . 'course_info/download.php?archive_path=&archive=' . str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch);
  1538. //@TODO: use more generic script to download.
  1539. $str = '<a class="btn btn-primary btn-large" href="' .$url. '">'.get_lang('ClickHereToDownloadTheFile').'</a>';
  1540. Display::addFlash(Display::return_message($str, 'normal', false));
  1541. } else {
  1542. Display::addFlash(Display::return_message(get_lang('FileNotFound'), 'warning'));
  1543. }
  1544. }
  1545. /**
  1546. * Helper function to tell if the style is changeable in the current URL
  1547. * @return bool $changeable Whether the style can be changed in this URL or not
  1548. */
  1549. function isStyleChangeable()
  1550. {
  1551. $changeable = false;
  1552. $urlId = api_get_current_access_url_id();
  1553. if ($urlId) {
  1554. $style_info = api_get_settings('stylesheets', '', 1, 0);
  1555. $url_info = api_get_access_url($urlId);
  1556. if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
  1557. $changeable = true;
  1558. }
  1559. } else {
  1560. $changeable = true;
  1561. }
  1562. return $changeable;
  1563. }