install.lib.php 128 KB

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