install.lib.php 139 KB

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