install.lib.php 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Chamilo LMS
  5. * This file contains functions used by the install and upgrade scripts.
  6. *
  7. * Ideas for future additions:
  8. * - a function get_old_version_settings to retrieve the config file settings
  9. * of older versions before upgrading.
  10. */
  11. use Doctrine\ORM\EntityManager;
  12. use Chamilo\CoreBundle\Entity\ExtraField;
  13. use Chamilo\CoreBundle\Entity\ExtraFieldOptions;
  14. use Chamilo\CoreBundle\Entity\ExtraFieldValues;
  15. /* CONSTANTS */
  16. define('SYSTEM_CONFIG_FILENAME', 'configuration.dist.php');
  17. /**
  18. * This function detects whether the system has been already installed.
  19. * It should be used for prevention from second running the installation
  20. * script and as a result - destroying a production system.
  21. * @return bool The detected result;
  22. * @author Ivan Tcholakov, 2010;
  23. */
  24. function isAlreadyInstalledSystem()
  25. {
  26. global $new_version, $_configuration;
  27. if (empty($new_version)) {
  28. return true; // Must be initialized.
  29. }
  30. $current_config_file = api_get_path(CONFIGURATION_PATH).'configuration.php';
  31. if (!file_exists($current_config_file)) {
  32. return false; // Configuration file does not exist, install the system.
  33. }
  34. require $current_config_file;
  35. $current_version = null;
  36. if (isset($_configuration['system_version'])) {
  37. $current_version = trim($_configuration['system_version']);
  38. }
  39. // If the current version is old, upgrading is assumed, the installer goes ahead.
  40. return empty($current_version) ? false : version_compare($current_version, $new_version, '>=');
  41. }
  42. /**
  43. * This function checks if a php extension exists or not and returns an HTML status string.
  44. *
  45. * @param string $extensionName Name of the PHP extension to be checked
  46. * @param string $returnSuccess Text to show when extension is available (defaults to 'Yes')
  47. * @param string $returnFailure Text to show when extension is available (defaults to 'No')
  48. * @param boolean $optional Whether this extension is optional (then show unavailable text in orange rather than red)
  49. * @param string $enabledTerm If this string is not null, then use to check if the corresponding parameter is = 1. If not, mention it's present but not enabled. For example, for opcache, this should be 'opcache.enable'
  50. * @return string HTML string reporting the status of this extension. Language-aware.
  51. * @author Christophe Gesch??
  52. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  53. * @author Yannick Warnier <yannick.warnier@dokeos.com>
  54. */
  55. function checkExtension($extensionName, $returnSuccess = 'Yes', $returnFailure = 'No', $optional = false, $enabledTerm = '')
  56. {
  57. if (extension_loaded($extensionName)) {
  58. if (!empty($enabledTerm)) {
  59. $isEnabled = ini_get($enabledTerm);
  60. if ($isEnabled == '1') {
  61. return Display::label($returnSuccess, 'success');
  62. } else {
  63. if ($optional) {
  64. return Display::label(get_lang('ExtensionInstalledButNotEnabled'), 'warning');
  65. } else {
  66. return Display::label(get_lang('ExtensionInstalledButNotEnabled'), 'important');
  67. }
  68. }
  69. } else {
  70. return Display::label($returnSuccess, 'success');
  71. }
  72. } else {
  73. if ($optional) {
  74. return Display::label($returnFailure, 'warning');
  75. } else {
  76. return Display::label($returnFailure, 'important');
  77. }
  78. }
  79. }
  80. /**
  81. * This function checks whether a php setting matches the recommended value
  82. * @param string $phpSetting A PHP setting to check
  83. * @param string $recommendedValue A recommended value to show on screen
  84. * @param mixed $returnSuccess What to show on success
  85. * @param mixed $returnFailure What to show on failure
  86. * @return string A label to show
  87. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  88. */
  89. function checkPhpSetting($phpSetting, $recommendedValue, $returnSuccess = false, $returnFailure = false)
  90. {
  91. $currentPhpValue = getPhpSetting($phpSetting);
  92. if ($currentPhpValue == $recommendedValue) {
  93. return Display::label($currentPhpValue.' '.$returnSuccess, 'success');
  94. } else {
  95. return Display::label($currentPhpValue.' '.$returnSuccess, 'important');
  96. }
  97. }
  98. /**
  99. * This function return the value of a php.ini setting if not "" or if exists,
  100. * otherwise return false
  101. * @param string $phpSetting The name of a PHP setting
  102. * @return mixed The value of the setting, or false if not found
  103. */
  104. function checkPhpSettingExists($phpSetting)
  105. {
  106. if (ini_get($phpSetting) != "") {
  107. return ini_get($phpSetting);
  108. }
  109. return false;
  110. }
  111. /**
  112. * Returns a textual value ('ON' or 'OFF') based on a requester 2-state ini- configuration setting.
  113. *
  114. * @param string $val a php ini value
  115. * @return boolean: ON or OFF
  116. * @author Joomla <http://www.joomla.org>
  117. */
  118. function getPhpSetting($val)
  119. {
  120. return ini_get($val) == '1' ? 'ON' : 'OFF';
  121. }
  122. /**
  123. * This function returns a string "true" or "false" according to the passed parameter.
  124. *
  125. * @param integer $var The variable to present as text
  126. * @return string the string "true" or "false"
  127. * @author Christophe Gesch??
  128. */
  129. function trueFalse($var)
  130. {
  131. return $var ? 'true' : 'false';
  132. }
  133. /**
  134. * Removes memory and time limits as much as possible.
  135. */
  136. function remove_memory_and_time_limits()
  137. {
  138. if (function_exists('ini_set')) {
  139. ini_set('memory_limit', -1);
  140. ini_set('max_execution_time', 0);
  141. error_log('Update-db script: memory_limit set to -1', 0);
  142. error_log('Update-db script: max_execution_time 0', 0);
  143. } else {
  144. error_log('Update-db script: could not change memory and time limits', 0);
  145. }
  146. }
  147. /**
  148. * Detects browser's language.
  149. * @return string Returns a language identificator, i.e. 'english', 'spanish', ...
  150. * @author Ivan Tcholakov, 2010
  151. */
  152. function detect_browser_language()
  153. {
  154. static $language_index = array(
  155. 'ar' => 'arabic',
  156. 'ast' => 'asturian',
  157. 'bg' => 'bulgarian',
  158. 'bs' => 'bosnian',
  159. 'ca' => 'catalan',
  160. 'zh' => 'simpl_chinese',
  161. 'zh-tw' => 'trad_chinese',
  162. 'cs' => 'czech',
  163. 'da' => 'danish',
  164. 'prs' => 'dari',
  165. 'de' => 'german',
  166. 'el' => 'greek',
  167. 'en' => 'english',
  168. 'es' => 'spanish',
  169. 'eo' => 'esperanto',
  170. 'eu' => 'basque',
  171. 'fa' => 'persian',
  172. 'fr' => 'french',
  173. 'fur' => 'friulian',
  174. 'gl' => 'galician',
  175. 'ka' => 'georgian',
  176. 'hr' => 'croatian',
  177. 'he' => 'hebrew',
  178. 'hi' => 'hindi',
  179. 'id' => 'indonesian',
  180. 'it' => 'italian',
  181. 'ko' => 'korean',
  182. 'lv' => 'latvian',
  183. 'lt' => 'lithuanian',
  184. 'mk' => 'macedonian',
  185. 'hu' => 'hungarian',
  186. 'ms' => 'malay',
  187. 'nl' => 'dutch',
  188. 'ja' => 'japanese',
  189. 'no' => 'norwegian',
  190. 'oc' => 'occitan',
  191. 'ps' => 'pashto',
  192. 'pl' => 'polish',
  193. 'pt' => 'portuguese',
  194. 'pt-br' => 'brazilian',
  195. 'ro' => 'romanian',
  196. 'qu' => 'quechua_cusco',
  197. 'ru' => 'russian',
  198. 'sk' => 'slovak',
  199. 'sl' => 'slovenian',
  200. 'sr' => 'serbian',
  201. 'fi' => 'finnish',
  202. 'sv' => 'swedish',
  203. 'th' => 'thai',
  204. 'tr' => 'turkish',
  205. 'uk' => 'ukrainian',
  206. 'vi' => 'vietnamese',
  207. 'sw' => 'swahili',
  208. 'yo' => 'yoruba'
  209. );
  210. $system_available_languages = & get_language_folder_list();
  211. $accept_languages = strtolower(str_replace('_', '-', $_SERVER['HTTP_ACCEPT_LANGUAGE']));
  212. foreach ($language_index as $code => $language) {
  213. if (strpos($accept_languages, $code) === 0) {
  214. if (!empty($system_available_languages[$language])) {
  215. return $language;
  216. }
  217. }
  218. }
  219. $user_agent = strtolower(str_replace('_', '-', $_SERVER['HTTP_USER_AGENT']));
  220. foreach ($language_index as $code => $language) {
  221. if (@preg_match("/[\[\( ]{$code}[;,_\-\)]/", $user_agent)) {
  222. if (!empty($system_available_languages[$language])) {
  223. return $language;
  224. }
  225. }
  226. }
  227. return 'english';
  228. }
  229. /* FILESYSTEM RELATED FUNCTIONS */
  230. /**
  231. * This function checks if the given folder is writable
  232. * @param string $folder Full path to a folder
  233. * @param bool $suggestion Whether to show a suggestion or not
  234. * @return string
  235. */
  236. function check_writable($folder, $suggestion = false)
  237. {
  238. if (is_writable($folder)) {
  239. return Display::label(get_lang('Writable'), 'success');
  240. } else {
  241. if ($suggestion) {
  242. return Display::label(get_lang('NotWritable'), 'info');
  243. } else {
  244. return Display::label(get_lang('NotWritable'), 'important');
  245. }
  246. }
  247. }
  248. /**
  249. * This function checks if the given folder is readable
  250. * @param string $folder Full path to a folder
  251. * @param bool $suggestion Whether to show a suggestion or not
  252. *
  253. * @return string
  254. */
  255. function checkReadable($folder, $suggestion = false)
  256. {
  257. if (is_readable($folder)) {
  258. return Display::label(get_lang('Readable'), 'success');
  259. } else {
  260. if ($suggestion) {
  261. return Display::label(get_lang('NotReadable'), 'info');
  262. } else {
  263. return Display::label(get_lang('NotReadable'), 'important');
  264. }
  265. }
  266. }
  267. /**
  268. * This function is similar to the core file() function, except that it
  269. * works with line endings in Windows (which is not the case of file())
  270. * @param string $filename
  271. *
  272. * @return array The lines of the file returned as an array
  273. */
  274. function file_to_array($filename)
  275. {
  276. if (!is_readable($filename) || is_dir($filename)) {
  277. return array();
  278. }
  279. $fp = fopen($filename, 'rb');
  280. $buffer = fread($fp, filesize($filename));
  281. fclose($fp);
  282. return explode('<br />', nl2br($buffer));
  283. }
  284. /**
  285. * We assume this function is called from install scripts that reside inside the install folder.
  286. */
  287. function set_file_folder_permissions()
  288. {
  289. @chmod('.', 0755); //set permissions on install dir
  290. @chmod('..', 0755); //set permissions on parent dir of install dir
  291. }
  292. /**
  293. * Write the main system config file
  294. * @param string $path Path to the config file
  295. */
  296. function write_system_config_file($path)
  297. {
  298. global $dbHostForm;
  299. global $dbPortForm;
  300. global $dbUsernameForm;
  301. global $dbPassForm;
  302. global $dbNameForm;
  303. global $urlForm;
  304. global $pathForm;
  305. global $urlAppendPath;
  306. global $languageForm;
  307. global $encryptPassForm;
  308. global $session_lifetime;
  309. global $new_version;
  310. global $new_version_stable;
  311. $root_sys = api_add_trailing_slash(str_replace('\\', '/', realpath($pathForm)));
  312. $content = file_get_contents(dirname(__FILE__).'/'.SYSTEM_CONFIG_FILENAME);
  313. $config['{DATE_GENERATED}'] = date('r');
  314. $config['{DATABASE_HOST}'] = $dbHostForm;
  315. $config['{DATABASE_PORT}'] = $dbPortForm;
  316. $config['{DATABASE_USER}'] = $dbUsernameForm;
  317. $config['{DATABASE_PASSWORD}'] = $dbPassForm;
  318. $config['{DATABASE_MAIN}'] = $dbNameForm;
  319. $config['{ROOT_WEB}'] = $urlForm;
  320. $config['{ROOT_SYS}'] = $root_sys;
  321. $config['{URL_APPEND_PATH}'] = $urlAppendPath;
  322. $config['{PLATFORM_LANGUAGE}'] = $languageForm;
  323. $config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
  324. $config['{ENCRYPT_PASSWORD}'] = $encryptPassForm;
  325. $config['SESSION_LIFETIME'] = $session_lifetime;
  326. $config['{NEW_VERSION}'] = $new_version;
  327. $config['NEW_VERSION_STABLE'] = trueFalse($new_version_stable);
  328. foreach ($config as $key => $value) {
  329. $content = str_replace($key, $value, $content);
  330. }
  331. $fp = @ fopen($path, 'w');
  332. if (!$fp) {
  333. echo '<strong><font color="red">Your script doesn\'t have write access to the config directory</font></strong><br />
  334. <em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
  335. You probably do not have write access on Chamilo root directory,
  336. i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
  337. Your problems can be related on two possible causes:<br />
  338. <ul>
  339. <li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
  340. <li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>. If possible, try to switch it off.</li>
  341. </ul>
  342. <a href="http://forum.chamilo.org/" target="_blank">Read about this problem in Support Forum</a><br /><br />
  343. Please go back to step 5.
  344. <p><input type="submit" name="step5" value="&lt; Back" /></p>
  345. </td></tr></table></form></body></html>';
  346. exit;
  347. }
  348. fwrite($fp, $content);
  349. fclose($fp);
  350. }
  351. /**
  352. * Returns a list of language directories.
  353. */
  354. function & get_language_folder_list()
  355. {
  356. static $result;
  357. if (!is_array($result)) {
  358. $result = array();
  359. $exceptions = array('.', '..', 'CVS', '.svn');
  360. $search = array('_latin', '_unicode', '_corporate', '_org' , '_KM', '_');
  361. $replace_with = array(' (Latin)', ' (unicode)', ' (corporate)', ' (org)', ' (KM)', ' ');
  362. $dirname = api_get_path(SYS_LANG_PATH);
  363. $handle = opendir($dirname);
  364. while ($entries = readdir($handle)) {
  365. if (in_array($entries, $exceptions)) {
  366. continue;
  367. }
  368. if (is_dir($dirname.$entries)) {
  369. if (is_file($dirname.$entries.'/install_disabled')) {
  370. // Skip all languages that have this file present, just for
  371. // the install process (languages incomplete)
  372. continue;
  373. }
  374. $result[$entries] = ucwords(str_replace($search, $replace_with, $entries));
  375. }
  376. }
  377. closedir($handle);
  378. asort($result);
  379. }
  380. return $result;
  381. }
  382. /**
  383. * TODO: my_directory_to_array() - maybe within the main API there is already a suitable function?
  384. * @param string $directory Full path to a directory
  385. * @return array A list of files and dirs in the directory
  386. */
  387. function my_directory_to_array($directory)
  388. {
  389. $array_items = array();
  390. if ($handle = opendir($directory)) {
  391. while (false !== ($file = readdir($handle))) {
  392. if ($file != "." && $file != "..") {
  393. if (is_dir($directory. "/" . $file)) {
  394. $array_items = array_merge($array_items, my_directory_to_array($directory. '/' . $file));
  395. $file = $directory . "/" . $file;
  396. $array_items[] = preg_replace("/\/\//si", '/', $file);
  397. }
  398. }
  399. }
  400. closedir($handle);
  401. }
  402. return $array_items;
  403. }
  404. /**
  405. * This function returns the value of a parameter from the configuration file
  406. *
  407. * WARNING - this function relies heavily on global variables $updateFromConfigFile
  408. * and $configFile, and also changes these globals. This can be rewritten.
  409. *
  410. * @param string $param the parameter of which the value is returned
  411. * @param string If we want to give the path rather than take it from POST
  412. * @return string the value of the parameter
  413. * @author Olivier Brouckaert
  414. * @author Reworked by Ivan Tcholakov, 2010
  415. */
  416. function get_config_param($param, $updatePath = '')
  417. {
  418. global $configFile, $updateFromConfigFile;
  419. // Look if we already have the queried parameter.
  420. if (is_array($configFile) && isset($configFile[$param])) {
  421. return $configFile[$param];
  422. }
  423. if (empty($updatePath) && !empty($_POST['updatePath'])) {
  424. $updatePath = $_POST['updatePath'];
  425. }
  426. if (empty($updatePath)) {
  427. $updatePath = api_get_path(SYS_PATH);
  428. }
  429. $updatePath = api_add_trailing_slash(str_replace('\\', '/', realpath($updatePath)));
  430. $updateFromInstalledVersionFile = '';
  431. if (empty($updateFromConfigFile)) {
  432. // If update from previous install was requested,
  433. // try to recover config file from Chamilo 1.9.x
  434. if (file_exists($updatePath.'main/inc/conf/configuration.php')) {
  435. $updateFromConfigFile = 'main/inc/conf/configuration.php';
  436. } elseif (file_exists($updatePath . 'app/config/configuration.php')) {
  437. $updateFromConfigFile = 'app/config/configuration.php';
  438. } else {
  439. // Give up recovering.
  440. //error_log('Chamilo Notice: Could not find previous config file at '.$updatePath.'main/inc/conf/configuration.php nor at '.$updatePath.'claroline/inc/conf/claro_main.conf.php in get_config_param(). Will start new config (in '.__FILE__.', line '.__LINE__.')', 0);
  441. return null;
  442. }
  443. }
  444. if (file_exists($updatePath.$updateFromConfigFile) &&
  445. !is_dir($updatePath.$updateFromConfigFile)
  446. ) {
  447. require $updatePath.$updateFromConfigFile;
  448. $config = new Zend\Config\Config($_configuration);
  449. return $config->get($param);
  450. }
  451. error_log('Config array could not be found in get_config_param()', 0);
  452. return null;
  453. /*if (file_exists($updatePath.$updateFromConfigFile)) {
  454. return $val;
  455. } else {
  456. error_log('Config array could not be found in get_config_param()', 0);
  457. return null;
  458. }*/
  459. }
  460. /* DATABASE RELATED FUNCTIONS */
  461. /**
  462. * Gets a configuration parameter from the database. Returns returns null on failure.
  463. * @param string $param Name of param we want
  464. * @return mixed The parameter value or null if not found
  465. */
  466. function get_config_param_from_db($param = '')
  467. {
  468. if (($res = Database::query("SELECT * FROM settings_current WHERE variable = '$param'")) !== false) {
  469. if (Database::num_rows($res) > 0) {
  470. $row = Database::fetch_array($res);
  471. return $row['selected_value'];
  472. }
  473. }
  474. return null;
  475. }
  476. /**
  477. * Connect to the database and returns the entity manager
  478. * @param string $dbHostForm DB host
  479. * @param string $dbUsernameForm DB username
  480. * @param string $dbPassForm DB password
  481. * @param string $dbNameForm DB name
  482. * @param int $dbPortForm DB port
  483. *
  484. * @return EntityManager
  485. */
  486. function connectToDatabase($dbHostForm, $dbUsernameForm, $dbPassForm, $dbNameForm, $dbPortForm = 3306)
  487. {
  488. $dbParams = array(
  489. 'driver' => 'pdo_mysql',
  490. 'host' => $dbHostForm,
  491. 'port' => $dbPortForm,
  492. 'user' => $dbUsernameForm,
  493. 'password' => $dbPassForm,
  494. 'dbname' => $dbNameForm
  495. );
  496. $database = new \Database();
  497. $database->connect($dbParams);
  498. return $database->getManager();
  499. }
  500. /* DISPLAY FUNCTIONS */
  501. /**
  502. * This function prints class=active_step $current_step=$param
  503. * @param int $param A step in the installer process
  504. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  505. */
  506. function step_active($param)
  507. {
  508. global $current_step;
  509. if ($param == $current_step) {
  510. echo 'class="current-step" ';
  511. }
  512. }
  513. /**
  514. * This function displays the Step X of Y -
  515. * @return string String that says 'Step X of Y' with the right values
  516. */
  517. function display_step_sequence()
  518. {
  519. global $current_step;
  520. return get_lang('Step'.$current_step).' &ndash; ';
  521. }
  522. /**
  523. * Displays a drop down box for selection the preferred language.
  524. */
  525. function display_language_selection_box($name = 'language_list', $default_language = 'english')
  526. {
  527. // Reading language list.
  528. $language_list = get_language_folder_list();
  529. /*
  530. // Reduction of the number of languages shown. Enable this fragment of code for customization purposes.
  531. // Modify the language list according to your preference. Don't exclude the 'english' item.
  532. $language_to_display = array('asturian', 'bulgarian', 'english', 'italian', 'french', 'slovenian', 'slovenian_unicode', 'spanish');
  533. foreach ($language_list as $key => & $value) {
  534. if (!in_array($key, $language_to_display)) {
  535. unset($language_list[$key]);
  536. }
  537. }
  538. */
  539. // Sanity checks due to the possibility for customizations.
  540. if (!is_array($language_list) || empty($language_list)) {
  541. $language_list = array('english' => 'English');
  542. }
  543. // Sorting again, if it is necessary.
  544. //asort($language_list);
  545. // More sanity checks.
  546. if (!array_key_exists($default_language, $language_list)) {
  547. if (array_key_exists('english', $language_list)) {
  548. $default_language = 'english';
  549. } else {
  550. $language_keys = array_keys($language_list);
  551. $default_language = $language_keys[0];
  552. }
  553. }
  554. // Displaying the box.
  555. $html = '';
  556. $html .= "\t\t<select class='selectpicker show-tick' name=\"$name\">\n";
  557. foreach ($language_list as $key => $value) {
  558. if ($key == $default_language) {
  559. $option_end = ' selected="selected">';
  560. } else {
  561. $option_end = '>';
  562. }
  563. $html .= "\t\t\t<option value=\"$key\"$option_end";
  564. $html .= $value;
  565. $html .= "</option>\n";
  566. }
  567. $html .= "\t\t</select>\n";
  568. return $html;
  569. }
  570. /**
  571. * This function displays a language dropdown box so that the installatioin
  572. * can be done in the language of the user
  573. */
  574. function display_language_selection()
  575. { ?>
  576. <h2><?php get_lang('WelcomeToTheChamiloInstaller'); ?></h2>
  577. <div class="RequirementHeading">
  578. <h2><?php echo display_step_sequence(); ?>
  579. <?php echo get_lang('InstallationLanguage');?>
  580. </h2>
  581. <p><?php echo get_lang('PleaseSelectInstallationProcessLanguage'); ?>:</p>
  582. <form id="lang_form" method="post" action="<?php echo api_get_self(); ?>">
  583. <div class="form-group">
  584. <div class="col-sm-4">
  585. <?php echo display_language_selection_box('language_list', api_get_interface_language()); ?>
  586. </div>
  587. <div class="col-sm-6">
  588. <button type="submit" name="step1" class="btn btn-success" value="<?php echo get_lang('Next'); ?>">
  589. <em class="fa fa-forward"> </em>
  590. <?php echo get_lang('Next'); ?></button>
  591. </div>
  592. </div>
  593. <input type="hidden" name="is_executable" id="is_executable" value="-" />
  594. </form>
  595. </div>
  596. <div class="RequirementHeading">
  597. <?php echo get_lang('YourLanguageNotThereContactUs'); ?>
  598. </div>
  599. <?php
  600. }
  601. /**
  602. * This function displays the requirements for installing Chamilo.
  603. *
  604. * @param string $installType
  605. * @param boolean $badUpdatePath
  606. * @param boolean $badUpdatePath
  607. * @param string $updatePath The updatePath given (if given)
  608. * @param array $update_from_version_8 The different subversions from version 1.9
  609. *
  610. * @author unknow
  611. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  612. */
  613. function display_requirements(
  614. $installType,
  615. $badUpdatePath,
  616. $updatePath = '',
  617. $update_from_version_8 = array()
  618. ) {
  619. global $_setting;
  620. echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Requirements')."</h2></div>";
  621. echo '<div class="RequirementText">';
  622. echo '<strong>'.get_lang('ReadThoroughly').'</strong><br />';
  623. echo get_lang('MoreDetails').' <a href="../../documentation/installation_guide.html" target="_blank">'.get_lang('ReadTheInstallationGuide').'</a>.<br />'."\n";
  624. if ($installType == 'update') {
  625. echo get_lang('IfYouPlanToUpgradeFromOlderVersionYouMightWantToHaveAlookAtTheChangelog').'<br />';
  626. }
  627. echo '</div>';
  628. // SERVER REQUIREMENTS
  629. echo '<div class="RequirementHeading"><h4>'.get_lang('ServerRequirements').'</h4>';
  630. $timezone = checkPhpSettingExists("date.timezone");
  631. if (!$timezone) {
  632. echo "<div class='alert alert-warning'>".
  633. Display::return_icon('warning.png', get_lang('Warning'), '', ICON_SIZE_MEDIUM).
  634. get_lang("DateTimezoneSettingNotSet")."</div>";
  635. }
  636. echo '<div class="RequirementText">'.get_lang('ServerRequirementsInfo').'</div>';
  637. echo '<div class="RequirementContent">';
  638. echo '<table class="table">
  639. <tr>
  640. <td class="requirements-item">'.get_lang('PHPVersion').' >= '.REQUIRED_PHP_VERSION.'</td>
  641. <td class="requirements-value">';
  642. if (phpversion() < REQUIRED_PHP_VERSION) {
  643. echo '<strong><font color="red">'.get_lang('PHPVersionError').'</font></strong>';
  644. } else {
  645. echo '<strong><font color="green">'.get_lang('PHPVersionOK'). ' '.phpversion().'</font></strong>';
  646. }
  647. echo '</td>
  648. </tr>
  649. <tr>
  650. <td class="requirements-item"><a href="http://php.net/manual/en/book.session.php" target="_blank">Session</a> '.get_lang('Support').'</td>
  651. <td class="requirements-value">'.checkExtension('session', get_lang('Yes'), get_lang('ExtensionSessionsNotAvailable')).'</td>
  652. </tr>
  653. <tr>
  654. <td class="requirements-item"><a href="http://php.net/manual/en/book.mysql.php" target="_blank">pdo_mysql</a> '.get_lang('Support').'</td>
  655. <td class="requirements-value">'.checkExtension('pdo_mysql', get_lang('Yes'), get_lang('ExtensionMySQLNotAvailable')).'</td>
  656. </tr>
  657. <tr>
  658. <td class="requirements-item"><a href="http://php.net/manual/en/book.zip.php" target="_blank">Zip</a> '.get_lang('Support').'</td>
  659. <td class="requirements-value">'.checkExtension('zip', get_lang('Yes'), get_lang('ExtensionNotAvailable')).'</td>
  660. </tr>
  661. <tr>
  662. <td class="requirements-item"><a href="http://php.net/manual/en/book.zlib.php" target="_blank">Zlib</a> '.get_lang('Support').'</td>
  663. <td class="requirements-value">'.checkExtension('zlib', get_lang('Yes'), get_lang('ExtensionZlibNotAvailable')).'</td>
  664. </tr>
  665. <tr>
  666. <td class="requirements-item"><a href="http://php.net/manual/en/book.pcre.php" target="_blank">Perl-compatible regular expressions</a> '.get_lang('Support').'</td>
  667. <td class="requirements-value">'.checkExtension('pcre', get_lang('Yes'), get_lang('ExtensionPCRENotAvailable')).'</td>
  668. </tr>
  669. <tr>
  670. <td class="requirements-item"><a href="http://php.net/manual/en/book.xml.php" target="_blank">XML</a> '.get_lang('Support').'</td>
  671. <td class="requirements-value">'.checkExtension('xml', get_lang('Yes'), get_lang('No')).'</td>
  672. </tr>
  673. <tr>
  674. <td class="requirements-item"><a href="http://php.net/manual/en/book.intl.php" target="_blank">Internationalization</a> '.get_lang('Support').'</td>
  675. <td class="requirements-value">'.checkExtension('intl', get_lang('Yes'), get_lang('No')).'</td>
  676. </tr>
  677. <tr>
  678. <td class="requirements-item"><a href="http://php.net/manual/en/book.json.php" target="_blank">JSON</a> '.get_lang('Support').'</td>
  679. <td class="requirements-value">'.checkExtension('json', get_lang('Yes'), get_lang('No')).'</td>
  680. </tr>
  681. <tr>
  682. <td class="requirements-item"><a href="http://php.net/manual/en/book.image.php" target="_blank">GD</a> '.get_lang('Support').'</td>
  683. <td class="requirements-value">'.checkExtension('gd', get_lang('Yes'), get_lang('ExtensionGDNotAvailable')).'</td>
  684. </tr>
  685. <tr>
  686. <td class="requirements-item"><a href="http://php.net/manual/en/book.curl.php" target="_blank">cURL</a>'.get_lang('Support').'</td>
  687. <td class="requirements-value">'.checkExtension('curl', get_lang('Yes'), get_lang('No')).'</td>
  688. </tr>
  689. <tr>
  690. <td class="requirements-item"><a href="http://php.net/manual/en/book.mbstring.php" target="_blank">Multibyte string</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
  691. <td class="requirements-value">'.checkExtension('mbstring', get_lang('Yes'), get_lang('ExtensionMBStringNotAvailable'), true).'</td>
  692. </tr>
  693. <tr>
  694. <td class="requirements-item"><a href="http://php.net/opcache" target="_blank">Zend OpCache</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
  695. <td class="requirements-value">'.checkExtension('Zend OPcache', get_lang('Yes'), get_lang('No'), true, 'opcache.enable').'</td>
  696. </tr>
  697. <tr>
  698. <td class="requirements-item"><a href="http://php.net/apcu" target="_blank">APCu</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
  699. <td class="requirements-value">'.checkExtension('apcu', get_lang('Yes'), get_lang('No'), true, 'apc.enabled').'</td>
  700. </tr>
  701. <tr>
  702. <td class="requirements-item"><a href="http://php.net/manual/en/book.iconv.php" target="_blank">Iconv</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
  703. <td class="requirements-value">'.checkExtension('iconv', get_lang('Yes'), get_lang('No'), true).'</td>
  704. </tr>
  705. <tr>
  706. <td class="requirements-item"><a href="http://php.net/manual/en/book.ldap.php" target="_blank">LDAP</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
  707. <td class="requirements-value">'.checkExtension('ldap', get_lang('Yes'), get_lang('ExtensionLDAPNotAvailable'), true).'</td>
  708. </tr>
  709. <tr>
  710. <td class="requirements-item"><a href="http://xapian.org/" target="_blank">Xapian</a> '.get_lang('Support').' ('.get_lang('Optional').')</td>
  711. <td class="requirements-value">'.checkExtension('xapian', get_lang('Yes'), get_lang('No'), true).'</td>
  712. </tr>
  713. </table>';
  714. echo '</div>';
  715. echo '</div>';
  716. // RECOMMENDED SETTINGS
  717. // Note: these are the settings for Joomla, does this also apply for Chamilo?
  718. // Note: also add upload_max_filesize here so that large uploads are possible
  719. echo '<div class="RequirementHeading"><h4>'.get_lang('RecommendedSettings').'</h4>';
  720. echo '<div class="RequirementText">'.get_lang('RecommendedSettingsInfo').'</div>';
  721. echo '<div class="RequirementContent">';
  722. echo '<table class="table">
  723. <tr>
  724. <th>'.get_lang('Setting').'</th>
  725. <th>'.get_lang('Recommended').'</th>
  726. <th>'.get_lang('Actual').'</th>
  727. </tr>
  728. <tr>
  729. <td class="requirements-item"><a href="http://php.net/manual/features.safe-mode.php">Safe Mode</a></td>
  730. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  731. <td class="requirements-value">'.checkPhpSetting('safe_mode', 'OFF').'</td>
  732. </tr>
  733. <tr>
  734. <td class="requirements-item"><a href="http://php.net/manual/ref.errorfunc.php#ini.display-errors">Display Errors</a></td>
  735. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  736. <td class="requirements-value">'.checkPhpSetting('display_errors', 'OFF').'</td>
  737. </tr>
  738. <tr>
  739. <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.file-uploads">File Uploads</a></td>
  740. <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
  741. <td class="requirements-value">'.checkPhpSetting('file_uploads', 'ON').'</td>
  742. </tr>
  743. <tr>
  744. <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-gpc">Magic Quotes GPC</a></td>
  745. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  746. <td class="requirements-value">'.checkPhpSetting('magic_quotes_gpc', 'OFF').'</td>
  747. </tr>
  748. <tr>
  749. <td class="requirements-item"><a href="http://php.net/manual/ref.info.php#ini.magic-quotes-runtime">Magic Quotes Runtime</a></td>
  750. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  751. <td class="requirements-value">'.checkPhpSetting('magic_quotes_runtime', 'OFF').'</td>
  752. </tr>
  753. <tr>
  754. <td class="requirements-item"><a href="http://php.net/manual/security.globals.php">Register Globals</a></td>
  755. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  756. <td class="requirements-value">'.checkPhpSetting('register_globals', 'OFF').'</td>
  757. </tr>
  758. <tr>
  759. <td class="requirements-item"><a href="http://php.net/manual/ref.session.php#ini.session.auto-start">Session auto start</a></td>
  760. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  761. <td class="requirements-value">'.checkPhpSetting('session.auto_start', 'OFF').'</td>
  762. </tr>
  763. <tr>
  764. <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.short-open-tag">Short Open Tag</a></td>
  765. <td class="requirements-recommended">'.Display::label('OFF', 'success').'</td>
  766. <td class="requirements-value">'.checkPhpSetting('short_open_tag', 'OFF').'</td>
  767. </tr>
  768. <tr>
  769. <td class="requirements-item"><a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly">Cookie HTTP Only</a></td>
  770. <td class="requirements-recommended">'.Display::label('ON', 'success').'</td>
  771. <td class="requirements-value">'.checkPhpSetting('session.cookie_httponly', 'ON').'</td>
  772. </tr>
  773. <tr>
  774. <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.upload-max-filesize">Maximum upload file size</a></td>
  775. <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M', 'success').'</td>
  776. <td class="requirements-value">'.compare_setting_values(ini_get('upload_max_filesize'), REQUIRED_MIN_UPLOAD_MAX_FILESIZE).'</td>
  777. </tr>
  778. <tr>
  779. <td class="requirements-item"><a href="http://php.net/manual/ini.core.php#ini.post-max-size">Maximum post size</a></td>
  780. <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_POST_MAX_SIZE.'M', 'success').'</td>
  781. <td class="requirements-value">'.compare_setting_values(ini_get('post_max_size'), REQUIRED_MIN_POST_MAX_SIZE).'</td>
  782. </tr>
  783. <tr>
  784. <td class="requirements-item"><a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit">Memory Limit</a></td>
  785. <td class="requirements-recommended">'.Display::label('>= '.REQUIRED_MIN_MEMORY_LIMIT.'M', 'success').'</td>
  786. <td class="requirements-value">'.compare_setting_values(ini_get('memory_limit'), REQUIRED_MIN_MEMORY_LIMIT).'</td>
  787. </tr>
  788. </table>';
  789. echo ' </div>';
  790. echo '</div>';
  791. // DIRECTORY AND FILE PERMISSIONS
  792. echo '<div class="RequirementHeading"><h4>'.get_lang('DirectoryAndFilePermissions').'</h4>';
  793. echo '<div class="RequirementText">'.get_lang('DirectoryAndFilePermissionsInfo').'</div>';
  794. echo '<div class="RequirementContent">';
  795. $course_attempt_name = '__XxTestxX__';
  796. $course_dir = api_get_path(SYS_COURSE_PATH).$course_attempt_name;
  797. //Just in case
  798. @unlink($course_dir.'/test.php');
  799. @rmdir($course_dir);
  800. $perms_dir = array(0777, 0755, 0775, 0770, 0750, 0700);
  801. $perms_fil = array(0666, 0644, 0664, 0660, 0640, 0600);
  802. $course_test_was_created = false;
  803. $dir_perm_verified = 0777;
  804. foreach ($perms_dir as $perm) {
  805. $r = @mkdir($course_dir, $perm);
  806. if ($r === true) {
  807. $dir_perm_verified = $perm;
  808. $course_test_was_created = true;
  809. break;
  810. }
  811. }
  812. $fil_perm_verified = 0666;
  813. $file_course_test_was_created = false;
  814. if (is_dir($course_dir)) {
  815. foreach ($perms_fil as $perm) {
  816. if ($file_course_test_was_created == true) {
  817. break;
  818. }
  819. $r = @touch($course_dir.'/test.php', $perm);
  820. if ($r === true) {
  821. $fil_perm_verified = $perm;
  822. if (check_course_script_interpretation($course_dir, $course_attempt_name, 'test.php')) {
  823. $file_course_test_was_created = true;
  824. }
  825. }
  826. }
  827. }
  828. @unlink($course_dir.'/test.php');
  829. @rmdir($course_dir);
  830. $_SESSION['permissions_for_new_directories'] = $_setting['permissions_for_new_directories'] = $dir_perm_verified;
  831. $_SESSION['permissions_for_new_files'] = $_setting['permissions_for_new_files'] = $fil_perm_verified;
  832. $dir_perm = Display::label('0'.decoct($dir_perm_verified), 'info');
  833. $file_perm = Display::label('0'.decoct($fil_perm_verified), 'info');
  834. $courseTestLabel = Display::label(get_lang('No'), 'important');
  835. if ($course_test_was_created && $file_course_test_was_created) {
  836. $courseTestLabel = Display::label(get_lang('Yes'), 'success');
  837. }
  838. if ($course_test_was_created && !$file_course_test_was_created) {
  839. $courseTestLabel = Display::label(get_lang('Warning'), 'warning');
  840. $courseTestLabel .= '<br />'.sprintf(
  841. get_lang('InstallWarningCouldNotInterpretPHP'),
  842. api_get_path(WEB_COURSE_PATH).$course_attempt_name.'/test.php'
  843. );
  844. }
  845. if (!$course_test_was_created && !$file_course_test_was_created) {
  846. $courseTestLabel = Display::label(get_lang('No'), 'important');
  847. }
  848. $oldConf = '';
  849. if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/configuration.php')) {
  850. $oldConf = '<tr>
  851. <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'inc/conf</td>
  852. <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'inc/conf').'</td>
  853. </tr>';
  854. }
  855. echo '<table class="table">
  856. '.$oldConf.'
  857. <tr>
  858. <td class="requirements-item">'.api_get_path(SYS_APP_PATH).'</td>
  859. <td class="requirements-value">'.check_writable(api_get_path(SYS_APP_PATH)).'</td>
  860. </tr>
  861. <tr>
  862. <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'default_course_document/images/</td>
  863. <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'default_course_document/images/').'</td>
  864. </tr>
  865. <tr>
  866. <td class="requirements-item">'.api_get_path(SYS_CODE_PATH).'lang/</td>
  867. <td class="requirements-value">'.check_writable(api_get_path(SYS_CODE_PATH).'lang/', true).' <br />('.get_lang('SuggestionOnlyToEnableSubLanguageFeatureOrUpgradeProcess').')</td>
  868. </tr>
  869. <tr>
  870. <td class="requirements-item">'.api_get_path(SYS_PATH).'vendor/</td>
  871. <td class="requirements-value">'.checkReadable(api_get_path(SYS_PATH).'vendor').'</td>
  872. </tr>
  873. <tr>
  874. <td class="requirements-item">'.api_get_path(SYS_PUBLIC_PATH).'</td>
  875. <td class="requirements-value">'.check_writable(api_get_path(SYS_PUBLIC_PATH)).'</td>
  876. </tr>
  877. <tr>
  878. <td class="requirements-item">'.get_lang('CourseTestWasCreated').'</td>
  879. <td class="requirements-value">'.$courseTestLabel.' </td>
  880. </tr>
  881. <tr>
  882. <td class="requirements-item">'.get_lang('PermissionsForNewDirs').'</td>
  883. <td class="requirements-value">'.$dir_perm.' </td>
  884. </tr>
  885. <tr>
  886. <td class="requirements-item">'.get_lang('PermissionsForNewFiles').'</td>
  887. <td class="requirements-value">'.$file_perm.' </td>
  888. </tr>
  889. </table>';
  890. echo ' </div>';
  891. echo '</div>';
  892. if ($installType == 'update' && (empty($updatePath) || $badUpdatePath)) {
  893. if ($badUpdatePath) { ?>
  894. <div class="alert alert-warning">
  895. <?php echo get_lang('Error'); ?>!<br />
  896. Chamilo <?php echo implode('|', $update_from_version_8).' '.get_lang('HasNotBeenFoundInThatDir'); ?>.
  897. </div>
  898. <?php }
  899. else {
  900. echo '<br />';
  901. }
  902. ?>
  903. <div class="row">
  904. <div class="col-md-12">
  905. <p><?php echo get_lang('OldVersionRootPath'); ?>:
  906. <input type="text" name="updatePath" size="50" value="<?php echo ($badUpdatePath && !empty($updatePath)) ? htmlentities($updatePath) : ''; ?>" />
  907. </p>
  908. <p>
  909. <button type="submit" class="btn btn-default" name="step1" value="<?php echo get_lang('Back'); ?>" >
  910. <em class="fa fa-backward"> <?php echo get_lang('Back'); ?></em>
  911. </button>
  912. <input type="hidden" name="is_executable" id="is_executable" value="-" />
  913. <button type="submit" class="btn btn-success" name="<?php echo (isset($_POST['step2_update_6']) ? 'step2_update_6' : 'step2_update_8'); ?>" value="<?php echo get_lang('Next'); ?> &gt;" >
  914. <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
  915. </button>
  916. </p>
  917. </div>
  918. </div>
  919. <?php
  920. } else {
  921. $error = false;
  922. // First, attempt to set writing permissions if we don't have them yet
  923. $perm = api_get_permissions_for_new_directories();
  924. $perm_file = api_get_permissions_for_new_files();
  925. $notWritable = array();
  926. $checked_writable = api_get_path(SYS_APP_PATH);
  927. if (!is_writable($checked_writable)) {
  928. $notWritable[] = $checked_writable;
  929. @chmod($checked_writable, $perm);
  930. }
  931. $checked_writable = api_get_path(SYS_PUBLIC_PATH);
  932. if (!is_writable($checked_writable)) {
  933. $notWritable[] = $checked_writable;
  934. @chmod($checked_writable, $perm);
  935. }
  936. $checked_writable = api_get_path(SYS_CODE_PATH).'default_course_document/images/';
  937. if (!is_writable($checked_writable)) {
  938. $notWritable[] = $checked_writable;
  939. @chmod($checked_writable, $perm);
  940. }
  941. if ($course_test_was_created == false) {
  942. $error = true;
  943. }
  944. $checked_writable = api_get_path(CONFIGURATION_PATH).'configuration.php';
  945. if (file_exists($checked_writable) && !is_writable($checked_writable)) {
  946. $notWritable[] = $checked_writable;
  947. @chmod($checked_writable, $perm_file);
  948. }
  949. // Second, if this fails, report an error
  950. //--> The user would have to adjust the permissions manually
  951. if (count($notWritable) > 0) {
  952. $error = true;
  953. ?>
  954. <div class="text-danger">
  955. <h3 class="text-center"><?php echo get_lang('Warning') ?></h3>
  956. <p>
  957. <?php printf(get_lang('NoWritePermissionPleaseReadInstallGuide'), '<a href="../../documentation/installation_guide.html" target="blank">', '</a>'); ?>
  958. </p>
  959. </div>
  960. <?php
  961. echo '<ul>';
  962. foreach ($notWritable as $value) {
  963. echo '<li class="text-danger">'.$value.'</li>';
  964. }
  965. echo '</ul>';
  966. } elseif (file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php')) {
  967. // Check wether a Chamilo configuration file already exists.
  968. echo '<div class="alert alert-warning"><h4><center>';
  969. echo get_lang('WarningExistingLMSInstallationDetected');
  970. echo '</center></h4></div>';
  971. }
  972. $deprecated = [
  973. api_get_path(SYS_CODE_PATH) . 'exercice/',
  974. api_get_path(SYS_CODE_PATH) . 'newscorm/',
  975. api_get_path(SYS_PLUGIN_PATH) . 'ticket/'
  976. ];
  977. $deprecatedToRemove = [];
  978. foreach ($deprecated as $deprecatedDirectory) {
  979. if (!is_dir($deprecatedDirectory)) {
  980. continue;
  981. }
  982. $deprecatedToRemove[] = $deprecatedDirectory;
  983. }
  984. if (count($deprecatedToRemove) > 0) {
  985. $error = true;
  986. ?>
  987. <p class="text-danger"><?php echo get_lang('WarningForDeprecatedDirectoriesForUpgrade') ?></p>
  988. <ul>
  989. <?php foreach ($deprecatedToRemove as $deprecatedDirectory) { ?>
  990. <li class="text-danger"><?php echo $deprecatedDirectory ?></li>
  991. <?php } ?>
  992. </ul>
  993. <?php
  994. }
  995. // And now display the choice buttons (go back or install)
  996. ?>
  997. <p align="center" style="padding-top:15px">
  998. <button type="submit" name="step1" class="btn btn-default" onclick="javascript: window.location='index.php'; return false;" value="<?php echo get_lang('Previous'); ?>" >
  999. <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
  1000. </button>
  1001. <button type="submit" name="step2_install" class="btn btn-success" value="<?php echo get_lang("NewInstallation"); ?>" <?php if ($error) echo 'disabled="disabled"'; ?> >
  1002. <em class="fa fa-forward"> </em> <?php echo get_lang('NewInstallation'); ?>
  1003. </button>
  1004. <input type="hidden" name="is_executable" id="is_executable" value="-" />
  1005. <button type="submit" class="btn btn-default" <?php echo !$error ?: 'disabled="disabled"' ?> name="step2_update_8" value="Upgrade from Chamilo 1.9.x">
  1006. <em class="fa fa-forward" aria-hidden="true"></em> <?php echo get_lang('UpgradeFromLMS19x') ?>
  1007. </button>
  1008. </p>
  1009. <?php
  1010. }
  1011. }
  1012. /**
  1013. * Displays the license (GNU GPL) as step 2, with
  1014. * - an "I accept" button named step3 to proceed to step 3;
  1015. * - a "Back" button named step1 to go back to the first step.
  1016. */
  1017. function display_license_agreement()
  1018. {
  1019. echo '<div class="RequirementHeading"><h2>'.display_step_sequence().get_lang('Licence').'</h2>';
  1020. echo '<p>'.get_lang('LMSLicenseInfo').'</p>';
  1021. echo '<p><a href="../../documentation/license.html" target="_blank">'.get_lang('PrintVers').'</a></p>';
  1022. echo '</div>';
  1023. ?>
  1024. <div class="row">
  1025. <div class="col-md-12">
  1026. <pre style="overflow: auto; height: 200px; margin-top: 5px;">
  1027. <?php echo api_htmlentities(@file_get_contents(api_get_path(SYS_PATH).'documentation/license.txt')); ?>
  1028. </pre>
  1029. <div class="checkbox">
  1030. <label>
  1031. <input type="checkbox" name="accept" id="accept_licence" value="1" />
  1032. <?php echo get_lang('IAccept'); ?>
  1033. </label>
  1034. </div>
  1035. </div>
  1036. </div>
  1037. <div class="row">
  1038. <div class="col-md-12">
  1039. <p class="alert alert-info"><?php echo get_lang('LMSMediaLicense'); ?></p>
  1040. </div>
  1041. </div>
  1042. <!-- Contact information form -->
  1043. <div class="section-parameters">
  1044. <a href="javascript://" class = "advanced_parameters" >
  1045. <span id="img_plus_and_minus">&nbsp;<img src="<?php echo api_get_path(WEB_IMG_PATH) ?>div_hide.gif" alt="<?php echo get_lang('Hide') ?>" title="<?php echo get_lang('Hide')?>" style ="vertical-align:middle" />&nbsp;<?php echo get_lang('ContactInformation') ?></span>
  1046. </a>
  1047. </div>
  1048. <div id="id_contact_form" style="display:block">
  1049. <div class="normal-message"><?php echo get_lang('ContactInformationDescription') ?></div>
  1050. <div id="contact_registration">
  1051. <p><?php echo get_contact_registration_form() ?></p><br />
  1052. </div>
  1053. </div>
  1054. <div class="text-center">
  1055. <button type="submit" class="btn btn-default" name="step1" value="&lt; <?php echo get_lang('Previous'); ?>" >
  1056. <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
  1057. </button>
  1058. <input type="hidden" name="is_executable" id="is_executable" value="-" />
  1059. <button type="submit" id="license-next" class="btn btn-success" name="step3" onclick="javascript: if(!document.getElementById('accept_licence').checked) { alert('<?php echo get_lang('YouMustAcceptLicence')?>');return false;}" value="<?php echo get_lang('Next'); ?> &gt;" >
  1060. <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
  1061. </button>
  1062. </div>
  1063. <?php
  1064. }
  1065. /**
  1066. * Get contact registration form
  1067. */
  1068. function get_contact_registration_form()
  1069. {
  1070. $html ='
  1071. <div class="form-horizontal">
  1072. <div class="panel panel-default">
  1073. <div class="panel-body">
  1074. <div id="div_sent_information"></div>
  1075. <div class="form-group">
  1076. <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Name').'</label>
  1077. <div class="col-sm-9"><input id="person_name" class="form-control" type="text" name="person_name" size="30" /></div>
  1078. </div>
  1079. <div class="form-group">
  1080. <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('Email').'</label>
  1081. <div class="col-sm-9"><input id="person_email" class="form-control" type="text" name="person_email" size="30" /></div>
  1082. </div>
  1083. <div class="form-group">
  1084. <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyName').'</label>
  1085. <div class="col-sm-9"><input id="company_name" class="form-control" type="text" name="company_name" size="30" /></div>
  1086. </div>
  1087. <div class="form-group">
  1088. <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyActivity').'</label>
  1089. <div class="col-sm-9">
  1090. <select class="selectpicker show-tick" name="company_activity" id="company_activity" >
  1091. <option value="">--- '.get_lang('SelectOne').' ---</option>
  1092. <Option value="Advertising/Marketing/PR">Advertising/Marketing/PR</Option><Option value="Agriculture/Forestry">Agriculture/Forestry</Option>
  1093. <Option value="Architecture">Architecture</Option><Option value="Banking/Finance">Banking/Finance</Option>
  1094. <Option value="Biotech/Pharmaceuticals">Biotech/Pharmaceuticals</Option><Option value="Business Equipment">Business Equipment</Option>
  1095. <Option value="Business Services">Business Services</Option><Option value="Construction">Construction</Option>
  1096. <Option value="Consulting/Research">Consulting/Research</Option><Option value="Education">Education</Option>
  1097. <Option value="Engineering">Engineering</Option><Option value="Environmental">Environmental</Option>
  1098. <Option value="Government">Government</Option><Option value="Healthcare">Health Care</Option>
  1099. <Option value="Hospitality/Lodging/Travel">Hospitality/Lodging/Travel</Option><Option value="Insurance">Insurance</Option>
  1100. <Option value="Legal">Legal</Option><Option value="Manufacturing">Manufacturing</Option>
  1101. <Option value="Media/Entertainment">Media/Entertainment</Option><Option value="Mortgage">Mortgage</Option>
  1102. <Option value="Non-Profit">Non-Profit</Option><Option value="Real Estate">Real Estate</Option>
  1103. <Option value="Restaurant">Restaurant</Option><Option value="Retail">Retail</Option>
  1104. <Option value="Shipping/Transportation">Shipping/Transportation</Option>
  1105. <Option value="Technology">Technology</Option><Option value="Telecommunications">Telecommunications</Option>
  1106. <Option value="Other">Other</Option>
  1107. </select>
  1108. </div>
  1109. </div>
  1110. <div class="form-group">
  1111. <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('PersonRole').'</label>
  1112. <div class="col-sm-9">
  1113. <select class="selectpicker show-tick" name="person_role" id="person_role" >
  1114. <option value="">--- '.get_lang('SelectOne').' ---</option>
  1115. <Option value="Administration">Administration</Option><Option value="CEO/President/ Owner">CEO/President/ Owner</Option>
  1116. <Option value="CFO">CFO</Option><Option value="CIO/CTO">CIO/CTO</Option>
  1117. <Option value="Consultant">Consultant</Option><Option value="Customer Service">Customer Service</Option>
  1118. <Option value="Engineer/Programmer">Engineer/Programmer</Option><Option value="Facilities/Operations">Facilities/Operations</Option>
  1119. <Option value="Finance/ Accounting Manager">Finance/ Accounting Manager</Option><Option value="Finance/ Accounting Staff">Finance/ Accounting Staff</Option>
  1120. <Option value="General Manager">General Manager</Option><Option value="Human Resources">Human Resources</Option>
  1121. <Option value="IS/IT Management">IS/IT Management</Option><Option value="IS/ IT Staff">IS/ IT Staff</Option>
  1122. <Option value="Marketing Manager">Marketing Manager</Option><Option value="Marketing Staff">Marketing Staff</Option>
  1123. <Option value="Partner/Principal">Partner/Principal</Option><Option value="Purchasing Manager">Purchasing Manager</Option>
  1124. <Option value="Sales/ Business Dev. Manager">Sales/ Business Dev. Manager</Option><Option value="Sales/ Business Dev.">Sales/ Business Dev.</Option>
  1125. <Option value="Vice President/Senior Manager">Vice President/Senior Manager</Option><Option value="Other">Other</Option>
  1126. </select>
  1127. </div>
  1128. </div>
  1129. <div class="form-group">
  1130. <label class="col-sm-3"><span class="form_required">*</span>'.get_lang('CompanyCountry').'</label>
  1131. <div class="col-sm-9">'.get_countries_list_from_array(true).'</div>
  1132. </div>
  1133. <div class="form-group">
  1134. <label class="col-sm-3">'.get_lang('CompanyCity').'</label>
  1135. <div class="col-sm-9">
  1136. <input type="text" class="form-control" id="company_city" name="company_city" size="30" />
  1137. </div>
  1138. </div>
  1139. <div class="form-group">
  1140. <label class="col-sm-3">'.get_lang('WhichLanguageWouldYouLikeToUseWhenContactingYou').'</label>
  1141. <div class="col-sm-9">
  1142. <select class="selectpicker show-tick" id="language" name="language">
  1143. <option value="bulgarian">Bulgarian</option>
  1144. <option value="indonesian">Bahasa Indonesia</option>
  1145. <option value="bosnian">Bosanski</option>
  1146. <option value="german">Deutsch</option>
  1147. <option selected="selected" value="english">English</option>
  1148. <option value="spanish">Spanish</option>
  1149. <option value="french">Français</option>
  1150. <option value="italian">Italian</option>
  1151. <option value="hungarian">Magyar</option>
  1152. <option value="dutch">Nederlands</option>
  1153. <option value="brazilian">Português do Brasil</option>
  1154. <option value="portuguese">Português europeu</option>
  1155. <option value="slovenian">Slovenčina</option>
  1156. </select>
  1157. </div>
  1158. </div>
  1159. <div class="form-group">
  1160. <label class="col-sm-3">'.get_lang('HaveYouThePowerToTakeFinancialDecisions').'</label>
  1161. <div class="col-sm-9">
  1162. <div class="radio">
  1163. <label>
  1164. <input type="radio" name="financial_decision" id="financial_decision1" value="1" checked /> ' . get_lang('Yes') . '
  1165. </label>
  1166. </div>
  1167. <div class="radio">
  1168. <label>
  1169. <input type="radio" name="financial_decision" id="financial_decision2" value="0" /> '.get_lang('No').'
  1170. </label>
  1171. </div>
  1172. </div>
  1173. </div>
  1174. <div class="clear"></div>
  1175. <div class="form-group">
  1176. <div class="col-sm-3">&nbsp;</div>
  1177. <div class="col-sm-9"><button type="button" class="btn btn-default" onclick="javascript:send_contact_information();" value="'.get_lang('SendInformation').'" ><em class="fa fa-floppy-o"></em> '.get_lang('SendInformation').'</button> <span id="loader-button"></span></div>
  1178. </div>
  1179. <div class="form-group">
  1180. <div class="col-sm-3">&nbsp;</div>
  1181. <div class="col-sm-9"><span class="form_required">*</span><small>'.get_lang('FieldRequired').'</small></div>
  1182. </div></div></div>
  1183. </div>';
  1184. return $html;
  1185. }
  1186. /**
  1187. * Displays a parameter in a table row.
  1188. * Used by the display_database_settings_form function.
  1189. * @param string Type of install
  1190. * @param string Name of parameter
  1191. * @param string Field name (in the HTML form)
  1192. * @param string Field value
  1193. * @param string Extra notice (to show on the right side)
  1194. * @param boolean Whether to display in update mode
  1195. * @param string Additional attribute for the <tr> element
  1196. * @return void Direct output
  1197. */
  1198. function displayDatabaseParameter(
  1199. $installType,
  1200. $parameterName,
  1201. $formFieldName,
  1202. $parameterValue,
  1203. $extra_notice,
  1204. $displayWhenUpdate = true,
  1205. $tr_attribute = ''
  1206. ) {
  1207. //echo "<tr ".$tr_attribute.">";
  1208. echo "<label class='col-sm-4'>$parameterName</label>";
  1209. if ($installType == INSTALL_TYPE_UPDATE && $displayWhenUpdate) {
  1210. echo '<input type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'" value="'.api_htmlentities($parameterValue).'" />'.$parameterValue;
  1211. } else {
  1212. $inputType = $formFieldName == 'dbPassForm' ? 'password' : 'text';
  1213. //Slightly limit the length of the database prefix to avoid having to cut down the databases names later on
  1214. $maxLength = $formFieldName == 'dbPrefixForm' ? '15' : MAX_FORM_FIELD_LENGTH;
  1215. if ($installType == INSTALL_TYPE_UPDATE) {
  1216. echo '<input type="hidden" name="'.$formFieldName.'" id="'.$formFieldName.'" value="'.api_htmlentities($parameterValue).'" />';
  1217. echo api_htmlentities($parameterValue);
  1218. } else {
  1219. echo '<div class="col-sm-5"><input type="' . $inputType . '" class="form-control" size="' . DATABASE_FORM_FIELD_DISPLAY_LENGTH . '" maxlength="' . $maxLength . '" name="' . $formFieldName . '" id="' . $formFieldName . '" value="' . api_htmlentities($parameterValue) . '" />' . "</div>";
  1220. echo '<div class="col-sm-3">' . $extra_notice . '</div>';
  1221. }
  1222. }
  1223. }
  1224. /**
  1225. * Displays step 3 - a form where the user can enter the installation settings
  1226. * regarding the databases - login and password, names, prefixes, single
  1227. * or multiple databases, tracking or not...
  1228. * @param string $installType
  1229. * @param string $dbHostForm
  1230. * @param string $dbUsernameForm
  1231. * @param string $dbPassForm
  1232. * @param string $dbNameForm
  1233. * @param int $dbPortForm
  1234. * @param string $installationProfile
  1235. */
  1236. function display_database_settings_form(
  1237. $installType,
  1238. $dbHostForm,
  1239. $dbUsernameForm,
  1240. $dbPassForm,
  1241. $dbNameForm,
  1242. $dbPortForm = 3306,
  1243. $installationProfile = ''
  1244. ) {
  1245. if ($installType == 'update') {
  1246. global $_configuration;
  1247. $dbHostForm = $_configuration['db_host'];
  1248. $dbUsernameForm = $_configuration['db_user'];
  1249. $dbPassForm = $_configuration['db_password'];
  1250. $dbNameForm = $_configuration['main_database'];
  1251. $dbPortForm = isset($_configuration['db_port']) ? $_configuration['db_port'] : '';
  1252. echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
  1253. echo '<div class="RequirementContent">';
  1254. echo get_lang('DBSettingUpgradeIntro');
  1255. echo '</div>';
  1256. } else {
  1257. echo '<div class="RequirementHeading"><h2>' . display_step_sequence() .get_lang('DBSetting') . '</h2></div>';
  1258. echo '<div class="RequirementContent">';
  1259. echo get_lang('DBSettingIntro');
  1260. echo '</div>';
  1261. }
  1262. ?>
  1263. <div class="panel panel-default">
  1264. <div class="panel-body">
  1265. <div class="form-group">
  1266. <label class="col-sm-4"><?php echo get_lang('DBHost'); ?> </label>
  1267. <?php if ($installType == 'update'){ ?>
  1268. <div class="col-sm-5">
  1269. <input type="hidden" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" /><?php echo $dbHostForm; ?>
  1270. </div>
  1271. <div class="col-sm-3"></div>
  1272. <?php }else{ ?>
  1273. <div class="col-sm-5">
  1274. <input type="text" class="form-control" size="25" maxlength="50" name="dbHostForm" value="<?php echo htmlentities($dbHostForm); ?>" />
  1275. </div>
  1276. <div class="col-sm-3"><?php echo get_lang('EG').' localhost'; ?></div>
  1277. <?php } ?>
  1278. </div>
  1279. <div class="form-group">
  1280. <label class="col-sm-4"><?php echo get_lang('DBPort'); ?> </label>
  1281. <?php if ($installType == 'update'){ ?>
  1282. <div class="col-sm-5">
  1283. <input type="hidden" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" /><?php echo $dbPortForm; ?>
  1284. </div>
  1285. <div class="col-sm-3"></div>
  1286. <?php }else{ ?>
  1287. <div class="col-sm-5">
  1288. <input type="text" class="form-control" size="25" maxlength="50" name="dbPortForm" value="<?php echo htmlentities($dbPortForm); ?>" />
  1289. </div>
  1290. <div class="col-sm-3"><?php echo get_lang('EG').' 3306'; ?></div>
  1291. <?php } ?>
  1292. </div>
  1293. <div class="form-group">
  1294. <?php
  1295. //database user username
  1296. $example_login = get_lang('EG').' root';
  1297. displayDatabaseParameter($installType, get_lang('DBLogin'), 'dbUsernameForm', $dbUsernameForm, $example_login);
  1298. ?>
  1299. </div>
  1300. <div class="form-group">
  1301. <?php
  1302. //database user password
  1303. $example_password = get_lang('EG').' '.api_generate_password();
  1304. displayDatabaseParameter($installType, get_lang('DBPassword'), 'dbPassForm', $dbPassForm, $example_password);
  1305. ?>
  1306. </div>
  1307. <div class="form-group">
  1308. <?php
  1309. //Database Name fix replace weird chars
  1310. if ($installType != INSTALL_TYPE_UPDATE) {
  1311. $dbNameForm = str_replace(array('-','*', '$', ' ', '.'), '', $dbNameForm);
  1312. }
  1313. displayDatabaseParameter(
  1314. $installType,
  1315. get_lang('MainDB'),
  1316. 'dbNameForm',
  1317. $dbNameForm,
  1318. '&nbsp;',
  1319. null,
  1320. 'id="optional_param1"'
  1321. );
  1322. ?>
  1323. </div>
  1324. <?php if ($installType != INSTALL_TYPE_UPDATE) { ?>
  1325. <div class="form-group">
  1326. <div class="col-sm-3"></div>
  1327. <div class="col-sm-9">
  1328. <button type="submit" class="btn btn-primary" name="step3" value="step3">
  1329. <em class="fa fa-refresh"> </em>
  1330. <?php echo get_lang('CheckDatabaseConnection'); ?>
  1331. </button>
  1332. </div>
  1333. </div>
  1334. <?php } ?>
  1335. </div>
  1336. </div>
  1337. <?php
  1338. $database_exists_text = '';
  1339. $manager = null;
  1340. try {
  1341. $manager = connectToDatabase(
  1342. $dbHostForm,
  1343. $dbUsernameForm,
  1344. $dbPassForm,
  1345. null,
  1346. $dbPortForm
  1347. );
  1348. $databases = $manager->getConnection()->getSchemaManager()->listDatabases();
  1349. if (in_array($dbNameForm, $databases)) {
  1350. $database_exists_text = '<div class="alert alert-warning">'.get_lang('ADatabaseWithTheSameNameAlreadyExists').'</div>';
  1351. }
  1352. } catch (Exception $e) {
  1353. $database_exists_text = $e->getMessage();
  1354. }
  1355. if ($manager && $manager->getConnection()->isConnected()): ?>
  1356. <?php echo $database_exists_text ?>
  1357. <div id="db_status" class="alert alert-success">
  1358. Database host: <strong><?php echo $manager->getConnection()->getHost(); ?></strong><br/>
  1359. Database port: <strong><?php echo $manager->getConnection()->getPort(); ?></strong><br/>
  1360. Database driver: <strong><?php echo $manager->getConnection()->getDriver()->getName(); ?></strong><br/>
  1361. </div>
  1362. <?php else: ?>
  1363. <div id="db_status" class="alert alert-danger">
  1364. <p><?php echo get_lang('FailedConectionDatabase'); ?></strong></p>
  1365. <code><?php echo $database_exists_text ?></code>
  1366. </div>
  1367. <?php endif; ?>
  1368. <div class="form-group">
  1369. <div class="col-sm-6">
  1370. <button type="submit" name="step2" class="btn btn-default pull-right" value="&lt; <?php echo get_lang('Previous'); ?>" >
  1371. <em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?>
  1372. </button>
  1373. </div>
  1374. <div class="col-sm-6">
  1375. <input type="hidden" name="is_executable" id="is_executable" value="-" />
  1376. <?php if ($manager) { ?>
  1377. <button type="submit" class="btn btn-success" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
  1378. <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
  1379. </button>
  1380. <?php } else { ?>
  1381. <button disabled="disabled" type="submit" class="btn btn-success disabled" name="step4" value="<?php echo get_lang('Next'); ?> &gt;" >
  1382. <em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?>
  1383. </button>
  1384. <?php } ?>
  1385. </div>
  1386. </div>
  1387. <?php
  1388. }
  1389. function panel($content = null, $title = null, $id = null, $style = null) {
  1390. $html = '';
  1391. if (empty($style)) {
  1392. $style = 'default';
  1393. }
  1394. if (!empty($title)) {
  1395. $panelTitle = Display::div($title, array('class' => 'panel-heading'));
  1396. $panelBody = Display::div($content, array('class' => 'panel-body'));
  1397. $panelParent = Display::div($panelTitle . $panelBody, array('id' => $id, 'class' => 'panel panel-'.$style));
  1398. } else {
  1399. $panelBody = Display::div($html, array('class' => 'panel-body'));
  1400. $panelParent = Display::div($panelBody, array('id' => $id, 'class' => 'panel panel-'.$style));
  1401. }
  1402. $html .= $panelParent;
  1403. return $html;
  1404. }
  1405. /**
  1406. * Displays a parameter in a table row.
  1407. * Used by the display_configuration_settings_form function.
  1408. * @param string $installType
  1409. * @param string $parameterName
  1410. * @param string $formFieldName
  1411. * @param string $parameterValue
  1412. * @param string $displayWhenUpdate
  1413. */
  1414. function display_configuration_parameter(
  1415. $installType,
  1416. $parameterName,
  1417. $formFieldName,
  1418. $parameterValue,
  1419. $displayWhenUpdate = 'true'
  1420. ) {
  1421. $html = '<div class="form-group">';
  1422. $html .= '<label class="col-sm-6 control-label">' . $parameterName . '</label>';
  1423. if ($installType == INSTALL_TYPE_UPDATE && $displayWhenUpdate) {
  1424. $html .= '<input type="hidden" name="' . $formFieldName . '" value="'. api_htmlentities($parameterValue, ENT_QUOTES). '" />' . $parameterValue;
  1425. } else {
  1426. $html .= '<div class="col-sm-6"><input class="form-control" type="text" size="'.FORM_FIELD_DISPLAY_LENGTH.'" maxlength="'.MAX_FORM_FIELD_LENGTH.'" name="'.$formFieldName.'" value="'.api_htmlentities($parameterValue, ENT_QUOTES).'" />'."</div>";
  1427. }
  1428. $html .= "</div>";
  1429. return $html;
  1430. }
  1431. /**
  1432. * Displays step 4 of the installation - configuration settings about Chamilo itself.
  1433. * @param string $installType
  1434. * @param string $urlForm
  1435. * @param string $languageForm
  1436. * @param string $emailForm
  1437. * @param string $adminFirstName
  1438. * @param string $adminLastName
  1439. * @param string $adminPhoneForm
  1440. * @param string $campusForm
  1441. * @param string $institutionForm
  1442. * @param string $institutionUrlForm
  1443. * @param string $encryptPassForm
  1444. * @param bool $allowSelfReg
  1445. * @param bool $allowSelfRegProf
  1446. * @param string $loginForm
  1447. * @param string $passForm
  1448. */
  1449. function display_configuration_settings_form(
  1450. $installType,
  1451. $urlForm,
  1452. $languageForm,
  1453. $emailForm,
  1454. $adminFirstName,
  1455. $adminLastName,
  1456. $adminPhoneForm,
  1457. $campusForm,
  1458. $institutionForm,
  1459. $institutionUrlForm,
  1460. $encryptPassForm,
  1461. $allowSelfReg,
  1462. $allowSelfRegProf,
  1463. $loginForm,
  1464. $passForm
  1465. ) {
  1466. if ($installType != 'update' && empty($languageForm)) {
  1467. $languageForm = $_SESSION['install_language'];
  1468. }
  1469. echo '<div class="RequirementHeading">';
  1470. echo "<h2>" . display_step_sequence() . get_lang("CfgSetting") . "</h2>";
  1471. echo '</div>';
  1472. echo '<p>'.get_lang('ConfigSettingsInfo').' <strong>app/config/configuration.php</strong></p>';
  1473. // Parameter 1: administrator's login
  1474. $html = '';
  1475. $html .= display_configuration_parameter($installType, get_lang('AdminLogin'), 'loginForm', $loginForm, $installType == 'update');
  1476. // Parameter 2: administrator's password
  1477. if ($installType != 'update') {
  1478. $html .= display_configuration_parameter($installType, get_lang('AdminPass'), 'passForm', $passForm, false);
  1479. }
  1480. // Parameters 3 and 4: administrator's names
  1481. $html .= display_configuration_parameter($installType, get_lang('AdminFirstName'), 'adminFirstName', $adminFirstName);
  1482. $html .= display_configuration_parameter($installType, get_lang('AdminLastName'), 'adminLastName', $adminLastName);
  1483. //Parameter 3: administrator's email
  1484. $html .= display_configuration_parameter($installType, get_lang('AdminEmail'), 'emailForm', $emailForm);
  1485. //Parameter 6: administrator's telephone
  1486. $html .= display_configuration_parameter($installType, get_lang('AdminPhone'), 'adminPhoneForm', $adminPhoneForm);
  1487. echo panel($html, get_lang('Administrator'), 'administrator');
  1488. //echo '<table class="table">';
  1489. //First parameter: language
  1490. $html = '<div class="form-group">';
  1491. $html .= '<label class="col-sm-6 control-label">'.get_lang('MainLang')."</label>";
  1492. if ($installType == 'update') {
  1493. $html .= '<input type="hidden" name="languageForm" value="'.api_htmlentities($languageForm, ENT_QUOTES).'" />'.$languageForm;
  1494. } else { // new installation
  1495. $html .= '<div class="col-sm-6">';
  1496. $html .= display_language_selection_box('languageForm', $languageForm);
  1497. $html .= '</div>';
  1498. }
  1499. $html.= "</div>";
  1500. //Second parameter: Chamilo URL
  1501. $html .= '<div class="form-group">';
  1502. $html .= '<label class="col-sm-6 control-label">'.get_lang('ChamiloURL') .get_lang('ThisFieldIsRequired').'</label>';
  1503. if ($installType == 'update') {
  1504. $html .= api_htmlentities($urlForm, ENT_QUOTES)."\n";
  1505. } else {
  1506. $html .= '<div class="col-sm-6">';
  1507. $html .= '<input class="form-control" type="text" size="40" maxlength="100" name="urlForm" value="'.api_htmlentities($urlForm, ENT_QUOTES).'" />';
  1508. $html .= '</div>';
  1509. }
  1510. $html .= '</div>';
  1511. //Parameter 9: campus name
  1512. $html .= display_configuration_parameter($installType, get_lang('CampusName'), 'campusForm', $campusForm);
  1513. //Parameter 10: institute (short) name
  1514. $html .= display_configuration_parameter($installType, get_lang('InstituteShortName'), 'institutionForm', $institutionForm);
  1515. //Parameter 11: institute (short) name
  1516. $html .= display_configuration_parameter($installType, get_lang('InstituteURL'), 'institutionUrlForm', $institutionUrlForm);
  1517. $html .= '<div class="form-group">
  1518. <label class="col-sm-6 control-label">' . get_lang("EncryptMethodUserPass") . '</label>
  1519. <div class="col-sm-6">';
  1520. if ($installType == 'update') {
  1521. $html .= '<input type="hidden" name="encryptPassForm" value="'. $encryptPassForm .'" />'. $encryptPassForm;
  1522. } else {
  1523. $html .= '<div class="checkbox">
  1524. <label>
  1525. <input type="radio" name="encryptPassForm" value="bcrypt" id="encryptPass1" '. ($encryptPassForm == 'bcrypt' ? 'checked="checked" ':'') .'/> bcrypt
  1526. </label>';
  1527. $html .= '<label>
  1528. <input type="radio" name="encryptPassForm" value="sha1" id="encryptPass1" '. ($encryptPassForm == 'sha1' ? 'checked="checked" ':'') .'/> sha1
  1529. </label>';
  1530. $html .= '<label>
  1531. <input type="radio" name="encryptPassForm" value="md5" id="encryptPass0" '. ($encryptPassForm == 'md5' ? 'checked="checked" ':'') .'/> md5
  1532. </label>';
  1533. $html .= '<label>
  1534. <input type="radio" name="encryptPassForm" value="none" id="encryptPass2" '. ($encryptPassForm == 'none' ? 'checked="checked" ':'') .'/>'. get_lang('None').'
  1535. </label>';
  1536. $html .= '</div>';
  1537. }
  1538. $html .= '</div></div>';
  1539. $html .= '<div class="form-group">
  1540. <label class="col-sm-6 control-label">' . get_lang('AllowSelfReg') . '</label>
  1541. <div class="col-sm-6">';
  1542. if ($installType == 'update') {
  1543. if ($allowSelfReg == 'true') {
  1544. $label = get_lang('Yes');
  1545. } elseif ($allowSelfReg == 'false') {
  1546. $label = get_lang('No');
  1547. } else {
  1548. $label = get_lang('AfterApproval');
  1549. }
  1550. $html .= '<input type="hidden" name="allowSelfReg" value="'. $allowSelfReg .'" />'. $label;
  1551. } else {
  1552. $html .= '<div class="control-group">';
  1553. $html .= '<label class="checkbox-inline">
  1554. <input type="radio" name="allowSelfReg" value="true" id="allowSelfReg1" '. ($allowSelfReg == 'true' ? 'checked="checked" ' : '') . ' /> '. get_lang('Yes') .'
  1555. </label>';
  1556. $html .= '<label class="checkbox-inline">
  1557. <input type="radio" name="allowSelfReg" value="false" id="allowSelfReg0" '. ($allowSelfReg == 'false' ? '' : 'checked="checked" ') .' /> '. get_lang('No') .'
  1558. </label>';
  1559. $html .= '<label class="checkbox-inline">
  1560. <input type="radio" name="allowSelfReg" value="approval" id="allowSelfReg2" '. ($allowSelfReg == 'approval' ? '' : 'checked="checked" ') .' /> '. get_lang('AfterApproval') .'
  1561. </label>';
  1562. $html .= '</div>';
  1563. }
  1564. $html .= '</div>';
  1565. $html .= '</div>';
  1566. $html .= '<div class="form-group">';
  1567. $html .= '<label class="col-sm-6 control-label">'. get_lang('AllowSelfRegProf') .'</label>
  1568. <div class="col-sm-6">';
  1569. if ($installType == 'update') {
  1570. if ($allowSelfRegProf == 'true') {
  1571. $label = get_lang('Yes');
  1572. } else {
  1573. $label = get_lang('No');
  1574. }
  1575. $html .= '<input type="hidden" name="allowSelfRegProf" value="'. $allowSelfRegProf.'" />'. $label;
  1576. } else {
  1577. $html .= '<div class="control-group">
  1578. <label class="checkbox-inline">
  1579. <input type="radio" name="allowSelfRegProf" value="1" id="allowSelfRegProf1" '. ($allowSelfRegProf ? 'checked="checked" ' : '') .'/>
  1580. ' . get_lang('Yes') .'
  1581. </label>';
  1582. $html .= '<label class="checkbox-inline">
  1583. <input type="radio" name="allowSelfRegProf" value="0" id="allowSelfRegProf0" '. ($allowSelfRegProf ? '' : 'checked="checked" ') .' />
  1584. '. get_lang('No') .'
  1585. </label>';
  1586. $html .= '</div>';
  1587. }
  1588. $html .= '</div>
  1589. </div>';
  1590. echo panel($html, get_lang('Platform'), 'platform');
  1591. ?>
  1592. <div class='form-group'>
  1593. <div class="col-sm-6">
  1594. <button type="submit" class="btn btn-default pull-right" name="step3" value="&lt; <?php echo get_lang('Previous'); ?>" ><em class="fa fa-backward"> </em> <?php echo get_lang('Previous'); ?></button>
  1595. <input type="hidden" name="is_executable" id="is_executable" value="-" />
  1596. </div>
  1597. <div class="col-sm-6">
  1598. <button class="btn btn-success" type="submit" name="step5" value="<?php echo get_lang('Next'); ?> &gt;" ><em class="fa fa-forward"> </em> <?php echo get_lang('Next'); ?></button>
  1599. </div>
  1600. </div>
  1601. <?php
  1602. }
  1603. /**
  1604. * After installation is completed (step 6), this message is displayed.
  1605. * @param string $installType
  1606. */
  1607. function display_after_install_message($installType)
  1608. {
  1609. echo '<div class="RequirementContent">'.get_lang('FirstUseTip').'</div>';
  1610. echo '<div class="alert alert-warning">';
  1611. echo '<strong>'.get_lang('SecurityAdvice').'</strong>';
  1612. echo ': ';
  1613. printf(get_lang('ToProtectYourSiteMakeXReadOnlyAndDeleteY'), 'app/config/', 'main/install/');
  1614. echo '</div>';
  1615. ?></form>
  1616. <br />
  1617. <a class="btn btn-success btn-block" href="../../index.php">
  1618. <?php echo get_lang('GoToYourNewlyCreatedPortal'); ?>
  1619. </a>
  1620. <?php
  1621. }
  1622. /**
  1623. * This function return countries list from array (hardcoded)
  1624. * @param bool $combo (Optional) True for returning countries list with select html
  1625. * @return array|string countries list
  1626. */
  1627. function get_countries_list_from_array($combo = false)
  1628. {
  1629. $a_countries = array(
  1630. "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan",
  1631. "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
  1632. "Cambodia", "Cameroon", "Canada", "Cape Verde", "Central African Republic", "Chad", "Chile", "China", "Colombi", "Comoros", "Congo (Brazzaville)", "Congo", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic",
  1633. "Denmark", "Djibouti", "Dominica", "Dominican Republic",
  1634. "East Timor (Timor Timur)", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia",
  1635. "Fiji", "Finland", "France",
  1636. "Gabon", "Gambia, The", "Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana",
  1637. "Haiti", "Honduras", "Hungary",
  1638. "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy",
  1639. "Jamaica", "Japan", "Jordan",
  1640. "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan",
  1641. "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
  1642. "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Morocco", "Mozambique", "Myanmar",
  1643. "Namibia", "Nauru", "Nepa", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway",
  1644. "Oman",
  1645. "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland","Portugal",
  1646. "Qatar",
  1647. "Romania", "Russia", "Rwanda",
  1648. "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria",
  1649. "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu",
  1650. "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan",
  1651. "Vanuatu", "Vatican City", "Venezuela", "Vietnam",
  1652. "Yemen",
  1653. "Zambia", "Zimbabwe"
  1654. );
  1655. $country_select = '';
  1656. if ($combo) {
  1657. $country_select = '<select class="selectpicker show-tick" id="country" name="country">';
  1658. $country_select .= '<option value="">--- '.get_lang('SelectOne').' ---</option>';
  1659. foreach ($a_countries as $country) {
  1660. $country_select .= '<option value="'.$country.'">'.$country.'</option>';
  1661. }
  1662. $country_select .= '</select>';
  1663. return $country_select;
  1664. }
  1665. return $a_countries;
  1666. }
  1667. /**
  1668. * Lock settings that can't be changed in other portals
  1669. */
  1670. function lockSettings()
  1671. {
  1672. $access_url_locked_settings = api_get_locked_settings();
  1673. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1674. foreach ($access_url_locked_settings as $setting) {
  1675. $sql = "UPDATE $table SET access_url_locked = 1 WHERE variable = '$setting'";
  1676. Database::query($sql);
  1677. }
  1678. }
  1679. /**
  1680. * Update dir values
  1681. */
  1682. function updateDirAndFilesPermissions()
  1683. {
  1684. $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  1685. $permissions_for_new_directories = isset($_SESSION['permissions_for_new_directories']) ? $_SESSION['permissions_for_new_directories'] : 0770;
  1686. $permissions_for_new_files = isset($_SESSION['permissions_for_new_files']) ? $_SESSION['permissions_for_new_files'] : 0660;
  1687. // use decoct() to store as string
  1688. $sql = "UPDATE $table SET selected_value = '0" . decoct($permissions_for_new_directories) . "'
  1689. WHERE variable = 'permissions_for_new_directories'";
  1690. Database::query($sql);
  1691. $sql = "UPDATE $table SET selected_value = '0" . decoct($permissions_for_new_files) . "' WHERE variable = 'permissions_for_new_files'";
  1692. Database::query($sql);
  1693. if (isset($_SESSION['permissions_for_new_directories'])) {
  1694. unset($_SESSION['permissions_for_new_directories']);
  1695. }
  1696. if (isset($_SESSION['permissions_for_new_files'])) {
  1697. unset($_SESSION['permissions_for_new_files']);
  1698. }
  1699. }
  1700. /**
  1701. * @param $current_value
  1702. * @param $wanted_value
  1703. * @return string
  1704. */
  1705. function compare_setting_values($current_value, $wanted_value)
  1706. {
  1707. $current_value_string = $current_value;
  1708. $current_value = (float)$current_value;
  1709. $wanted_value = (float)$wanted_value;
  1710. if ($current_value >= $wanted_value) {
  1711. return Display::label($current_value_string, 'success');
  1712. } else {
  1713. return Display::label($current_value_string, 'important');
  1714. }
  1715. }
  1716. /**
  1717. * @param $course_dir
  1718. * @param $course_attempt_name
  1719. * @param string $file
  1720. * @return bool
  1721. */
  1722. function check_course_script_interpretation($course_dir, $course_attempt_name, $file = 'test.php')
  1723. {
  1724. $output = false;
  1725. //Write in file
  1726. $file_name = $course_dir.'/'.$file;
  1727. $content = '<?php echo "123"; exit;';
  1728. if (is_writable($file_name)) {
  1729. if ($handler = @fopen($file_name, "w")) {
  1730. //write content
  1731. if (fwrite($handler, $content)) {
  1732. $sock_errno = '';
  1733. $sock_errmsg = '';
  1734. $url = api_get_path(WEB_PATH).'app/courses/'.$course_attempt_name.'/'.$file;
  1735. $parsed_url = parse_url($url);
  1736. //$scheme = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'] : ''; //http
  1737. $host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  1738. // Patch if the host is the default host and is used through
  1739. // the IP address (sometimes the host is not taken correctly
  1740. // in this case)
  1741. if (empty($host) && !empty($_SERVER['HTTP_HOST'])) {
  1742. $host = $_SERVER['HTTP_HOST'];
  1743. $url = preg_replace('#:///#', '://'.$host.'/', $url);
  1744. }
  1745. $path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
  1746. $port = '';
  1747. $scheme = '';
  1748. switch ($parsed_url['scheme']) {
  1749. case 'https':
  1750. $scheme = 'ssl://';
  1751. $port = 443;
  1752. break;
  1753. case 'http':
  1754. default:
  1755. $scheme = '';
  1756. $port = 80;
  1757. }
  1758. //Check fsockopen (not sure it works with https). If that is your case, you might want to try the
  1759. // suggestion at https://support.chamilo.org/issues/8260#note-3 (although it ignores SSL peer checks)
  1760. if ($fp = @fsockopen(str_replace('http://', $scheme, $url), $port, $sock_errno, $sock_errmsg, 60)) {
  1761. $out = "GET $path HTTP/1.1\r\n";
  1762. $out .= "Host: $host\r\n";
  1763. $out .= "Connection: Close\r\n\r\n";
  1764. fwrite($fp, $out);
  1765. while (!feof($fp)) {
  1766. $result = str_replace("\r\n", '',fgets($fp, 128));
  1767. if (!empty($result) && $result == '123') {
  1768. $output = true;
  1769. }
  1770. }
  1771. fclose($fp);
  1772. //Check allow_url_fopen
  1773. } elseif (ini_get('allow_url_fopen')) {
  1774. if ($fp = @fopen($url, 'r')) {
  1775. while ($result = fgets($fp, 1024)) {
  1776. if (!empty($result) && $result == '123') {
  1777. $output = true;
  1778. }
  1779. }
  1780. fclose($fp);
  1781. }
  1782. // Check if has support for cURL
  1783. } elseif (function_exists('curl_init')) {
  1784. $ch = curl_init();
  1785. curl_setopt($ch, CURLOPT_HEADER, 0);
  1786. curl_setopt($ch, CURLOPT_URL, $url);
  1787. //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  1788. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1789. $result = curl_exec ($ch);
  1790. if (!empty($result) && $result == '123') {
  1791. $output = true;
  1792. }
  1793. curl_close($ch);
  1794. }
  1795. }
  1796. @fclose($handler);
  1797. }
  1798. }
  1799. return $output;
  1800. }
  1801. /**
  1802. * Save settings values
  1803. *
  1804. * @param string $organizationName
  1805. * @param string $organizationUrl
  1806. * @param string $siteName
  1807. * @param string $adminEmail
  1808. * @param string $adminLastName
  1809. * @param string $adminFirstName
  1810. * @param string $language
  1811. * @param string $allowRegistration
  1812. * @param string $allowTeacherSelfRegistration
  1813. * @param string $installationProfile The name of an installation profile file in main/install/profiles/
  1814. */
  1815. function installSettings(
  1816. $organizationName,
  1817. $organizationUrl,
  1818. $siteName,
  1819. $adminEmail,
  1820. $adminLastName,
  1821. $adminFirstName,
  1822. $language,
  1823. $allowRegistration,
  1824. $allowTeacherSelfRegistration,
  1825. $installationProfile = ''
  1826. ) {
  1827. $allowTeacherSelfRegistration = $allowTeacherSelfRegistration ? 'true' : 'false';
  1828. // Use PHP 5.3 to avoid issue with weird peripherical auto-installers like travis-ci
  1829. $settings = array(
  1830. 'Institution' => $organizationName,
  1831. 'InstitutionUrl' => $organizationUrl,
  1832. 'siteName' => $siteName,
  1833. 'emailAdministrator' => $adminEmail,
  1834. 'administratorSurname' => $adminLastName,
  1835. 'administratorName' => $adminFirstName,
  1836. 'platformLanguage' => $language,
  1837. 'allow_registration' => $allowRegistration,
  1838. 'allow_registration_as_teacher' => $allowTeacherSelfRegistration,
  1839. );
  1840. foreach ($settings as $variable => $value) {
  1841. $sql = "UPDATE settings_current
  1842. SET selected_value = '$value'
  1843. WHERE variable = '$variable'";
  1844. Database::query($sql);
  1845. }
  1846. installProfileSettings($installationProfile);
  1847. }
  1848. /**
  1849. * Executes DB changes based in the classes defined in
  1850. * src/Chamilo/CoreBundle/Migrations/Schema/*
  1851. *
  1852. * @param string $chamiloVersion
  1853. * @param EntityManager $manager
  1854. * @throws \Doctrine\DBAL\DBALException
  1855. */
  1856. function migrate($chamiloVersion, EntityManager $manager)
  1857. {
  1858. $debug = true;
  1859. $connection = $manager->getConnection();
  1860. $config = new \Doctrine\DBAL\Migrations\Configuration\Configuration($connection);
  1861. // Table name that will store migrations log (will be created automatically,
  1862. // default name is: doctrine_migration_versions)
  1863. $config->setMigrationsTableName('version');
  1864. // Namespace of your migration classes, do not forget escape slashes, do not add last slash
  1865. $config->setMigrationsNamespace('Application\Migrations\Schema\V'.$chamiloVersion);
  1866. // Directory where your migrations are located
  1867. $config->setMigrationsDirectory(api_get_path(SYS_PATH).'app/Migrations/Schema/V'.$chamiloVersion);
  1868. // Load your migrations
  1869. $config->registerMigrationsFromDirectory($config->getMigrationsDirectory());
  1870. $migration = new \Doctrine\DBAL\Migrations\Migration($config);
  1871. $versions = $config->getMigrations();
  1872. /** @var Doctrine\DBAL\Migrations\Version $migrationItem */
  1873. foreach ($versions as $version) {
  1874. $version->getMigration()->setEntityManager($manager);
  1875. }
  1876. $to = null; // if $to == null then schema will be migrated to latest version
  1877. echo "<pre>";
  1878. try {
  1879. // Execute migration!
  1880. $migratedSQL = $migration->migrate($to);
  1881. if ($debug) {
  1882. foreach ($migratedSQL as $version => $sqlList) {
  1883. echo "VERSION: $version<br>";
  1884. echo "----------------------------------------------<br>";
  1885. $total = count($sqlList);
  1886. error_log("VERSION: $version");
  1887. error_log("# queries: ".$total);
  1888. $counter = 1;
  1889. foreach ($sqlList as $sql) {
  1890. echo "<code>$sql</code><br>";
  1891. error_log("$counter/$total : $sql");
  1892. $counter++;
  1893. }
  1894. }
  1895. echo "<br>DONE!<br>";
  1896. }
  1897. return true;
  1898. } catch (Exception $ex) {
  1899. if ($debug) {
  1900. echo "ERROR: {$ex->getMessage()}<br>";
  1901. return false;
  1902. }
  1903. }
  1904. echo "</pre>";
  1905. return false;
  1906. }
  1907. /**
  1908. * @param EntityManager $em
  1909. *
  1910. * @throws \Doctrine\DBAL\DBALException
  1911. */
  1912. function fixIds(EntityManager $em)
  1913. {
  1914. $debug = true;
  1915. $connection = $em->getConnection();
  1916. if ($debug) {
  1917. error_log('fixIds');
  1918. }
  1919. // Create temporary indexes to increase speed of the following operations
  1920. // Adding and removing indexes will usually take much less time than
  1921. // the execution without indexes of the queries in this function, particularly
  1922. // for large tables
  1923. $sql = "ALTER TABLE c_document ADD INDEX tmpidx_doc(c_id, id)";
  1924. $connection->executeQuery($sql);
  1925. $sql = "ALTER TABLE c_student_publication ADD INDEX tmpidx_stud (c_id, id)";
  1926. $connection->executeQuery($sql);
  1927. $sql = "ALTER TABLE c_quiz ADD INDEX tmpidx_quiz (c_id, id)";
  1928. $connection->executeQuery($sql);
  1929. $sql = "ALTER TABLE c_item_property ADD INDEX tmpidx_ip (to_group_id)";
  1930. $connection->executeQuery($sql);
  1931. $sql = "SELECT * FROM c_lp_item";
  1932. $result = $connection->fetchAll($sql);
  1933. foreach ($result as $item) {
  1934. $courseId = $item['c_id'];
  1935. $iid = isset($item['iid']) ? intval($item['iid']) : 0;
  1936. $ref = isset($item['ref']) ? intval($item['ref']) : 0;
  1937. $sql = null;
  1938. $newId = '';
  1939. switch ($item['item_type']) {
  1940. case TOOL_LINK:
  1941. $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref";
  1942. $data = $connection->fetchAssoc($sql);
  1943. if ($data) {
  1944. $newId = $data['iid'];
  1945. }
  1946. break;
  1947. case TOOL_STUDENTPUBLICATION:
  1948. $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
  1949. $data = $connection->fetchAssoc($sql);
  1950. if ($data) {
  1951. $newId = $data['iid'];
  1952. }
  1953. break;
  1954. case TOOL_QUIZ:
  1955. $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
  1956. $data = $connection->fetchAssoc($sql);
  1957. if ($data) {
  1958. $newId = $data['iid'];
  1959. }
  1960. break;
  1961. case TOOL_DOCUMENT:
  1962. $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
  1963. $data = $connection->fetchAssoc($sql);
  1964. if ($data) {
  1965. $newId = $data['iid'];
  1966. }
  1967. break;
  1968. case TOOL_FORUM:
  1969. $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND forum_id = $ref";
  1970. $data = $connection->fetchAssoc($sql);
  1971. if ($data) {
  1972. $newId = $data['iid'];
  1973. }
  1974. break;
  1975. case 'thread':
  1976. $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
  1977. $data = $connection->fetchAssoc($sql);
  1978. if ($data) {
  1979. $newId = $data['iid'];
  1980. }
  1981. break;
  1982. }
  1983. if (!empty($sql) && !empty($newId) && !empty($iid)) {
  1984. $sql = "UPDATE c_lp_item SET ref = $newId WHERE iid = $iid";
  1985. $connection->executeQuery($sql);
  1986. }
  1987. }
  1988. // Set NULL if session = 0
  1989. $sql = "UPDATE c_item_property SET session_id = NULL WHERE session_id = 0";
  1990. $connection->executeQuery($sql);
  1991. // Set NULL if group = 0
  1992. $sql = "UPDATE c_item_property SET to_group_id = NULL WHERE to_group_id = 0";
  1993. $connection->executeQuery($sql);
  1994. // Set NULL if insert_user_id = 0
  1995. $sql = "UPDATE c_item_property SET insert_user_id = NULL WHERE insert_user_id = 0";
  1996. $connection->executeQuery($sql);
  1997. // Delete session data of sessions that don't exist.
  1998. $sql = "DELETE FROM c_item_property
  1999. WHERE session_id IS NOT NULL AND session_id NOT IN (SELECT id FROM session)";
  2000. $connection->executeQuery($sql);
  2001. // Delete group data of groups that don't exist.
  2002. $sql = "DELETE FROM c_item_property
  2003. WHERE to_group_id IS NOT NULL AND to_group_id NOT IN (SELECT DISTINCT id FROM c_group_info)";
  2004. $connection->executeQuery($sql);
  2005. // This updates the group_id with c_group_info.iid instead of c_group_info.id
  2006. if ($debug) {
  2007. error_log('update iids');
  2008. }
  2009. $groupTableToFix = [
  2010. 'c_group_rel_user',
  2011. 'c_group_rel_tutor',
  2012. 'c_permission_group',
  2013. 'c_role_group',
  2014. 'c_survey_invitation',
  2015. 'c_attendance_calendar_rel_group'
  2016. ];
  2017. foreach ($groupTableToFix as $table) {
  2018. $sql = "SELECT * FROM $table";
  2019. $result = $connection->fetchAll($sql);
  2020. foreach ($result as $item) {
  2021. $iid = $item['iid'];
  2022. $courseId = $item['c_id'];
  2023. $groupId = intval($item['group_id']);
  2024. // Fix group id
  2025. if (!empty($groupId)) {
  2026. $sql = "SELECT * FROM c_group_info
  2027. WHERE c_id = $courseId AND id = $groupId
  2028. LIMIT 1";
  2029. $data = $connection->fetchAssoc($sql);
  2030. if (!empty($data)) {
  2031. $newGroupId = $data['iid'];
  2032. $sql = "UPDATE $table SET group_id = $newGroupId
  2033. WHERE iid = $iid";
  2034. $connection->executeQuery($sql);
  2035. } else {
  2036. // The group does not exists clean this record
  2037. $sql = "DELETE FROM $table WHERE iid = $iid";
  2038. $connection->executeQuery($sql);
  2039. }
  2040. }
  2041. }
  2042. }
  2043. // Fix c_item_property
  2044. if ($debug) {
  2045. error_log('update c_item_property');
  2046. }
  2047. $sql = "SELECT * FROM course";
  2048. $courseList = $connection->fetchAll($sql);
  2049. if ($debug) {
  2050. error_log('Getting course list');
  2051. }
  2052. $totalCourse = count($courseList);
  2053. $counter = 0;
  2054. foreach ($courseList as $courseData) {
  2055. $courseId = $courseData['id'];
  2056. if ($debug) {
  2057. error_log('Updating course: '.$courseData['code']);
  2058. }
  2059. $sql = "SELECT * FROM c_item_property WHERE c_id = $courseId";
  2060. $result = $connection->fetchAll($sql);
  2061. foreach ($result as $item) {
  2062. //$courseId = $item['c_id'];
  2063. $sessionId = intval($item['session_id']);
  2064. $groupId = intval($item['to_group_id']);
  2065. $iid = $item['iid'];
  2066. $ref = $item['ref'];
  2067. // Fix group id
  2068. if (!empty($groupId)) {
  2069. $sql = "SELECT * FROM c_group_info
  2070. WHERE c_id = $courseId AND id = $groupId";
  2071. $data = $connection->fetchAssoc($sql);
  2072. if (!empty($data)) {
  2073. $newGroupId = $data['iid'];
  2074. $sql = "UPDATE c_item_property SET to_group_id = $newGroupId
  2075. WHERE iid = $iid";
  2076. $connection->executeQuery($sql);
  2077. } else {
  2078. // The group does not exists clean this record
  2079. $sql = "DELETE FROM c_item_property WHERE iid = $iid";
  2080. $connection->executeQuery($sql);
  2081. }
  2082. }
  2083. $sql = '';
  2084. $newId = '';
  2085. switch ($item['tool']) {
  2086. case TOOL_LINK:
  2087. $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
  2088. break;
  2089. case TOOL_STUDENTPUBLICATION:
  2090. $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
  2091. break;
  2092. case TOOL_QUIZ:
  2093. $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
  2094. break;
  2095. case TOOL_DOCUMENT:
  2096. $sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
  2097. break;
  2098. case TOOL_FORUM:
  2099. $sql = "SELECT * FROM c_forum_forum WHERE c_id = $courseId AND id = $ref";
  2100. break;
  2101. case 'thread':
  2102. $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND id = $ref";
  2103. break;
  2104. }
  2105. if (!empty($sql) && !empty($newId)) {
  2106. $data = $connection->fetchAssoc($sql);
  2107. if (isset($data['iid'])) {
  2108. $newId = $data['iid'];
  2109. }
  2110. $sql = "UPDATE c_item_property SET ref = $newId WHERE iid = $iid";
  2111. error_log($sql);
  2112. $connection->executeQuery($sql);
  2113. }
  2114. if ($debug) {
  2115. // Print a status in the log once in a while
  2116. error_log("Process item #$counter/$totalCourse");
  2117. }
  2118. $counter++;
  2119. }
  2120. }
  2121. if ($debug) {
  2122. error_log('update gradebook_link');
  2123. }
  2124. // Fix gradebook_link
  2125. $sql = "SELECT * FROM gradebook_link";
  2126. $result = $connection->fetchAll($sql);
  2127. foreach ($result as $item) {
  2128. $courseCode = $item['course_code'];
  2129. $courseInfo = api_get_course_info($courseCode);
  2130. if (empty($courseInfo)) {
  2131. continue;
  2132. }
  2133. $courseId = $courseInfo['real_id'];
  2134. $ref = $item['ref_id'];
  2135. $iid = $item['id'];
  2136. $sql = '';
  2137. switch ($item['type']) {
  2138. case LINK_LEARNPATH:
  2139. $sql = "SELECT * FROM c_link WHERE c_id = $courseId AND id = $ref ";
  2140. break;
  2141. case LINK_STUDENTPUBLICATION:
  2142. $sql = "SELECT * FROM c_student_publication WHERE c_id = $courseId AND id = $ref";
  2143. break;
  2144. case LINK_EXERCISE:
  2145. $sql = "SELECT * FROM c_quiz WHERE c_id = $courseId AND id = $ref";
  2146. break;
  2147. case LINK_ATTENDANCE:
  2148. //$sql = "SELECT * FROM c_document WHERE c_id = $courseId AND id = $ref";
  2149. break;
  2150. case LINK_FORUM_THREAD:
  2151. $sql = "SELECT * FROM c_forum_thread WHERE c_id = $courseId AND thread_id = $ref";
  2152. break;
  2153. }
  2154. if (!empty($sql)) {
  2155. $data = $connection->fetchAssoc($sql);
  2156. if (isset($data) && isset($data['iid'])) {
  2157. $newId = $data['iid'];
  2158. $sql = "UPDATE gradebook_link SET ref_id = $newId
  2159. WHERE id = $iid";
  2160. $connection->executeQuery($sql);
  2161. }
  2162. }
  2163. }
  2164. if ($debug) {
  2165. error_log('update groups');
  2166. }
  2167. $sql = "SELECT * FROM groups";
  2168. $result = $connection->executeQuery($sql);
  2169. $groups = $result->fetchAll();
  2170. $oldGroups = array();
  2171. if (!empty($groups)) {
  2172. foreach ($groups as $group) {
  2173. if (empty($group['name'])) {
  2174. continue;
  2175. }
  2176. /*$group['description'] = Database::escape_string($group['description']);
  2177. $group['name'] = Database::escape_string($group['name']);
  2178. $sql = "INSERT INTO usergroup (name, group_type, description, picture, url, visibility, updated_at, created_at)
  2179. VALUES ('{$group['name']}', '1', '{$group['description']}', '{$group['picture_uri']}', '{$group['url']}', '{$group['visibility']}', '{$group['updated_on']}', '{$group['created_on']}')";
  2180. */
  2181. $params = [
  2182. 'name' => $group['name'],
  2183. 'description' => $group['description'],
  2184. 'group_type' => 1,
  2185. 'picture' => $group['picture_uri'],
  2186. 'url' => $group['url'],
  2187. 'visibility' => $group['visibility'],
  2188. 'updated_at' => $group['updated_on'],
  2189. 'created_at' => $group['created_on']
  2190. ];
  2191. $connection->insert('usergroup', $params);
  2192. //$connection->executeQuery($sql);
  2193. $id = $connection->lastInsertId('id');
  2194. $oldGroups[$group['id']] = $id;
  2195. }
  2196. }
  2197. if (!empty($oldGroups)) {
  2198. error_log('Moving group files');
  2199. foreach ($oldGroups as $oldId => $newId) {
  2200. $path = get_group_picture_path_by_id(
  2201. $oldId,
  2202. 'system'
  2203. );
  2204. if (!empty($path)) {
  2205. $newPath = str_replace(
  2206. "groups/$oldId/",
  2207. "groups/$newId/",
  2208. $path['dir']
  2209. );
  2210. $command = "mv {$path['dir']} $newPath ";
  2211. error_log("Executing $command");
  2212. system($command);
  2213. }
  2214. }
  2215. $sql = "SELECT * FROM group_rel_user";
  2216. $result = $connection->executeQuery($sql);
  2217. $dataList = $result->fetchAll();
  2218. if (!empty($dataList)) {
  2219. foreach ($dataList as $data) {
  2220. if (isset($oldGroups[$data['group_id']])) {
  2221. $data['group_id'] = $oldGroups[$data['group_id']];
  2222. $userId = $data['user_id'];
  2223. $sql = "SELECT id FROM user WHERE user_id = $userId";
  2224. $userResult = $connection->executeQuery($sql);
  2225. $userInfo = $userResult->fetch();
  2226. if (empty($userInfo)) {
  2227. continue;
  2228. }
  2229. $sql = "INSERT INTO usergroup_rel_user (usergroup_id, user_id, relation_type)
  2230. VALUES ('{$data['group_id']}', '{$userId}', '{$data['relation_type']}')";
  2231. $connection->executeQuery($sql);
  2232. }
  2233. }
  2234. }
  2235. $sql = "SELECT * FROM group_rel_group";
  2236. $result = $connection->executeQuery($sql);
  2237. $dataList = $result->fetchAll();
  2238. if (!empty($dataList)) {
  2239. foreach ($dataList as $data) {
  2240. if (isset($oldGroups[$data['group_id']]) && isset($oldGroups[$data['subgroup_id']])) {
  2241. $data['group_id'] = $oldGroups[$data['group_id']];
  2242. $data['subgroup_id'] = $oldGroups[$data['subgroup_id']];
  2243. $sql = "INSERT INTO usergroup_rel_usergroup (group_id, subgroup_id, relation_type)
  2244. VALUES ('{$data['group_id']}', '{$data['subgroup_id']}', '{$data['relation_type']}')";
  2245. $connection->executeQuery($sql);
  2246. }
  2247. }
  2248. }
  2249. $sql = "SELECT * FROM announcement_rel_group";
  2250. $result = $connection->executeQuery($sql);
  2251. $dataList = $result->fetchAll();
  2252. if (!empty($dataList)) {
  2253. foreach ($dataList as $data) {
  2254. if (isset($oldGroups[$data['group_id']])) {
  2255. // Deleting relation
  2256. $sql = "DELETE FROM announcement_rel_group WHERE group_id = {$data['group_id']}";
  2257. $connection->executeQuery($sql);
  2258. // Add new relation
  2259. $data['group_id'] = $oldGroups[$data['group_id']];
  2260. $sql = "INSERT INTO announcement_rel_group(group_id, announcement_id)
  2261. VALUES ('{$data['group_id']}', '{$data['announcement_id']}')";
  2262. $connection->executeQuery($sql);
  2263. }
  2264. }
  2265. }
  2266. $sql = "SELECT * FROM group_rel_tag";
  2267. $result = $connection->executeQuery($sql);
  2268. $dataList = $result->fetchAll();
  2269. if (!empty($dataList)) {
  2270. foreach ($dataList as $data) {
  2271. if (isset($oldGroups[$data['group_id']])) {
  2272. $data['group_id'] = $oldGroups[$data['group_id']];
  2273. $sql = "INSERT INTO usergroup_rel_tag (tag_id, usergroup_id)
  2274. VALUES ('{$data['tag_id']}', '{$data['group_id']}')";
  2275. $connection->executeQuery($sql);
  2276. }
  2277. }
  2278. }
  2279. }
  2280. if ($debug) {
  2281. error_log('update extra fields');
  2282. }
  2283. // Extra fields
  2284. $extraFieldTables = [
  2285. ExtraField::USER_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_USER_FIELD),
  2286. ExtraField::COURSE_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
  2287. //ExtraField::LP_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_LP_FIELD),
  2288. ExtraField::SESSION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
  2289. //ExtraField::CALENDAR_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
  2290. //ExtraField::QUESTION_FIELD_TYPE => Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_FIELD),
  2291. //ExtraField::USER_FIELD_TYPE => //Database::get_main_table(TABLE_MAIN_SPECIFIC_FIELD),
  2292. ];
  2293. foreach ($extraFieldTables as $type => $table) {
  2294. $sql = "SELECT * FROM $table ";
  2295. if ($debug) {
  2296. error_log($sql);
  2297. }
  2298. $result = $connection->query($sql);
  2299. $fields = $result->fetchAll();
  2300. foreach ($fields as $field) {
  2301. if ($debug) {
  2302. error_log("Loading field: ".$field['field_variable']);
  2303. }
  2304. $originalId = $field['id'];
  2305. $extraField = new ExtraField();
  2306. $extraField
  2307. ->setExtraFieldType($type)
  2308. ->setVariable($field['field_variable'])
  2309. ->setFieldType($field['field_type'])
  2310. ->setDisplayText($field['field_display_text'])
  2311. ->setDefaultValue($field['field_default_value'])
  2312. ->setFieldOrder($field['field_order'])
  2313. ->setVisible($field['field_visible'])
  2314. ->setChangeable($field['field_changeable'])
  2315. ->setFilter($field['field_filter']);
  2316. $em->persist($extraField);
  2317. $em->flush();
  2318. $values = array();
  2319. $handlerId = null;
  2320. switch ($type) {
  2321. case ExtraField::USER_FIELD_TYPE:
  2322. $optionTable = Database::get_main_table(
  2323. TABLE_MAIN_USER_FIELD_OPTIONS
  2324. );
  2325. $valueTable = Database::get_main_table(
  2326. TABLE_MAIN_USER_FIELD_VALUES
  2327. );
  2328. $handlerId = 'user_id';
  2329. break;
  2330. case ExtraField::COURSE_FIELD_TYPE:
  2331. $optionTable = Database::get_main_table(
  2332. TABLE_MAIN_COURSE_FIELD_OPTIONS
  2333. );
  2334. $valueTable = Database::get_main_table(
  2335. TABLE_MAIN_COURSE_FIELD_VALUES
  2336. );
  2337. $handlerId = 'c_id';
  2338. break;
  2339. case ExtraField::SESSION_FIELD_TYPE:
  2340. $optionTable = Database::get_main_table(
  2341. TABLE_MAIN_SESSION_FIELD_OPTIONS
  2342. );
  2343. $valueTable = Database::get_main_table(
  2344. TABLE_MAIN_SESSION_FIELD_VALUES
  2345. );
  2346. $handlerId = 'session_id';
  2347. break;
  2348. }
  2349. if (!empty($optionTable)) {
  2350. $sql = "SELECT * FROM $optionTable WHERE field_id = $originalId ";
  2351. $result = $connection->query($sql);
  2352. $options = $result->fetchAll();
  2353. foreach ($options as $option) {
  2354. $extraFieldOption = new ExtraFieldOptions();
  2355. $extraFieldOption
  2356. ->setDisplayText($option['option_display_text'])
  2357. ->setField($extraField)
  2358. ->setOptionOrder($option['option_order'])
  2359. ->setValue($option['option_value']);
  2360. $em->persist($extraFieldOption);
  2361. $em->flush();
  2362. }
  2363. $sql = "SELECT * FROM $valueTable WHERE field_id = $originalId ";
  2364. $result = $connection->query($sql);
  2365. $values = $result->fetchAll();
  2366. if ($debug) {
  2367. error_log("Fetch all values for field");
  2368. }
  2369. }
  2370. if (!empty($values)) {
  2371. if ($debug) {
  2372. error_log("Saving field value in new table");
  2373. }
  2374. $k = 0;
  2375. foreach ($values as $value) {
  2376. if (isset($value[$handlerId])) {
  2377. /*
  2378. $extraFieldValue = new ExtraFieldValues();
  2379. $extraFieldValue
  2380. ->setValue($value['field_value'])
  2381. ->setField($extraField)
  2382. ->setItemId($value[$handlerId]);
  2383. $em->persist($extraFieldValue);
  2384. $em->flush();
  2385. */
  2386. // Insert without the use of the entity as it reduces
  2387. // speed to 2 records per second (much too slow)
  2388. $params = [
  2389. 'field_id' => $extraField->getId(),
  2390. 'value' => $value['field_value'],
  2391. 'item_id' => $value[$handlerId]
  2392. ];
  2393. $connection->insert('extra_field_values', $params);
  2394. if ($debug && ($k % 10000 == 0)) {
  2395. error_log("Saving field $k");
  2396. }
  2397. $k++;
  2398. }
  2399. }
  2400. }
  2401. }
  2402. }
  2403. if ($debug) {
  2404. error_log('Remove index');
  2405. }
  2406. // Drop temporary indexes added to increase speed of this function's queries
  2407. $sql = "ALTER TABLE c_document DROP INDEX tmpidx_doc";
  2408. $connection->executeQuery($sql);
  2409. $sql = "ALTER TABLE c_student_publication DROP INDEX tmpidx_stud";
  2410. $connection->executeQuery($sql);
  2411. $sql = "ALTER TABLE c_quiz DROP INDEX tmpidx_quiz";
  2412. $connection->executeQuery($sql);
  2413. $sql = "ALTER TABLE c_item_property DROP INDEX tmpidx_ip";
  2414. $connection->executeQuery($sql);
  2415. if ($debug) {
  2416. error_log('Finish fixId function');
  2417. }
  2418. }
  2419. /**
  2420. *
  2421. * After the schema was created (table creation), the function adds
  2422. * admin/platform information.
  2423. *
  2424. * @param EntityManager $manager
  2425. * @param string $sysPath
  2426. * @param string $encryptPassForm
  2427. * @param string $passForm
  2428. * @param string $adminLastName
  2429. * @param string $adminFirstName
  2430. * @param string $loginForm
  2431. * @param string $emailForm
  2432. * @param string $adminPhoneForm
  2433. * @param string $languageForm
  2434. * @param string $institutionForm
  2435. * @param string $institutionUrlForm
  2436. * @param string $siteName
  2437. * @param string $allowSelfReg
  2438. * @param string $allowSelfRegProf
  2439. * @param string $installationProfile Installation profile, if any was provided
  2440. */
  2441. function finishInstallation(
  2442. $manager,
  2443. $sysPath,
  2444. $encryptPassForm,
  2445. $passForm,
  2446. $adminLastName,
  2447. $adminFirstName,
  2448. $loginForm,
  2449. $emailForm,
  2450. $adminPhoneForm,
  2451. $languageForm,
  2452. $institutionForm,
  2453. $institutionUrlForm,
  2454. $siteName,
  2455. $allowSelfReg,
  2456. $allowSelfRegProf,
  2457. $installationProfile = ''
  2458. ) {
  2459. $sysPath = !empty($sysPath) ? $sysPath : api_get_path(SYS_PATH);
  2460. // Inserting data
  2461. $data = file_get_contents($sysPath.'main/install/data.sql');
  2462. $result = $manager->getConnection()->prepare($data);
  2463. $result->execute();
  2464. $result->closeCursor();
  2465. UserManager::setPasswordEncryption($encryptPassForm);
  2466. // Create admin user.
  2467. @UserManager::create_user(
  2468. $adminFirstName,
  2469. $adminLastName,
  2470. 1,
  2471. $emailForm,
  2472. $loginForm,
  2473. $passForm,
  2474. 'ADMIN', //$official_code = '',
  2475. $languageForm,
  2476. $adminPhoneForm,
  2477. '', //$picture_uri = '',
  2478. PLATFORM_AUTH_SOURCE,
  2479. '',//$expirationDate,
  2480. 1,
  2481. 0,
  2482. null,
  2483. '',
  2484. false, //$send_mail = false,
  2485. true //$isAdmin = false
  2486. );
  2487. // Create anonymous user.
  2488. @UserManager::create_user(
  2489. 'Joe',
  2490. 'Anonymous',
  2491. 6,
  2492. 'anonymous@localhost',
  2493. 'anon',
  2494. 'anon',
  2495. 'anonymous', //$official_code = '',
  2496. $languageForm,
  2497. '',
  2498. '', //$picture_uri = '',
  2499. PLATFORM_AUTH_SOURCE,
  2500. '',
  2501. 1,
  2502. 0,
  2503. null,
  2504. '',
  2505. false, //$send_mail = false,
  2506. false //$isAdmin = false
  2507. );
  2508. // Set default language
  2509. $sql = "UPDATE language SET available = 1 WHERE dokeos_folder = '$languageForm'";
  2510. Database::query($sql);
  2511. // Install settings
  2512. installSettings(
  2513. $institutionForm,
  2514. $institutionUrlForm,
  2515. $siteName,
  2516. $emailForm,
  2517. $adminLastName,
  2518. $adminFirstName,
  2519. $languageForm,
  2520. $allowSelfReg,
  2521. $allowSelfRegProf,
  2522. $installationProfile
  2523. );
  2524. lockSettings();
  2525. updateDirAndFilesPermissions();
  2526. // Set the latest version
  2527. $path = api_get_path(SYS_PATH).'app/Migrations/Schema/V111/';
  2528. $finder = new \Symfony\Component\Finder\Finder();
  2529. $files = $finder->files()->in($path);
  2530. foreach ($files as $version) {
  2531. $version = str_replace(['Version', '.php' ], '', $version->getFilename());
  2532. $sql = "INSERT INTO version (version) VALUES ('$version')";
  2533. Database::query($sql);
  2534. }
  2535. }
  2536. /**
  2537. * Update settings based on installation profile defined in a JSON file
  2538. * @param string $installationProfile The name of the JSON file in main/install/profiles/ folder
  2539. *
  2540. * @return bool false on failure (no bad consequences anyway, just ignoring profile)
  2541. */
  2542. function installProfileSettings($installationProfile = '')
  2543. {
  2544. if (empty($installationProfile)) {
  2545. return false;
  2546. }
  2547. $jsonPath = api_get_path(SYS_PATH).'main/install/profiles/'.$installationProfile.'.json';
  2548. // Make sure the path to the profile is not hacked
  2549. if (!Security::check_abs_path($jsonPath, api_get_path(SYS_PATH).'main/install/profiles/')) {
  2550. return false;
  2551. }
  2552. if (!is_file($jsonPath)) {
  2553. return false;
  2554. }
  2555. if (!is_readable($jsonPath)) {
  2556. return false;
  2557. }
  2558. if (!function_exists('json_decode')) {
  2559. // The php-json extension is not available. Ignore profile.
  2560. return false;
  2561. }
  2562. $json = file_get_contents($jsonPath);
  2563. $params = json_decode($json);
  2564. if ($params === false or $params === null) {
  2565. return false;
  2566. }
  2567. $settings = $params->params;
  2568. if (!empty($params->parent)) {
  2569. installProfileSettings($params->parent);
  2570. }
  2571. foreach ($settings as $id => $param) {
  2572. $sql = "UPDATE settings_current
  2573. SET selected_value = '".$param->selected_value."'
  2574. WHERE variable = '".$param->variable."'";
  2575. if (!empty($param->subkey)) {
  2576. $sql .= " AND subkey='" . $param->subkey . "'";
  2577. }
  2578. Database::query($sql);
  2579. }
  2580. return true;
  2581. }
  2582. /**
  2583. * Quick function to remove a directory with its subdirectories
  2584. * @param $dir
  2585. */
  2586. function rrmdir($dir)
  2587. {
  2588. if (is_dir($dir)) {
  2589. $objects = scandir($dir);
  2590. foreach ($objects as $object) {
  2591. if ($object != "." && $object != "..") {
  2592. if (filetype($dir."/".$object) == "dir") {
  2593. @rrmdir($dir."/".$object);
  2594. } else {
  2595. @unlink($dir."/".$object);
  2596. }
  2597. }
  2598. }
  2599. reset($objects);
  2600. rmdir($dir);
  2601. }
  2602. }
  2603. function get_group_picture_path_by_id($id, $type = 'web', $preview = false, $anonymous = false)
  2604. {
  2605. switch ($type) {
  2606. case 'system': // Base: absolute system path.
  2607. $base = api_get_path(SYS_UPLOAD_PATH);
  2608. break;
  2609. case 'web': // Base: absolute web path.
  2610. default:
  2611. $base = api_get_path(WEB_UPLOAD_PATH);
  2612. break;
  2613. }
  2614. $noPicturePath = array('dir' => $base.'img/', 'file' => 'unknown.jpg');
  2615. if (empty($id) || empty($type)) {
  2616. return $anonymous ? $noPicturePath : array('dir' => '', 'file' => '');
  2617. }
  2618. $id = intval($id);
  2619. //$group_table = Database :: get_main_table(TABLE_MAIN_GROUP);
  2620. $group_table = 'groups';
  2621. $sql = "SELECT picture_uri FROM $group_table WHERE id=".$id;
  2622. $res = Database::query($sql);
  2623. if (!Database::num_rows($res)) {
  2624. return $anonymous ? $noPicturePath : array('dir' => '', 'file' => '');
  2625. }
  2626. $user = Database::fetch_array($res);
  2627. $picture_filename = trim($user['picture_uri']);
  2628. if (api_get_setting('split_users_upload_directory') === 'true') {
  2629. if (!empty($picture_filename)) {
  2630. $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
  2631. } elseif ($preview) {
  2632. $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
  2633. } else {
  2634. $dir = $base.'groups/'.$id.'/';
  2635. }
  2636. } else {
  2637. $dir = $base.'groups/'.$id.'/';
  2638. }
  2639. if (empty($picture_filename) && $anonymous) {
  2640. return $noPicturePath;
  2641. }
  2642. return array('dir' => $dir, 'file' => $picture_filename);
  2643. }
  2644. /**
  2645. * @param string $fromVersion
  2646. * @param EntityManager $manager
  2647. * @param bool $processFiles
  2648. */
  2649. function migrateSwitch($fromVersion, $manager, $processFiles = true)
  2650. {
  2651. error_log('Starting migration process from '.$fromVersion.' ('.date('Y-m-d H:i:s').')');
  2652. echo '<a class="btn btn-default" href="javascript:void(0)" id="details_button">'.get_lang('Details').'</a><br />';
  2653. echo '<div id="details" style="display:none">';
  2654. $connection = $manager->getConnection();
  2655. switch ($fromVersion) {
  2656. case '1.9.0':
  2657. case '1.9.2':
  2658. case '1.9.4':
  2659. case '1.9.6':
  2660. case '1.9.6.1':
  2661. case '1.9.8':
  2662. case '1.9.8.1':
  2663. case '1.9.8.2':
  2664. case '1.9.10':
  2665. case '1.9.10.2':
  2666. case '1.9.10.4':
  2667. // Fix type "enum" before running the migration with Doctrine
  2668. $connection->executeQuery("ALTER TABLE course_category MODIFY COLUMN auth_course_child VARCHAR(40) DEFAULT 'TRUE'");
  2669. $connection->executeQuery("ALTER TABLE course_category MODIFY COLUMN auth_cat_child VARCHAR(40) DEFAULT 'TRUE'");
  2670. $connection->executeQuery("ALTER TABLE c_quiz_answer MODIFY COLUMN hotspot_type varchar(40) default NULL");
  2671. $connection->executeQuery("ALTER TABLE c_tool MODIFY COLUMN target varchar(20) NOT NULL default '_self'");
  2672. $connection->executeQuery("ALTER TABLE c_link MODIFY COLUMN on_homepage char(10) NOT NULL default '0'");
  2673. $connection->executeQuery("ALTER TABLE c_blog_rating MODIFY COLUMN rating_type char(40) NOT NULL default 'post'");
  2674. $connection->executeQuery("ALTER TABLE c_survey MODIFY COLUMN anonymous char(10) NOT NULL default '0'");
  2675. $connection->executeQuery("ALTER TABLE c_document MODIFY COLUMN filetype char(10) NOT NULL default 'file'");
  2676. $connection->executeQuery("ALTER TABLE c_student_publication MODIFY COLUMN filetype char(10) NOT NULL default 'file'");
  2677. // Migrate using the migration files located in:
  2678. // src/Chamilo/CoreBundle/Migrations/Schema/V110
  2679. $result = migrate(
  2680. 110,
  2681. $manager
  2682. );
  2683. if ($result) {
  2684. error_log('Migrations files were executed.');
  2685. fixIds($manager);
  2686. $connection->executeQuery("UPDATE settings_current SET selected_value = '1.10.0' WHERE variable = 'chamilo_database_version'");
  2687. if ($processFiles) {
  2688. include __DIR__.'/update-files-1.9.0-1.10.0.inc.php';
  2689. // Only updates the configuration.inc.php with the new version
  2690. include __DIR__.'/update-configuration.inc.php';
  2691. $configurationFiles = array(
  2692. 'mail.conf.php',
  2693. 'profile.conf.php',
  2694. 'course_info.conf.php',
  2695. 'add_course.conf.php',
  2696. 'events.conf.php',
  2697. 'auth.conf.php',
  2698. 'portfolio.conf.php'
  2699. );
  2700. error_log('Copy conf files');
  2701. foreach ($configurationFiles as $file) {
  2702. if (file_exists(api_get_path(SYS_CODE_PATH).'inc/conf/'.$file)) {
  2703. copy(
  2704. api_get_path(SYS_CODE_PATH).'inc/conf/'.$file,
  2705. api_get_path(CONFIGURATION_PATH).$file
  2706. );
  2707. }
  2708. }
  2709. }
  2710. error_log('Upgrade 1.10.x process concluded! ('.date('Y-m-d H:i:s').')');
  2711. } else {
  2712. error_log('There was an error during running migrations. Check error.log');
  2713. break;
  2714. }
  2715. case '1.10.0':
  2716. // no break
  2717. case '1.10.2':
  2718. // no break
  2719. case '1.10.4':
  2720. // no break
  2721. case '1.10.6':
  2722. // no break
  2723. case '1.10.8':
  2724. // Migrate using the migration files located in:
  2725. // src/Chamilo/CoreBundle/Migrations/Schema/V111
  2726. $result = migrate(
  2727. 111,
  2728. $manager
  2729. );
  2730. if ($result) {
  2731. $connection->executeQuery("UPDATE settings_current SET selected_value = '1.11.0' WHERE variable = 'chamilo_database_version'");
  2732. error_log('Migrations files were executed.');
  2733. if ($processFiles) {
  2734. include __DIR__.'/update-files-1.10.0-1.11.0.inc.php';
  2735. }
  2736. error_log('Upgrade 1.11.x process concluded! ('.date('Y-m-d H:i:s').')');
  2737. } else {
  2738. error_log('There was an error during running migrations. Check error.log');
  2739. }
  2740. break;
  2741. default:
  2742. break;
  2743. }
  2744. echo '</div>';
  2745. return true;
  2746. }