settings.lib.php 65 KB

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