import_csv.php 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CCalendarEvent;
  4. use Chamilo\CourseBundle\Entity\CItemProperty;
  5. use Chamilo\PluginBundle\Entity\StudentFollowUp\CarePost;
  6. use Fhaculty\Graph\Graph;
  7. use Monolog\Handler\BufferHandler;
  8. use Monolog\Handler\RotatingFileHandler;
  9. use Monolog\Handler\StreamHandler;
  10. use Monolog\Logger;
  11. if (PHP_SAPI != 'cli') {
  12. die('Run this script through the command line or comment this line in the code');
  13. }
  14. if (file_exists('multiple_url_fix.php')) {
  15. require 'multiple_url_fix.php';
  16. }
  17. require_once __DIR__.'/../inc/global.inc.php';
  18. ini_set('memory_limit', -1);
  19. ini_set('max_execution_time', 0);
  20. ini_set('log_errors', '1');
  21. ini_set('display_errors', '1');
  22. /**
  23. * Class ImportCsv.
  24. */
  25. class ImportCsv
  26. {
  27. public $test;
  28. public $defaultLanguage = 'dutch';
  29. public $extraFieldIdNameList = [
  30. 'session' => 'external_session_id',
  31. 'session_career' => 'external_career_id',
  32. 'course' => 'external_course_id',
  33. 'user' => 'external_user_id',
  34. 'calendar_event' => 'external_calendar_event_id',
  35. 'career' => 'external_career_id',
  36. 'career_urls' => 'career_urls',
  37. 'career_diagram' => 'career_diagram',
  38. ];
  39. public $defaultAdminId = 1;
  40. public $defaultSessionVisibility = 1;
  41. /**
  42. * When creating a user the expiration date is set to registration date + this value.
  43. *
  44. * @var int number of years
  45. */
  46. public $expirationDateInUserCreation = 1;
  47. public $batchSize = 20;
  48. /**
  49. * When updating a user the expiration date is set to update date + this value.
  50. *
  51. * @var int number of years
  52. */
  53. public $expirationDateInUserUpdate = 1;
  54. public $daysCoachAccessBeforeBeginning = 14;
  55. public $daysCoachAccessAfterBeginning = 14;
  56. public $conditions;
  57. private $logger;
  58. private $dumpValues;
  59. private $updateEmailToDummy;
  60. /**
  61. * @param Monolog\Logger $logger
  62. * @param array
  63. */
  64. public function __construct($logger, $conditions)
  65. {
  66. $this->logger = $logger;
  67. $this->conditions = $conditions;
  68. $this->updateEmailToDummy = false;
  69. }
  70. /**
  71. * @param bool $dump
  72. */
  73. public function setDumpValues($dump)
  74. {
  75. $this->dumpValues = $dump;
  76. }
  77. /**
  78. * @return bool
  79. */
  80. public function getDumpValues()
  81. {
  82. return $this->dumpValues;
  83. }
  84. /**
  85. * Runs the import process.
  86. */
  87. public function run()
  88. {
  89. global $_configuration;
  90. $value = api_get_configuration_value('import_csv_custom_url_id');
  91. if (!empty($value)) {
  92. $_configuration['access_url'] = $value;
  93. }
  94. $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
  95. if (!is_dir($path)) {
  96. echo "The folder! $path does not exits";
  97. return 0;
  98. }
  99. if ($this->getDumpValues()) {
  100. $this->dumpDatabaseTables();
  101. }
  102. echo 'Reading files: '.PHP_EOL.PHP_EOL;
  103. $files = scandir($path);
  104. $fileToProcess = [];
  105. $fileToProcessStatic = [];
  106. $teacherBackup = [];
  107. $groupBackup = [];
  108. $this->prepareImport();
  109. if (!empty($files)) {
  110. foreach ($files as $file) {
  111. $fileInfo = pathinfo($file);
  112. if (isset($fileInfo['extension']) && $fileInfo['extension'] === 'csv') {
  113. // Checking teachers_yyyymmdd.csv,
  114. // courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
  115. $parts = explode('_', $fileInfo['filename']);
  116. $preMethod = ucwords($parts[1]);
  117. $preMethod = str_replace('-static', 'Static', $preMethod);
  118. $method = 'import'.$preMethod;
  119. $isStatic = strpos($method, 'Static');
  120. if ($method == 'importSessionsextidStatic') {
  121. $method = 'importSessionsExtIdStatic';
  122. }
  123. if ($method == 'importCourseinsertStatic') {
  124. $method = 'importSubscribeUserToCourse';
  125. }
  126. if ($method == 'importUnsubsessionsextidStatic') {
  127. $method = 'importUnsubsessionsExtidStatic';
  128. }
  129. if ($method == 'importCareersdiagram') {
  130. $method = 'importCareersDiagram';
  131. }
  132. if ($method == 'importOpensessions') {
  133. $method = 'importOpenSessions';
  134. }
  135. if ($method == 'importSubsessionsextidStatic') {
  136. $method = 'importSubscribeUserToCourseSessionExtStatic';
  137. }
  138. if (method_exists($this, $method)) {
  139. if ((
  140. $method == 'importSubscribeStatic' ||
  141. $method == 'importSubscribeUserToCourse'
  142. ) ||
  143. empty($isStatic)
  144. ) {
  145. $fileToProcess[$parts[1]][] = [
  146. 'method' => $method,
  147. 'file' => $path.$fileInfo['basename'],
  148. ];
  149. } else {
  150. $fileToProcessStatic[$parts[1]][] = [
  151. 'method' => $method,
  152. 'file' => $path.$fileInfo['basename'],
  153. ];
  154. }
  155. } else {
  156. echo "Error - This file '$file' can't be processed.".PHP_EOL;
  157. echo "Trying to call $method".PHP_EOL;
  158. echo "The file have to has this format:".PHP_EOL;
  159. echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv,
  160. prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
  161. exit;
  162. }
  163. }
  164. }
  165. if (empty($fileToProcess) && empty($fileToProcessStatic)) {
  166. echo 'Error - no files to process.';
  167. return 0;
  168. }
  169. $sections = [
  170. 'students',
  171. 'teachers',
  172. 'courses',
  173. 'sessions',
  174. 'opensessions',
  175. 'subscribe-static',
  176. 'courseinsert-static',
  177. 'unsubscribe-static',
  178. 'care',
  179. 'careers',
  180. 'careersdiagram',
  181. ];
  182. foreach ($sections as $section) {
  183. if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
  184. $this->logger->addInfo("-- Import $section --");
  185. $files = $fileToProcess[$section];
  186. foreach ($files as $fileInfo) {
  187. $method = $fileInfo['method'];
  188. $file = $fileInfo['file'];
  189. echo 'File: '.$file.PHP_EOL;
  190. echo 'Method : '.$method.PHP_EOL;
  191. echo PHP_EOL;
  192. $this->logger->addInfo('====================================================');
  193. $this->logger->addInfo("Reading file: $file");
  194. $this->logger->addInfo("Loading method $method ");
  195. if ($method == 'importSessions' || $method == 'importOpenSessions') {
  196. $this->$method(
  197. $file,
  198. true,
  199. $teacherBackup,
  200. $groupBackup
  201. );
  202. } else {
  203. $this->$method($file, true);
  204. }
  205. $this->logger->addInfo('--Finish reading file--');
  206. }
  207. }
  208. }
  209. $sections = [
  210. 'students-static',
  211. 'teachers-static',
  212. 'courses-static',
  213. 'sessions-static',
  214. 'sessionsextid-static',
  215. 'unsubscribe-static',
  216. 'unsubsessionsextid-static',
  217. 'subsessionsextid-static',
  218. 'calendar-static',
  219. ];
  220. foreach ($sections as $section) {
  221. if (isset($fileToProcessStatic[$section]) &&
  222. !empty($fileToProcessStatic[$section])
  223. ) {
  224. $this->logger->addInfo("-- Import static files $section --");
  225. $files = $fileToProcessStatic[$section];
  226. foreach ($files as $fileInfo) {
  227. $method = $fileInfo['method'];
  228. $file = $fileInfo['file'];
  229. echo 'Static file: '.$file.PHP_EOL;
  230. echo 'Method : '.$method.PHP_EOL;
  231. echo PHP_EOL;
  232. $this->logger->addInfo("Reading static file: $file");
  233. $this->logger->addInfo("Loading method $method ");
  234. $this->$method(
  235. $file,
  236. true,
  237. $teacherBackup,
  238. $groupBackup
  239. );
  240. $this->logger->addInfo('--Finish reading file--');
  241. }
  242. }
  243. }
  244. $this->logger->addInfo('teacher backup');
  245. $this->logger->addInfo(print_r($teacherBackup, 1));
  246. }
  247. }
  248. /**
  249. * @param $file
  250. * @param bool $moveFile
  251. */
  252. public function importCare($file, $moveFile = false)
  253. {
  254. $data = Import::csv_reader($file);
  255. $counter = 1;
  256. $batchSize = $this->batchSize;
  257. $em = Database::getManager();
  258. if (!empty($data)) {
  259. $this->logger->addInfo(count($data)." records found.");
  260. $items = [];
  261. foreach ($data as $list) {
  262. $post = [];
  263. foreach ($list as $key => $value) {
  264. $key = (string) trim($key);
  265. // Remove utf8 bom
  266. $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
  267. $post[$key] = $value;
  268. }
  269. if (empty($post)) {
  270. continue;
  271. }
  272. $externalId = $post['External_care_id'];
  273. $items[$externalId] = $post;
  274. }
  275. ksort($items);
  276. foreach ($items as $row) {
  277. // Insert user
  278. //$insertUserInfo = api_get_user_info_from_username($row['Added_by']);
  279. // User about the post
  280. $userId = UserManager::get_user_id_from_original_id(
  281. $row['Added_by'],
  282. $this->extraFieldIdNameList['user']
  283. );
  284. $insertUserInfo = api_get_user_info($userId);
  285. if (empty($insertUserInfo)) {
  286. $this->logger->addInfo("User: '".$row['Added_by']."' doesn't exists. Skip this entry.");
  287. continue;
  288. }
  289. $insertUserInfo = api_get_user_entity($insertUserInfo['user_id']);
  290. // User about the post
  291. $userId = UserManager::get_user_id_from_original_id(
  292. $row['External_user_id'],
  293. $this->extraFieldIdNameList['user']
  294. );
  295. if (empty($userId)) {
  296. $this->logger->addInfo("User does '".$row['External_user_id']."' not exists skip this entry.");
  297. continue;
  298. }
  299. $userInfo = api_get_user_entity($userId);
  300. if (empty($userInfo)) {
  301. $this->logger->addInfo("Chamilo user does not found: #".$userId."' ");
  302. continue;
  303. }
  304. // Dates
  305. $createdAt = $this->createDateTime($row['Added_On']);
  306. $updatedAt = $this->createDateTime($row['Edited_on']);
  307. // Parent
  308. $parent = null;
  309. if (!empty($row['Parent_id'])) {
  310. $parentId = $items[$row['Parent_id']];
  311. $criteria = [
  312. 'externalCareId' => $parentId,
  313. ];
  314. $parent = $em->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost')->findOneBy($criteria);
  315. }
  316. // Tags
  317. $tags = explode(',', $row['Tags']);
  318. // Check if post already was added:
  319. $criteria = [
  320. 'externalCareId' => $row['External_care_id'],
  321. ];
  322. $post = $em->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost')->findOneBy($criteria);
  323. if (empty($post)) {
  324. $post = new CarePost();
  325. $this->logger->addInfo("New post will be created no match for externalCareId = ".$row['External_care_id']);
  326. }
  327. $contentDecoded = utf8_encode(base64_decode($row['Article']));
  328. $post
  329. ->setTitle($row['Title'])
  330. ->setContent($contentDecoded)
  331. ->setExternalCareId($row['External_care_id'])
  332. ->setCreatedAt($createdAt)
  333. ->setUpdatedAt($updatedAt)
  334. ->setPrivate((int) $row['Private'])
  335. ->setInsertUser($insertUserInfo)
  336. ->setExternalSource((int) $row['Source_is_external'])
  337. ->setParent($parent)
  338. ->setTags($tags)
  339. ->setUser($userInfo)
  340. ->setAttachment($row['Attachement'])
  341. ;
  342. $em->persist($post);
  343. $em->flush();
  344. $this->logger->addInfo("Post id saved #".$post->getId());
  345. if (($counter % $batchSize) === 0) {
  346. $em->flush();
  347. $em->clear(); // Detaches all objects from Doctrine!
  348. }
  349. $counter++;
  350. }
  351. $em->clear(); // Detaches all objects from Doctrine!
  352. }
  353. }
  354. /**
  355. * @return mixed
  356. */
  357. public function getUpdateEmailToDummy()
  358. {
  359. return $this->updateEmailToDummy;
  360. }
  361. /**
  362. * @param mixed $updateEmailToDummy
  363. */
  364. public function setUpdateEmailToDummy($updateEmailToDummy)
  365. {
  366. $this->updateEmailToDummy = $updateEmailToDummy;
  367. }
  368. /**
  369. * Change emails of all users except admins.
  370. */
  371. public function updateUsersEmails()
  372. {
  373. if ($this->getUpdateEmailToDummy() === true) {
  374. $sql = "UPDATE user SET email = CONCAT(username,'@example.com') WHERE id NOT IN (SELECT user_id FROM admin)";
  375. Database::query($sql);
  376. }
  377. }
  378. /**
  379. * Prepares extra fields before the import.
  380. */
  381. private function prepareImport()
  382. {
  383. // Create user extra field: extra_external_user_id
  384. UserManager::create_extra_field(
  385. $this->extraFieldIdNameList['user'],
  386. 1,
  387. 'External user id',
  388. null
  389. );
  390. // Create course extra field: extra_external_course_id
  391. CourseManager::create_course_extra_field(
  392. $this->extraFieldIdNameList['course'],
  393. 1,
  394. 'External course id',
  395. ''
  396. );
  397. CourseManager::create_course_extra_field(
  398. 'disable_import_calendar',
  399. 13,
  400. 'Disable import calendar',
  401. ''
  402. );
  403. // Create session extra field extra_external_session_id
  404. SessionManager::create_session_extra_field(
  405. $this->extraFieldIdNameList['session'],
  406. 1,
  407. 'External session id'
  408. );
  409. SessionManager::create_session_extra_field(
  410. $this->extraFieldIdNameList['session_career'],
  411. 1,
  412. 'Career id'
  413. );
  414. // Create calendar_event extra field extra_external_session_id
  415. $extraField = new ExtraField('calendar_event');
  416. $extraField->save(
  417. [
  418. 'field_type' => ExtraField::FIELD_TYPE_TEXT,
  419. 'variable' => $this->extraFieldIdNameList['calendar_event'],
  420. 'display_text' => 'External calendar event id',
  421. ]
  422. );
  423. $extraField = new ExtraField('career');
  424. $extraField->save(
  425. [
  426. 'visible_to_self' => 1,
  427. 'field_type' => ExtraField::FIELD_TYPE_TEXT,
  428. 'variable' => $this->extraFieldIdNameList['career'],
  429. 'display_text' => 'External career id',
  430. ]
  431. );
  432. $extraField->save(
  433. [
  434. 'visible_to_self' => 1,
  435. 'field_type' => ExtraField::FIELD_TYPE_TEXTAREA,
  436. 'variable' => $this->extraFieldIdNameList['career_diagram'],
  437. 'display_text' => 'Career diagram',
  438. ]
  439. );
  440. $extraField->save(
  441. [
  442. 'visible_to_self' => 1,
  443. 'field_type' => ExtraField::FIELD_TYPE_TEXTAREA,
  444. 'variable' => $this->extraFieldIdNameList['career_urls'],
  445. 'display_text' => 'Career urls',
  446. ]
  447. );
  448. }
  449. /**
  450. * @param string $file
  451. */
  452. private function moveFile($file)
  453. {
  454. $moved = str_replace('incoming', 'treated', $file);
  455. if ($this->test) {
  456. $result = 1;
  457. } else {
  458. $result = rename($file, $moved);
  459. }
  460. if ($result) {
  461. $this->logger->addInfo("Moving file to the treated folder: $file");
  462. } else {
  463. $this->logger->addError(
  464. "Error - Cant move file to the treated folder: $file"
  465. );
  466. }
  467. }
  468. /**
  469. * @param array $row
  470. *
  471. * @return array
  472. */
  473. private function cleanUserRow($row)
  474. {
  475. $row['lastname'] = $row['LastName'];
  476. $row['firstname'] = $row['FirstName'];
  477. $row['email'] = $row['Email'];
  478. $row['username'] = $row['UserName'];
  479. $row['password'] = $row['Password'];
  480. $row['auth_source'] = isset($row['AuthSource']) ? $row['AuthSource'] : PLATFORM_AUTH_SOURCE;
  481. $row['official_code'] = $row['OfficialCode'];
  482. $row['phone'] = isset($row['PhoneNumber']) ? $row['PhoneNumber'] : '';
  483. if (isset($row['StudentID'])) {
  484. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
  485. }
  486. if (isset($row['TeacherID'])) {
  487. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
  488. }
  489. return $row;
  490. }
  491. /**
  492. * @param array $row
  493. *
  494. * @return array
  495. */
  496. private function cleanCourseRow($row)
  497. {
  498. $row['title'] = $row['Title'];
  499. $row['course_code'] = $row['Code'];
  500. $row['course_category'] = $row['CourseCategory'];
  501. $row['email'] = $row['Teacher'];
  502. $row['language'] = $row['Language'];
  503. $row['visibility'] = isset($row['Visibility']) ? $row['Visibility'] : COURSE_VISIBILITY_REGISTERED;
  504. $row['teachers'] = [];
  505. if (isset($row['Teacher']) && !empty($row['Teacher'])) {
  506. $this->logger->addInfo("Teacher list found: ".$row['Teacher']);
  507. $teachers = explode(',', $row['Teacher']);
  508. if (!empty($teachers)) {
  509. foreach ($teachers as $teacherUserName) {
  510. $teacherUserName = trim($teacherUserName);
  511. $userInfo = api_get_user_info_from_username($teacherUserName);
  512. if (!empty($userInfo)) {
  513. $this->logger->addInfo("Username found: $teacherUserName");
  514. $row['teachers'][] = $userInfo['user_id'];
  515. }
  516. }
  517. }
  518. }
  519. if (isset($row['CourseID'])) {
  520. $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
  521. }
  522. return $row;
  523. }
  524. /**
  525. * File to import.
  526. *
  527. * @param string $file
  528. */
  529. private function importTeachersStatic($file)
  530. {
  531. $this->importTeachers($file, true);
  532. }
  533. /**
  534. * File to import.
  535. *
  536. * @param string $file
  537. * @param bool $moveFile
  538. */
  539. private function importTeachers($file, $moveFile = true)
  540. {
  541. $this->fixCSVFile($file);
  542. $data = Import::csvToArray($file);
  543. /* Unique identifier: official-code username.
  544. Email address and password should never get updated. *ok
  545. The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
  546. A slight edit of these fields should be taken into account. ???
  547. Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
  548. We’ll handle that manually if applicable.
  549. No delete!
  550. */
  551. $language = $this->defaultLanguage;
  552. if (!empty($data)) {
  553. $this->logger->addInfo(count($data)." records found.");
  554. $expirationDateOnCreation = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  555. $expirationDateOnUpdate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  556. $batchSize = $this->batchSize;
  557. $em = Database::getManager();
  558. $counter = 1;
  559. foreach ($data as $row) {
  560. $row = $this->cleanUserRow($row);
  561. $user_id = UserManager::get_user_id_from_original_id(
  562. $row['extra_'.$this->extraFieldIdNameList['user']],
  563. $this->extraFieldIdNameList['user']
  564. );
  565. $userInfo = [];
  566. $userInfoByOfficialCode = null;
  567. if (!empty($user_id)) {
  568. $userInfo = api_get_user_info($user_id);
  569. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  570. }
  571. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  572. // Create user
  573. $userId = UserManager::create_user(
  574. $row['firstname'],
  575. $row['lastname'],
  576. COURSEMANAGER,
  577. $row['email'],
  578. $row['username'],
  579. $row['password'],
  580. $row['official_code'],
  581. $language, //$row['language'],
  582. $row['phone'],
  583. null, //$row['picture'], //picture
  584. $row['auth_source'], // ?
  585. $expirationDateOnCreation, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  586. 1, //active
  587. 0,
  588. null, // extra
  589. null, //$encrypt_method = '',
  590. false //$send_mail = false
  591. );
  592. $row['extra_mail_notify_invitation'] = 1;
  593. $row['extra_mail_notify_message'] = 1;
  594. $row['extra_mail_notify_group_message'] = 1;
  595. if ($userId) {
  596. foreach ($row as $key => $value) {
  597. if (substr($key, 0, 6) == 'extra_') {
  598. //an extra field
  599. UserManager::update_extra_field_value(
  600. $userId,
  601. substr($key, 6),
  602. $value
  603. );
  604. }
  605. }
  606. $this->logger->addInfo("Teachers - User created: ".$row['username']);
  607. } else {
  608. $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  609. $this->logger->addError(strip_tags(Display::getFlashToString()));
  610. Display::cleanFlashMessages();
  611. }
  612. } else {
  613. if (empty($userInfo)) {
  614. $this->logger->addError("Teachers - Can't update user :".$row['username']);
  615. continue;
  616. }
  617. // Update user
  618. $result = UserManager::update_user(
  619. $userInfo['user_id'],
  620. $row['firstname'], // <<-- changed
  621. $row['lastname'], // <<-- changed
  622. $userInfo['username'],
  623. null, //$password = null,
  624. $row['auth_source'],
  625. $userInfo['email'],
  626. COURSEMANAGER,
  627. $userInfo['official_code'],
  628. $userInfo['phone'],
  629. $userInfo['picture_uri'],
  630. $expirationDateOnUpdate,
  631. $userInfo['active'],
  632. null, //$creator_id = null,
  633. 0, //$hr_dept_id = 0,
  634. null, // $extra = null,
  635. null, //$language = 'english',
  636. null, //$encrypt_method = '',
  637. false, //$send_email = false,
  638. 0 //$reset_password = 0
  639. );
  640. if ($result) {
  641. foreach ($row as $key => $value) {
  642. if (substr($key, 0, 6) == 'extra_') {
  643. //an extra field
  644. UserManager::update_extra_field_value(
  645. $userInfo['user_id'],
  646. substr($key, 6),
  647. $value
  648. );
  649. }
  650. }
  651. $this->logger->addInfo("Teachers - User updated: ".$row['username']);
  652. } else {
  653. $this->logger->addError("Teachers - User not updated: ".$row['username']);
  654. }
  655. }
  656. if (($counter % $batchSize) === 0) {
  657. $em->flush();
  658. $em->clear(); // Detaches all objects from Doctrine!
  659. }
  660. $counter++;
  661. }
  662. $em->clear(); // Detaches all objects from Doctrine!
  663. }
  664. if ($moveFile) {
  665. $this->moveFile($file);
  666. }
  667. $this->updateUsersEmails();
  668. }
  669. /**
  670. * @param string $file
  671. */
  672. private function importStudentsStatic($file)
  673. {
  674. $this->importStudents($file, true);
  675. }
  676. /**
  677. * @param string $file
  678. * @param bool $moveFile
  679. */
  680. private function importStudents($file, $moveFile = true)
  681. {
  682. $this->fixCSVFile($file);
  683. $data = Import::csvToArray($file);
  684. /*
  685. * Another users import.
  686. Unique identifier: official code and username . ok
  687. Password should never get updated. ok
  688. If an update should need to occur (because it changed in the .csv),
  689. we’ll want that logged. We will handle this manually in that case.
  690. All other fields should be updateable, though passwords should of course not get updated. ok
  691. If a user gets deleted (not there anymore),
  692. He should be set inactive one year after the current date.
  693. So I presume you’ll just update the expiration date.
  694. We want to grant access to courses up to a year after deletion.
  695. */
  696. $timeStart = microtime(true);
  697. $batchSize = $this->batchSize;
  698. $em = Database::getManager();
  699. if (!empty($data)) {
  700. $language = $this->defaultLanguage;
  701. $this->logger->addInfo(count($data)." records found.");
  702. $expirationDateOnCreate = api_get_utc_datetime(
  703. strtotime("+".intval($this->expirationDateInUserCreation)."years")
  704. );
  705. $expirationDateOnUpdate = api_get_utc_datetime(
  706. strtotime("+".intval($this->expirationDateInUserUpdate)."years")
  707. );
  708. $counter = 1;
  709. $secondsInYear = 365 * 24 * 60 * 60;
  710. foreach ($data as $row) {
  711. $row = $this->cleanUserRow($row);
  712. $user_id = UserManager::get_user_id_from_original_id(
  713. $row['extra_'.$this->extraFieldIdNameList['user']],
  714. $this->extraFieldIdNameList['user']
  715. );
  716. $userInfo = [];
  717. $userInfoByOfficialCode = null;
  718. if (!empty($user_id)) {
  719. $userInfo = api_get_user_info($user_id, false, true);
  720. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  721. }
  722. $userInfoFromUsername = api_get_user_info_from_username($row['username']);
  723. if (!empty($userInfoFromUsername)) {
  724. $extraFieldValue = new ExtraFieldValue('user');
  725. $extraFieldValues = $extraFieldValue->get_values_by_handler_and_field_variable(
  726. $userInfoFromUsername['user_id'],
  727. $this->extraFieldIdNameList['user']
  728. );
  729. if (!empty($extraFieldValues)) {
  730. $value = 0;
  731. foreach ($extraFieldValues as $extraFieldValue) {
  732. $value = $extraFieldValue['value'];
  733. }
  734. if (!empty($user_id) && $value != $user_id) {
  735. $emails = api_get_configuration_value('cron_notification_help_desk');
  736. if (!empty($emails)) {
  737. $this->logger->addInfo('Preparing email to users in configuration: "cron_notification_help_desk"');
  738. $subject = 'User not added due to same username';
  739. $body = 'Cannot add username: "'.$row['username'].'"
  740. with external_user_id: '.$row['extra_'.$this->extraFieldIdNameList['user']].'
  741. because '.$userInfoFromUsername['username'].' with external_user_id '.$value.' exists on the portal';
  742. $this->logger->addInfo($body);
  743. foreach ($emails as $email) {
  744. api_mail_html('', $email, $subject, $body);
  745. }
  746. }
  747. }
  748. }
  749. }
  750. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  751. // Create user
  752. $result = UserManager::create_user(
  753. $row['firstname'],
  754. $row['lastname'],
  755. STUDENT,
  756. $row['email'],
  757. $row['username'],
  758. $row['password'],
  759. $row['official_code'],
  760. $language, //$row['language'],
  761. $row['phone'],
  762. null, //$row['picture'], //picture
  763. $row['auth_source'], // ?
  764. $expirationDateOnCreate,
  765. 1, //active
  766. 0,
  767. null, // extra
  768. null, //$encrypt_method = '',
  769. false //$send_mail = false
  770. );
  771. $row['extra_mail_notify_invitation'] = 1;
  772. $row['extra_mail_notify_message'] = 1;
  773. $row['extra_mail_notify_group_message'] = 1;
  774. if ($result) {
  775. foreach ($row as $key => $value) {
  776. if (substr($key, 0, 6) === 'extra_') {
  777. //an extra field
  778. UserManager::update_extra_field_value(
  779. $result,
  780. substr($key, 6),
  781. $value
  782. );
  783. }
  784. }
  785. $this->logger->addInfo("Students - User created: ".$row['username']);
  786. } else {
  787. $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  788. $this->logger->addError(strip_tags(Display::getFlashToString()));
  789. Display::cleanFlashMessages();
  790. }
  791. } else {
  792. if (empty($userInfo)) {
  793. $this->logger->addError("Students - Can't update user :".$row['username']);
  794. continue;
  795. }
  796. if (isset($row['action']) && $row['action'] === 'delete') {
  797. // Inactive one year later
  798. $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + $secondsInYear));
  799. }
  800. $password = $row['password']; // change password
  801. $email = $row['email']; // change email
  802. $resetPassword = 2; // allow password change
  803. // Conditions that disables the update of password and email:
  804. if (isset($this->conditions['importStudents'])) {
  805. if (isset($this->conditions['importStudents']['update']) &&
  806. isset($this->conditions['importStudents']['update']['avoid'])
  807. ) {
  808. // Blocking email update -
  809. // 1. Condition
  810. $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
  811. if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
  812. $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
  813. // Do not change email keep the old email.
  814. $email = $userInfo['email'];
  815. }
  816. // 2. Condition
  817. if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
  818. $email = $userInfo['email'];
  819. }
  820. // 3. Condition
  821. if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
  822. $email = $row['email'];
  823. }
  824. // Blocking password update
  825. //$avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
  826. /*if (isset($row['password'])) {
  827. $user = api_get_user_entity($userInfo['id']);
  828. $encoded = UserManager::encryptPassword(
  829. $row['password'],
  830. $user
  831. );
  832. if ($userInfo['password'] != $encoded &&
  833. in_array($row['password'], $avoidUsersWithPassword)
  834. ) {
  835. $this->logger->addInfo(
  836. "Students - User password is not updated: ".$row['username']." because the avoid conditions (password)."
  837. );
  838. $password = null;
  839. $resetPassword = 0; // disallow password change
  840. }
  841. }*/
  842. }
  843. }
  844. // Always disallow password change during update
  845. $password = null;
  846. $resetPassword = 0; // disallow password change
  847. // Update user
  848. $result = UserManager::update_user(
  849. $userInfo['user_id'],
  850. $row['firstname'], // <<-- changed
  851. $row['lastname'], // <<-- changed
  852. $row['username'], // <<-- changed
  853. $password, //$password = null,
  854. $row['auth_source'],
  855. $email,
  856. STUDENT,
  857. $userInfo['official_code'],
  858. $userInfo['phone'],
  859. $userInfo['picture_uri'],
  860. $expirationDateOnUpdate,
  861. $userInfo['active'],
  862. null, //$creator_id = null,
  863. 0, //$hr_dept_id = 0,
  864. null, // $extra = null,
  865. null, //$language = 'english',
  866. null, //$encrypt_method = '',
  867. false, //$send_email = false,
  868. $resetPassword //$reset_password = 0
  869. );
  870. if ($result) {
  871. if ($row['username'] != $userInfo['username']) {
  872. $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
  873. }
  874. foreach ($row as $key => $value) {
  875. if (substr($key, 0, 6) === 'extra_') {
  876. //an extra field
  877. UserManager::update_extra_field_value(
  878. $userInfo['user_id'],
  879. substr($key, 6),
  880. $value
  881. );
  882. }
  883. }
  884. $this->logger->addInfo("Students - User updated: ".$row['username']);
  885. } else {
  886. $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  887. }
  888. }
  889. if (($counter % $batchSize) === 0) {
  890. $em->flush();
  891. $em->clear(); // Detaches all objects from Doctrine!
  892. $this->logger->addInfo("Detaches all objects");
  893. }
  894. $counter++;
  895. }
  896. $em->clear(); // Detaches all objects from Doctrine!
  897. }
  898. $timeEnd = microtime(true);
  899. $executionTime = round(($timeEnd - $timeStart) / 60, 2);
  900. $this->logger->addInfo("Execution Time for process students: $executionTime Min");
  901. if ($moveFile) {
  902. $this->moveFile($file);
  903. }
  904. $this->updateUsersEmails();
  905. }
  906. /**
  907. * @param string $file
  908. */
  909. private function importCoursesStatic($file, $moveFile, &$teacherBackup = [], &$groupBackup = [])
  910. {
  911. $this->importCourses($file, true, $teacherBackup, $groupBackup);
  912. }
  913. /**
  914. * @param string $file
  915. * @param bool $moveFile
  916. *
  917. * @return int
  918. */
  919. private function importCalendarStatic($file, $moveFile = true)
  920. {
  921. $this->fixCSVFile($file);
  922. $this->updateUsersEmails();
  923. $data = Import::csvToArray($file);
  924. if (!empty($data)) {
  925. $this->logger->addInfo(count($data).' records found.');
  926. $eventsToCreate = [];
  927. $errorFound = false;
  928. $courseExtraFieldValue = new ExtraFieldValue('course');
  929. foreach ($data as $row) {
  930. $sessionId = null;
  931. $externalSessionId = null;
  932. if (isset($row['external_sessionID'])) {
  933. $externalSessionId = $row['external_sessionID'];
  934. $sessionId = SessionManager::getSessionIdFromOriginalId(
  935. $externalSessionId,
  936. $this->extraFieldIdNameList['session']
  937. );
  938. }
  939. $courseCode = null;
  940. if (isset($row['coursecode'])) {
  941. $courseCode = $row['coursecode'];
  942. }
  943. $courseInfo = api_get_course_info($courseCode);
  944. $item = $courseExtraFieldValue->get_values_by_handler_and_field_variable(
  945. $courseInfo['real_id'],
  946. 'disable_import_calendar'
  947. );
  948. if (!empty($item) && isset($item['value']) && $item['value'] == 1) {
  949. $this->logger->addInfo(
  950. "Course '".$courseInfo['code']."' has 'disable_import_calendar' turn on. Skip"
  951. );
  952. $errorFound = true;
  953. }
  954. if (empty($courseInfo)) {
  955. $this->logger->addInfo("Course '$courseCode' does not exists");
  956. } else {
  957. if ($courseInfo['visibility'] == COURSE_VISIBILITY_HIDDEN) {
  958. $this->logger->addInfo("Course '".$courseInfo['code']."' has hidden visiblity. Skip");
  959. $errorFound = true;
  960. }
  961. }
  962. if (empty($sessionId)) {
  963. $this->logger->addInfo("external_sessionID: $externalSessionId does not exists.");
  964. }
  965. $teacherId = null;
  966. $sessionInfo = [];
  967. if (!empty($sessionId) && !empty($courseInfo)) {
  968. $sessionInfo = api_get_session_info($sessionId);
  969. $courseIncluded = SessionManager::relation_session_course_exist(
  970. $sessionId,
  971. $courseInfo['real_id']
  972. );
  973. if ($courseIncluded == false) {
  974. $this->logger->addInfo(
  975. "Course '$courseCode' is not included in session: $sessionId"
  976. );
  977. $errorFound = true;
  978. } else {
  979. $teachers = CourseManager::get_coach_list_from_course_code(
  980. $courseInfo['code'],
  981. $sessionId
  982. );
  983. // Getting first teacher.
  984. if (!empty($teachers)) {
  985. $teacher = current($teachers);
  986. $teacherId = $teacher['user_id'];
  987. } else {
  988. $teacherId = $sessionInfo['id_coach'];
  989. }
  990. }
  991. } else {
  992. $errorFound = true;
  993. }
  994. if (empty($teacherId)) {
  995. $errorFound = true;
  996. $this->logger->addInfo(
  997. "No teacher found in course code : '$courseCode' and session: '$sessionId'"
  998. );
  999. }
  1000. $date = $row['date'];
  1001. $startTime = $row['time_start'];
  1002. $endTime = $row['time_end'];
  1003. $title = $row['title'];
  1004. $comment = $row['comment'];
  1005. $color = isset($row['color']) ? $row['color'] : '';
  1006. $startDateYear = substr($date, 0, 4);
  1007. $startDateMonth = substr($date, 4, 2);
  1008. $startDateDay = substr($date, 6, 8);
  1009. $startDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$startTime.':00';
  1010. $endDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$endTime.':00';
  1011. if (!api_is_valid_date($startDate) || !api_is_valid_date($endDate)) {
  1012. $this->logger->addInfo("Verify your dates: '$startDate' : '$endDate' ");
  1013. $errorFound = true;
  1014. }
  1015. // Check session dates
  1016. if ($sessionInfo && !empty($sessionInfo['access_start_date'])) {
  1017. $date = new \DateTime($sessionInfo['access_start_date']);
  1018. $interval = new \DateInterval('P7D');
  1019. $date->sub($interval);
  1020. if ($date->getTimestamp() > time()) {
  1021. $this->logger->addInfo(
  1022. "Calendar event # ".$row['external_calendar_itemID']."
  1023. in session [$externalSessionId] was not added
  1024. because the startdate is more than 7 days in the future: ".$sessionInfo['access_start_date']
  1025. );
  1026. $errorFound = true;
  1027. }
  1028. }
  1029. if ($errorFound == false) {
  1030. $eventsToCreate[] = [
  1031. 'start' => $startDate,
  1032. 'end' => $endDate,
  1033. 'title' => $title,
  1034. 'sender_id' => $teacherId,
  1035. 'course_id' => $courseInfo['real_id'],
  1036. 'session_id' => $sessionId,
  1037. 'comment' => $comment,
  1038. 'color' => $color,
  1039. $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID'],
  1040. ];
  1041. }
  1042. $errorFound = false;
  1043. }
  1044. if (empty($eventsToCreate)) {
  1045. $this->logger->addInfo('No events to add');
  1046. return 0;
  1047. }
  1048. $extraFieldValue = new ExtraFieldValue('calendar_event');
  1049. $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
  1050. $externalEventId = null;
  1051. $extraField = new ExtraField('calendar_event');
  1052. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
  1053. if (empty($extraFieldInfo)) {
  1054. $this->logger->addInfo(
  1055. "No calendar event extra field created: $extraFieldName"
  1056. );
  1057. return 0;
  1058. }
  1059. $this->logger->addInfo('Ready to insert # '.count($eventsToCreate).' events');
  1060. $batchSize = $this->batchSize;
  1061. $counter = 1;
  1062. $em = Database::getManager();
  1063. $eventStartDateList = [];
  1064. $eventEndDateList = [];
  1065. $report = [
  1066. 'mail_sent' => 0,
  1067. 'mail_not_sent_announcement_exists' => 0,
  1068. 'mail_not_sent_because_date' => 0,
  1069. ];
  1070. $eventsToCreateFinal = [];
  1071. foreach ($eventsToCreate as $event) {
  1072. $update = false;
  1073. $item = null;
  1074. if (!isset($event[$extraFieldName])) {
  1075. $this->logger->addInfo('No external_calendar_itemID found. Skipping ...');
  1076. continue;
  1077. } else {
  1078. $externalEventId = $event[$extraFieldName];
  1079. if (empty($externalEventId)) {
  1080. $this->logger->addInfo('external_calendar_itemID was set but empty. Skipping ...');
  1081. continue;
  1082. }
  1083. $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  1084. $extraFieldName,
  1085. $externalEventId,
  1086. false,
  1087. false,
  1088. false
  1089. );
  1090. if (!empty($item)) {
  1091. $update = true;
  1092. }
  1093. }
  1094. $courseInfo = api_get_course_info_by_id($event['course_id']);
  1095. $event['course_info'] = $courseInfo;
  1096. $event['update'] = $update;
  1097. $event['item'] = $item;
  1098. $calendarEvent = null;
  1099. /* Check if event changed of course code */
  1100. if (!empty($item) && isset($item['item_id']) && !empty($item['item_id'])) {
  1101. /** @var CCalendarEvent $calendarEvent */
  1102. $calendarEvent = $em->getRepository('ChamiloCourseBundle:CCalendarEvent')->find($item['item_id']);
  1103. }
  1104. if ($calendarEvent) {
  1105. $this->logger->addInfo('Calendar event found '.$item['item_id']);
  1106. if ($calendarEvent->getCId() != $courseInfo['real_id']) {
  1107. $this->logger->addInfo('Move from course #'.$calendarEvent->getCId().' to #'.$courseInfo['real_id']);
  1108. // Seems that the course id changed in the csv
  1109. $calendarEvent->setCId($courseInfo['real_id']);
  1110. $em->persist($calendarEvent);
  1111. $em->flush();
  1112. $criteria = [
  1113. 'tool' => 'calendar_event',
  1114. 'ref' => $item['item_id'],
  1115. ];
  1116. /** @var CItemProperty $itemProperty */
  1117. $itemProperty = $em->getRepository('ChamiloCourseBundle:CItemProperty')->findOneBy($criteria);
  1118. $courseEntity = $em->getRepository('ChamiloCoreBundle:Course')->find($courseInfo['real_id']);
  1119. if ($itemProperty && $courseEntity) {
  1120. $itemProperty->setCourse($courseEntity);
  1121. $em->persist($itemProperty);
  1122. $em->flush();
  1123. }
  1124. }
  1125. // Checking if session still exists
  1126. $calendarSessionId = (int) $calendarEvent->getSessionId();
  1127. if (!empty($calendarSessionId)) {
  1128. $calendarSessionInfo = api_get_session_info($calendarSessionId);
  1129. if (empty($calendarSessionInfo)) {
  1130. $calendarId = (int) $calendarEvent->getIid();
  1131. // Delete calendar events because the session was deleted!
  1132. $this->logger->addInfo(
  1133. "Delete event # $calendarId because session # $calendarSessionId doesn't exist"
  1134. );
  1135. $sql = "DELETE FROM c_calendar_event
  1136. WHERE iid = $calendarId AND session_id = $calendarSessionId";
  1137. Database::query($sql);
  1138. $this->logger->addInfo($sql);
  1139. $sql = "DELETE FROM c_item_property
  1140. WHERE
  1141. tool = 'calendar_event' AND
  1142. ref = $calendarSessionId AND
  1143. session_id = $calendarSessionId";
  1144. Database::query($sql);
  1145. $this->logger->addInfo($sql);
  1146. }
  1147. }
  1148. } else {
  1149. $this->logger->addInfo('Calendar event not found '.$item['item_id']);
  1150. }
  1151. $event['external_event_id'] = $externalEventId;
  1152. if (isset($eventStartDateList[$courseInfo['real_id']]) &&
  1153. isset($eventStartDateList[$courseInfo['real_id']][$event['session_id']])
  1154. ) {
  1155. $currentItemDate = api_strtotime($event['start']);
  1156. $firstDate = $eventStartDateList[$courseInfo['real_id']][$event['session_id']];
  1157. if ($currentItemDate < api_strtotime($firstDate)) {
  1158. $eventStartDateList[$courseInfo['real_id']][$event['session_id']] = $event['start'];
  1159. $eventEndDateList[$courseInfo['real_id']][$event['session_id']] = $event['end'];
  1160. }
  1161. } else {
  1162. // First time
  1163. $eventStartDateList[$courseInfo['real_id']][$event['session_id']] = $event['start'];
  1164. $eventEndDateList[$courseInfo['real_id']][$event['session_id']] = $event['end'];
  1165. }
  1166. $eventsToCreateFinal[] = $event;
  1167. }
  1168. $eventAlreadySent = [];
  1169. $tpl = new Template(null, false, false, false, false, false, false);
  1170. foreach ($eventsToCreateFinal as $event) {
  1171. $courseInfo = $event['course_info'];
  1172. $item = $event['item'];
  1173. $update = $event['update'];
  1174. $externalEventId = $event['external_event_id'];
  1175. $info = 'Course: '.$courseInfo['real_id'].' ('.$courseInfo['code'].') - Session: '.$event['session_id'].' external event id: '.$externalEventId;
  1176. $agenda = new Agenda(
  1177. 'course',
  1178. $event['sender_id'],
  1179. $courseInfo['real_id'],
  1180. $event['session_id']
  1181. );
  1182. $agenda->set_course($courseInfo);
  1183. $agenda->setSessionId($event['session_id']);
  1184. $agenda->setSenderId($event['sender_id']);
  1185. $agenda->setIsAllowedToEdit(true);
  1186. $eventComment = $event['comment'];
  1187. $color = $event['color'];
  1188. // To use the event comment you need
  1189. // ALTER TABLE c_calendar_event ADD COLUMN comment TEXT;
  1190. // add in configuration.php allow_agenda_event_comment = true
  1191. if (empty($courseInfo)) {
  1192. $this->logger->addInfo(
  1193. "No course found for event #$externalEventId Course #".$event['course_id']." Skipping ..."
  1194. );
  1195. continue;
  1196. }
  1197. if (empty($event['sender_id'])) {
  1198. $this->logger->addInfo(
  1199. "No sender found for event #$externalEventId Send #".$event['sender_id']." Skipping ..."
  1200. );
  1201. continue;
  1202. }
  1203. // Taking first element of course-session event
  1204. $alreadyAdded = false;
  1205. $firstDate = $eventStartDateList[$courseInfo['real_id']][$event['session_id']];
  1206. $firstEndDate = $eventEndDateList[$courseInfo['real_id']][$event['session_id']];
  1207. if (isset($eventAlreadySent[$courseInfo['real_id']]) &&
  1208. isset($eventAlreadySent[$courseInfo['real_id']][$event['session_id']])
  1209. ) {
  1210. $alreadyAdded = true;
  1211. } else {
  1212. $eventAlreadySent[$courseInfo['real_id']][$event['session_id']] = true;
  1213. }
  1214. // Working days (Mon-Fri)see BT#12156#note-16
  1215. $days = 3;
  1216. $startDatePlusDays = api_strtotime("$days weekdays");
  1217. /*
  1218. $timePart = date('H:i:s', api_strtotime('now'));
  1219. $datePart = date('Y-m-d', api_strtotime("$days weekdays"));
  1220. $startDatePlusDays = "$timePart $datePart";
  1221. */
  1222. $this->logger->addInfo(
  1223. 'startDatePlusDays: '.api_get_utc_datetime($startDatePlusDays).' - First date: '.$firstDate
  1224. );
  1225. // Send
  1226. $sendMail = false;
  1227. if ($startDatePlusDays > api_strtotime($firstDate)) {
  1228. $sendMail = true;
  1229. }
  1230. // Send announcement to users
  1231. if ($sendMail && $alreadyAdded == false) {
  1232. $start = $firstDate;
  1233. $end = $firstEndDate;
  1234. if (!empty($end) &&
  1235. api_format_date($start, DATE_FORMAT_LONG) ==
  1236. api_format_date($end, DATE_FORMAT_LONG)
  1237. ) {
  1238. $date = api_format_date($start, DATE_FORMAT_LONG).' ('.
  1239. api_format_date($start, TIME_NO_SEC_FORMAT).' '.
  1240. api_format_date($end, TIME_NO_SEC_FORMAT).')';
  1241. } else {
  1242. $date = api_format_date($start, DATE_TIME_FORMAT_LONG_24H).' - '.
  1243. api_format_date($end, DATE_TIME_FORMAT_LONG_24H);
  1244. }
  1245. $sessionName = '';
  1246. $sessionId = isset($event['session_id']) && !empty($event['session_id']) ? $event['session_id'] : 0;
  1247. if (!empty($sessionId)) {
  1248. $sessionName = api_get_session_name($sessionId);
  1249. }
  1250. $courseTitle = $courseInfo['title'];
  1251. // Get the value of the "careerid" extra field of this
  1252. // session
  1253. $sessionExtraFieldValue = new ExtraFieldValue('session');
  1254. $externalCareerIdList = $sessionExtraFieldValue->get_values_by_handler_and_field_variable(
  1255. $event['session_id'],
  1256. 'careerid'
  1257. );
  1258. $externalCareerIdList = $externalCareerIdList['value'];
  1259. $externalCareerIds = [];
  1260. if (substr($externalCareerIdList, 0, 1) === '[') {
  1261. $externalCareerIdList = substr($externalCareerIdList, 1, -1);
  1262. $externalCareerIds = preg_split('/,/', $externalCareerIdList);
  1263. } else {
  1264. $externalCareerIds = [$externalCareerIdList];
  1265. }
  1266. $careerExtraFieldValue = new ExtraFieldValue('career');
  1267. $career = new Career();
  1268. $careerName = '';
  1269. // Concat the names of each career linked to this session
  1270. foreach ($externalCareerIds as $externalCareerId) {
  1271. // Using the external_career_id field (from above),
  1272. // find the career ID
  1273. $careerValue = $careerExtraFieldValue->get_item_id_from_field_variable_and_field_value(
  1274. 'external_career_id',
  1275. $externalCareerId
  1276. );
  1277. $career = $career->find($careerValue['item_id']);
  1278. $careerName .= $career['name'].', ';
  1279. }
  1280. // Remove trailing comma
  1281. $careerName = substr($careerName, 0, -2);
  1282. $subject = sprintf(
  1283. get_lang('WelcomeToPortalXInCourseSessionX'),
  1284. api_get_setting('Institution'),
  1285. $courseInfo['title']
  1286. );
  1287. $tpl->assign('course_title', $courseTitle);
  1288. $tpl->assign('career_name', $careerName);
  1289. $tpl->assign('first_lesson', $date);
  1290. $tpl->assign('location', $eventComment);
  1291. $tpl->assign('session_name', $sessionName);
  1292. if (empty($sessionId)) {
  1293. $teachersToString = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code'], ',');
  1294. } else {
  1295. $teachersToString = SessionManager::getCoachesByCourseSessionToString(
  1296. $sessionId,
  1297. $courseInfo['real_id'],
  1298. ','
  1299. );
  1300. }
  1301. $tpl->assign('teachers', $teachersToString);
  1302. $templateName = $tpl->get_template('mail/custom_calendar_welcome.tpl');
  1303. $emailBody = $tpl->fetch($templateName);
  1304. $coaches = SessionManager::getCoachesByCourseSession(
  1305. $event['session_id'],
  1306. $courseInfo['real_id']
  1307. );
  1308. // Search if an announcement exists:
  1309. $announcementsWithTitleList = AnnouncementManager::getAnnouncementsByTitle(
  1310. $subject,
  1311. $courseInfo['real_id'],
  1312. $event['session_id'],
  1313. 1
  1314. );
  1315. if (count($announcementsWithTitleList) === 0) {
  1316. $this->logger->addInfo(
  1317. 'Mail to be sent because start date: '.$event['start'].' and no announcement found.'
  1318. );
  1319. $senderId = $this->defaultAdminId;
  1320. if (!empty($coaches) && isset($coaches[0]) && !empty($coaches[0])) {
  1321. $senderId = $coaches[0];
  1322. }
  1323. $announcementId = AnnouncementManager::add_announcement(
  1324. $courseInfo,
  1325. $event['session_id'],
  1326. $subject,
  1327. $emailBody,
  1328. [
  1329. 'everyone',
  1330. 'users' => $coaches,
  1331. ],
  1332. [],
  1333. null,
  1334. null,
  1335. false,
  1336. $senderId
  1337. );
  1338. if ($announcementId) {
  1339. $this->logger->addInfo("Announcement added: $announcementId in $info");
  1340. $this->logger->addInfo("<<--SENDING MAIL Sender id: $senderId-->>");
  1341. $report['mail_sent']++;
  1342. AnnouncementManager::sendEmail(
  1343. $courseInfo,
  1344. $event['session_id'],
  1345. $announcementId,
  1346. false,
  1347. false,
  1348. $this->logger,
  1349. $senderId,
  1350. true
  1351. );
  1352. } else {
  1353. $this->logger->addError(
  1354. "Error when trying to add announcement with title $subject here: $info and SenderId = $senderId"
  1355. );
  1356. }
  1357. } else {
  1358. $report['mail_not_sent_announcement_exists']++;
  1359. $this->logger->addInfo(
  1360. "Mail NOT sent. An announcement seems to be already saved in '$info'"
  1361. );
  1362. }
  1363. } else {
  1364. $this->logger->addInfo(
  1365. "Send Mail: ".intval($sendMail).' - Already added: '.intval($alreadyAdded)
  1366. );
  1367. if ($sendMail == false) {
  1368. $report['mail_not_sent_because_date']++;
  1369. }
  1370. }
  1371. $content = '';
  1372. if ($update && isset($item['item_id'])) {
  1373. $eventInfo = $agenda->get_event($item['item_id']);
  1374. if (empty($eventInfo)) {
  1375. // Means that agenda external id exists but the event doesn't exist
  1376. $this->logger->addInfo("external event id exists: $externalEventId");
  1377. $this->logger->addInfo("but Chamilo event doesn't exists: ".$item['item_id']);
  1378. $eventId = $agenda->addEvent(
  1379. $event['start'],
  1380. $event['end'],
  1381. false,
  1382. $event['title'],
  1383. $content,
  1384. ['everyone'], // $usersToSend
  1385. false, //$addAsAnnouncement = false
  1386. null, // $parentEventId
  1387. [], //$attachmentArray = array(),
  1388. [], //$attachmentCommentList
  1389. $eventComment,
  1390. $color
  1391. );
  1392. if (!empty($eventId)) {
  1393. $this->logger->addInfo("Chamilo event created: ".$eventId);
  1394. $extraFieldValueItem = $extraFieldValue->get_values_by_handler_and_field_id(
  1395. $item['item_id'],
  1396. $extraFieldInfo['id']
  1397. );
  1398. if (!empty($extraFieldValueItem) && isset($extraFieldValueItem['id'])) {
  1399. $params = [
  1400. 'id' => $extraFieldValueItem['id'],
  1401. 'item_id' => $eventId,
  1402. ];
  1403. $extraFieldValue->update($params);
  1404. $this->logger->addInfo(
  1405. 'Updating calendar extra field #'.$extraFieldValueItem['id'].'
  1406. new item_id: '.$eventId.' old item_id: '.$item['item_id']
  1407. );
  1408. }
  1409. } else {
  1410. $this->logger->addInfo("Error while creating event external id: $externalEventId");
  1411. }
  1412. } else {
  1413. // The event already exists, just update
  1414. $eventResult = $agenda->editEvent(
  1415. $item['item_id'],
  1416. $event['start'],
  1417. $event['end'],
  1418. false,
  1419. $event['title'],
  1420. $content,
  1421. ['everyone'], // $usersToSend
  1422. [], //$attachmentArray = array(),
  1423. [], //$attachmentCommentList
  1424. $eventComment,
  1425. $color,
  1426. false,
  1427. false,
  1428. $this->defaultAdminId
  1429. );
  1430. if ($eventResult !== false) {
  1431. $this->logger->addInfo(
  1432. "Event updated #".$item['item_id']." External cal Id: (".$externalEventId.") $info"
  1433. );
  1434. } else {
  1435. $this->logger->addInfo(
  1436. "Error while updating event with external id: $externalEventId"
  1437. );
  1438. }
  1439. }
  1440. } else {
  1441. // New event. Create it.
  1442. $eventId = $agenda->addEvent(
  1443. $event['start'],
  1444. $event['end'],
  1445. false,
  1446. $event['title'],
  1447. $content,
  1448. ['everyone'], // $usersToSend
  1449. false, //$addAsAnnouncement = false
  1450. null, // $parentEventId
  1451. [], //$attachmentArray = array(),
  1452. [], //$attachmentCommentList
  1453. $eventComment,
  1454. $color
  1455. );
  1456. if (!empty($eventId)) {
  1457. $extraFieldValue->save(
  1458. [
  1459. 'value' => $externalEventId,
  1460. 'field_id' => $extraFieldInfo['id'],
  1461. 'item_id' => $eventId,
  1462. ]
  1463. );
  1464. $this->logger->addInfo(
  1465. "Event added: #$eventId External cal id: (".$externalEventId.") $info"
  1466. );
  1467. } else {
  1468. $this->logger->addInfo(
  1469. "Error while creating event external id: $externalEventId"
  1470. );
  1471. }
  1472. }
  1473. if (($counter % $batchSize) === 0) {
  1474. $em->flush();
  1475. $em->clear(); // Detaches all objects from Doctrine!
  1476. }
  1477. $counter++;
  1478. }
  1479. $em->clear(); // Detaches all objects from Doctrine!
  1480. $this->logger->addInfo('------Summary------');
  1481. foreach ($report as $title => $count) {
  1482. $this->logger->addInfo("$title: $count");
  1483. }
  1484. $this->logger->addInfo('------End Summary------');
  1485. }
  1486. if ($moveFile) {
  1487. $this->moveFile($file);
  1488. }
  1489. }
  1490. /**
  1491. * @param string $file
  1492. * @param bool $moveFile
  1493. * @param array $teacherBackup
  1494. * @param array $groupBackup
  1495. */
  1496. private function importCourses(
  1497. $file,
  1498. $moveFile = true,
  1499. &$teacherBackup = [],
  1500. &$groupBackup = []
  1501. ) {
  1502. $this->fixCSVFile($file);
  1503. $data = Import::csvToArray($file);
  1504. if (!empty($data)) {
  1505. $this->logger->addInfo(count($data)." records found.");
  1506. foreach ($data as $row) {
  1507. $row = $this->cleanCourseRow($row);
  1508. $courseId = CourseManager::get_course_id_from_original_id(
  1509. $row['extra_'.$this->extraFieldIdNameList['course']],
  1510. $this->extraFieldIdNameList['course']
  1511. );
  1512. $courseInfo = api_get_course_info_by_id($courseId);
  1513. if (empty($courseInfo)) {
  1514. // Create
  1515. $params = [];
  1516. $params['title'] = $row['title'];
  1517. $params['exemplary_content'] = false;
  1518. $params['wanted_code'] = $row['course_code'];
  1519. $params['course_category'] = $row['course_category'];
  1520. $params['course_language'] = $row['language'];
  1521. $params['teachers'] = $row['teachers'];
  1522. $params['visibility'] = $row['visibility'];
  1523. $courseInfo = CourseManager::create_course(
  1524. $params,
  1525. $this->defaultAdminId
  1526. );
  1527. if (!empty($courseInfo)) {
  1528. CourseManager::update_course_extra_field_value(
  1529. $courseInfo['code'],
  1530. 'external_course_id',
  1531. $row['extra_'.$this->extraFieldIdNameList['course']]
  1532. );
  1533. $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
  1534. } else {
  1535. $this->logger->addError("Courses - Can't create course:".$row['title']);
  1536. }
  1537. } else {
  1538. // Update
  1539. $params = [
  1540. 'title' => $row['title'],
  1541. 'category_code' => $row['course_category'],
  1542. 'visibility' => $row['visibility'],
  1543. ];
  1544. $result = CourseManager::update_attributes(
  1545. $courseInfo['real_id'],
  1546. $params
  1547. );
  1548. $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
  1549. $teachers = $row['teachers'];
  1550. if (!is_array($teachers)) {
  1551. $teachers = [$teachers];
  1552. }
  1553. if ($addTeacherToSession) {
  1554. $this->logger->addInfo("Add teacher to all course sessions");
  1555. CourseManager::updateTeachers(
  1556. $courseInfo,
  1557. $row['teachers'],
  1558. false,
  1559. true,
  1560. false,
  1561. $teacherBackup,
  1562. $this->logger
  1563. );
  1564. } else {
  1565. CourseManager::updateTeachers(
  1566. $courseInfo,
  1567. $row['teachers'],
  1568. true,
  1569. false,
  1570. false,
  1571. $teacherBackup,
  1572. $this->logger
  1573. );
  1574. }
  1575. foreach ($teachers as $teacherId) {
  1576. if (isset($groupBackup['tutor'][$teacherId]) &&
  1577. isset($groupBackup['tutor'][$teacherId][$courseInfo['code']])
  1578. ) {
  1579. foreach ($groupBackup['tutor'][$teacherId][$courseInfo['code']] as $data) {
  1580. $groupInfo = GroupManager::get_group_properties($data['group_id']);
  1581. GroupManager::subscribe_tutors(
  1582. [$teacherId],
  1583. $groupInfo,
  1584. $data['c_id']
  1585. );
  1586. }
  1587. }
  1588. if (isset($groupBackup['user'][$teacherId]) &&
  1589. isset($groupBackup['user'][$teacherId][$courseInfo['code']]) &&
  1590. !empty($groupBackup['user'][$teacherId][$courseInfo['code']])
  1591. ) {
  1592. foreach ($groupBackup['user'][$teacherId][$courseInfo['code']] as $data) {
  1593. $groupInfo = GroupManager::get_group_properties($data['group_id']);
  1594. GroupManager::subscribe_users(
  1595. [$teacherId],
  1596. $groupInfo,
  1597. $data['c_id']
  1598. );
  1599. }
  1600. }
  1601. }
  1602. if ($result) {
  1603. $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
  1604. } else {
  1605. $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
  1606. }
  1607. }
  1608. }
  1609. }
  1610. if ($moveFile) {
  1611. $this->moveFile($file);
  1612. }
  1613. }
  1614. /**
  1615. * Parse filename: encora_subsessionsextid-static_31082016.csv.
  1616. *
  1617. * @param string $file
  1618. */
  1619. private function importSubscribeUserToCourseSessionExtStatic($file, $moveFile = true)
  1620. {
  1621. $data = Import::csv_reader($file);
  1622. if (!empty($data)) {
  1623. $this->logger->addInfo(count($data)." records found.");
  1624. $userIdList = [];
  1625. foreach ($data as $row) {
  1626. $chamiloUserName = $row['UserName'];
  1627. $chamiloCourseCode = $row['CourseCode'];
  1628. $externalSessionId = $row['ExtSessionID'];
  1629. $status = $row['Status'];
  1630. $chamiloSessionId = null;
  1631. if (!empty($externalSessionId)) {
  1632. $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
  1633. $externalSessionId,
  1634. $this->extraFieldIdNameList['session']
  1635. );
  1636. }
  1637. $sessionInfo = api_get_session_info($chamiloSessionId);
  1638. if (empty($sessionInfo)) {
  1639. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1640. continue;
  1641. }
  1642. $courseInfo = api_get_course_info($chamiloCourseCode);
  1643. if (empty($courseInfo)) {
  1644. $this->logger->addError('Course does not exists: '.$courseInfo);
  1645. continue;
  1646. }
  1647. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1648. if (empty($userId)) {
  1649. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1650. continue;
  1651. }
  1652. switch ($status) {
  1653. case 'student':
  1654. SessionManager::subscribe_users_to_session_course(
  1655. [$userId],
  1656. $chamiloSessionId,
  1657. $courseInfo['code']
  1658. );
  1659. break;
  1660. case 'teacher':
  1661. SessionManager::set_coach_to_course_session(
  1662. $userId,
  1663. $chamiloSessionId,
  1664. $courseInfo['code']
  1665. );
  1666. break;
  1667. case 'drh':
  1668. $removeAllSessionsFromUser = true;
  1669. if (in_array($userId, $userIdList)) {
  1670. $removeAllSessionsFromUser = false;
  1671. } else {
  1672. $userIdList[] = $userId;
  1673. }
  1674. $userInfo = api_get_user_info($userId);
  1675. SessionManager::subscribeSessionsToDrh(
  1676. $userInfo,
  1677. [$chamiloSessionId],
  1678. false,
  1679. $removeAllSessionsFromUser
  1680. );
  1681. break;
  1682. }
  1683. $this->logger->addError(
  1684. "User '$chamiloUserName' was added as '$status' to Session: #$chamiloSessionId - Course: ".$courseInfo['code']
  1685. );
  1686. }
  1687. }
  1688. if ($moveFile) {
  1689. $this->moveFile($file);
  1690. }
  1691. }
  1692. /**
  1693. * @param $file
  1694. * @param bool $moveFile
  1695. */
  1696. private function importUnsubSessionsExtIdStatic($file, $moveFile = true)
  1697. {
  1698. $data = Import::csv_reader($file);
  1699. if (!empty($data)) {
  1700. $this->logger->addInfo(count($data)." records found.");
  1701. foreach ($data as $row) {
  1702. $chamiloUserName = $row['UserName'];
  1703. $chamiloCourseCode = $row['CourseCode'];
  1704. $externalSessionId = $row['ExtSessionID'];
  1705. $dateStop = $row['DateStop'];
  1706. $chamiloSessionId = null;
  1707. if (!empty($externalSessionId)) {
  1708. $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
  1709. $externalSessionId,
  1710. $this->extraFieldIdNameList['session']
  1711. );
  1712. }
  1713. $sessionInfo = api_get_session_info($chamiloSessionId);
  1714. if (empty($sessionInfo)) {
  1715. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1716. continue;
  1717. }
  1718. $courseInfo = api_get_course_info($chamiloCourseCode);
  1719. if (empty($courseInfo)) {
  1720. $this->logger->addError('Course does not exists: '.$courseInfo);
  1721. continue;
  1722. }
  1723. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1724. if (empty($userId)) {
  1725. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1726. continue;
  1727. }
  1728. SessionManager::removeUsersFromCourseSession(
  1729. [$userId],
  1730. $chamiloSessionId,
  1731. $courseInfo
  1732. );
  1733. $this->logger->addError(
  1734. "User '$chamiloUserName' was remove from Session: #$chamiloSessionId - Course: ".$courseInfo['code']
  1735. );
  1736. }
  1737. }
  1738. if ($moveFile) {
  1739. $this->moveFile($file);
  1740. }
  1741. }
  1742. /**
  1743. * @param string $file
  1744. */
  1745. private function importSessionsExtIdStatic($file, $moveFile = true)
  1746. {
  1747. $data = Import::csv_reader($file);
  1748. if (!empty($data)) {
  1749. $this->logger->addInfo(count($data)." records found.");
  1750. foreach ($data as $row) {
  1751. $chamiloUserName = $row['UserName'];
  1752. $chamiloCourseCode = $row['CourseCode'];
  1753. $externalSessionId = $row['ExtSessionID'];
  1754. $type = $row['Type'];
  1755. $chamiloSessionId = null;
  1756. if (!empty($externalSessionId)) {
  1757. $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
  1758. $externalSessionId,
  1759. $this->extraFieldIdNameList['session']
  1760. );
  1761. }
  1762. $sessionInfo = api_get_session_info($chamiloSessionId);
  1763. if (empty($sessionInfo)) {
  1764. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1765. continue;
  1766. }
  1767. $courseInfo = api_get_course_info($chamiloCourseCode);
  1768. if (empty($courseInfo)) {
  1769. $this->logger->addError('Course does not exists: '.$courseInfo);
  1770. continue;
  1771. }
  1772. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1773. if (empty($userId)) {
  1774. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1775. continue;
  1776. }
  1777. switch ($type) {
  1778. case 'student':
  1779. SessionManager::subscribe_users_to_session_course(
  1780. [$userId],
  1781. $chamiloSessionId,
  1782. $courseInfo['code'],
  1783. null,
  1784. false
  1785. );
  1786. break;
  1787. case 'teacher':
  1788. SessionManager::set_coach_to_course_session(
  1789. $userId,
  1790. $chamiloSessionId,
  1791. $courseInfo['code']
  1792. );
  1793. break;
  1794. }
  1795. $this->logger->addError(
  1796. "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: ".$courseInfo['code']
  1797. );
  1798. }
  1799. }
  1800. if ($moveFile) {
  1801. $this->moveFile($file);
  1802. }
  1803. }
  1804. /**
  1805. * Updates the session synchronize with the csv file.
  1806. *
  1807. * @param bool $moveFile
  1808. * @param string $file
  1809. */
  1810. private function importSessionsStatic($file, $moveFile = true)
  1811. {
  1812. $content = file($file);
  1813. $sessions = [];
  1814. $tag_names = [];
  1815. foreach ($content as $key => $enreg) {
  1816. $enreg = explode(';', trim($enreg));
  1817. if ($key) {
  1818. foreach ($tag_names as $tag_key => $tag_name) {
  1819. if (isset($enreg[$tag_key])) {
  1820. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  1821. }
  1822. }
  1823. } else {
  1824. foreach ($enreg as $tag_name) {
  1825. $tag_names[] = api_preg_replace(
  1826. '/[^a-zA-Z0-9_\-]/',
  1827. '',
  1828. $tag_name
  1829. );
  1830. }
  1831. if (!in_array('SessionName', $tag_names) ||
  1832. !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)
  1833. ) {
  1834. $error_message = get_lang('NoNeededData');
  1835. break;
  1836. }
  1837. }
  1838. }
  1839. if (!empty($sessions)) {
  1840. // Looping the sessions.
  1841. foreach ($sessions as $session) {
  1842. if (!empty($session['SessionID'])) {
  1843. $sessionId = SessionManager::getSessionIdFromOriginalId(
  1844. $session['SessionID'],
  1845. $this->extraFieldIdNameList['session']
  1846. );
  1847. $coachUserName = isset($session['Coach']) ? $session['Coach'] : null;
  1848. $categoryId = isset($session['category_id']) ? $session['category_id'] : null;
  1849. // 2014-06-30
  1850. $dateStart = explode('/', $session['DateStart']);
  1851. $dateEnd = explode('/', $session['DateEnd']);
  1852. $visibility = $this->defaultSessionVisibility;
  1853. $coachId = null;
  1854. if (!empty($coachUserName)) {
  1855. $coachInfo = api_get_user_info_from_username($coachUserName);
  1856. $coachId = $coachInfo['user_id'];
  1857. }
  1858. $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
  1859. $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
  1860. $date = new \DateTime($dateStart);
  1861. $interval = new DateInterval('P'.$this->daysCoachAccessBeforeBeginning.'D');
  1862. $date->sub($interval);
  1863. $coachBefore = $date->format('Y-m-d h:i');
  1864. $date = new \DateTime($dateEnd);
  1865. $interval = new DateInterval('P'.$this->daysCoachAccessAfterBeginning.'D');
  1866. $date->add($interval);
  1867. $coachAfter = $date->format('Y-m-d h:i');
  1868. /*$dateStart = api_get_utc_datetime($dateStart);
  1869. $dateEnd = api_get_utc_datetime($dateEnd);
  1870. $coachBefore = api_get_utc_datetime($coachBefore);
  1871. $coachAfter = api_get_utc_datetime($coachAfter);*/
  1872. if (empty($sessionId)) {
  1873. $result = SessionManager::create_session(
  1874. $session['SessionName'],
  1875. $dateStart,
  1876. $dateEnd,
  1877. $dateStart,
  1878. $dateEnd,
  1879. $coachBefore,
  1880. $coachAfter,
  1881. $coachId,
  1882. $categoryId,
  1883. $visibility
  1884. );
  1885. if (is_numeric($result)) {
  1886. $sessionId = $result;
  1887. $this->logger->addInfo("Session #$sessionId created: ".$session['SessionName']);
  1888. SessionManager::update_session_extra_field_value(
  1889. $sessionId,
  1890. $this->extraFieldIdNameList['session'],
  1891. $session['SessionID']
  1892. );
  1893. } else {
  1894. $this->logger->addInfo("Failed creating session: ".$session['SessionName']);
  1895. }
  1896. } else {
  1897. $sessionInfo = api_get_session_info($sessionId);
  1898. $accessBefore = null;
  1899. $accessAfter = null;
  1900. if (empty($sessionInfo['nb_days_access_before_beginning']) ||
  1901. (!empty($sessionInfo['nb_days_access_before_beginning']) &&
  1902. $sessionInfo['nb_days_access_before_beginning'] < $this->daysCoachAccessBeforeBeginning)
  1903. ) {
  1904. $accessBefore = $coachBefore;
  1905. }
  1906. $accessAfter = null;
  1907. if (empty($sessionInfo['nb_days_access_after_end']) ||
  1908. (!empty($sessionInfo['nb_days_access_after_end']) &&
  1909. $sessionInfo['nb_days_access_after_end'] < $this->daysCoachAccessAfterBeginning)
  1910. ) {
  1911. $accessAfter = $coachAfter;
  1912. }
  1913. $showDescription = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : 1;
  1914. $result = SessionManager::edit_session(
  1915. $sessionId,
  1916. $session['SessionName'],
  1917. $dateStart,
  1918. $dateEnd,
  1919. $dateStart,
  1920. $dateEnd,
  1921. $accessBefore,
  1922. $accessAfter,
  1923. $coachId,
  1924. $categoryId,
  1925. $visibility,
  1926. null, //$description = null,
  1927. $showDescription
  1928. );
  1929. if (is_numeric($result)) {
  1930. $this->logger->addInfo("Session #$sessionId updated: ".$session['SessionName']);
  1931. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1932. $params = [
  1933. 'description' => $session['SessionDescription'],
  1934. ];
  1935. Database::update(
  1936. $tbl_session,
  1937. $params,
  1938. ['id = ?' => $sessionId]
  1939. );
  1940. }
  1941. }
  1942. if (!empty($sessionId)) {
  1943. // Courses
  1944. $courses = explode('|', $session['Courses']);
  1945. $courseList = [];
  1946. $courseListWithCoach = [];
  1947. foreach ($courses as $course) {
  1948. $courseArray = bracketsToArray($course);
  1949. $courseCode = $courseArray[0];
  1950. if (CourseManager::course_exists($courseCode)) {
  1951. $courseInfo = api_get_course_info($courseCode);
  1952. $courseList[] = $courseInfo['real_id'];
  1953. // Extracting course coaches
  1954. $courseCoaches = isset($courseArray[1]) ? $courseArray[1] : null;
  1955. $courseCoaches = explode(',', $courseCoaches);
  1956. // Extracting students
  1957. $courseUsers = isset($courseArray[2]) ? $courseArray[2] : null;
  1958. $courseUsers = explode(',', $courseUsers);
  1959. $courseListWithCoach[] = [
  1960. 'course_info' => $courseInfo,
  1961. 'coaches' => $courseCoaches,
  1962. 'course_users' => $courseUsers,
  1963. ];
  1964. }
  1965. }
  1966. SessionManager::add_courses_to_session(
  1967. $sessionId,
  1968. $courseList,
  1969. true
  1970. );
  1971. $this->logger->addInfo("Session #$sessionId: Courses added: '".implode(', ', $courseList)."'");
  1972. if (empty($courseListWithCoach)) {
  1973. $this->logger->addInfo("No users/coaches to update");
  1974. continue;
  1975. }
  1976. foreach ($courseListWithCoach as $courseData) {
  1977. $courseInfo = $courseData['course_info'];
  1978. $courseCode = $courseInfo['code'];
  1979. $courseId = $courseInfo['real_id'];
  1980. $courseCoaches = $courseData['coaches'];
  1981. $courseUsers = $courseData['course_users'];
  1982. // Coaches
  1983. if (!empty($courseCoaches)) {
  1984. $coachList = [];
  1985. foreach ($courseCoaches as $courseCoach) {
  1986. $courseCoachId = UserManager::get_user_id_from_username(
  1987. $courseCoach
  1988. );
  1989. if ($courseCoachId !== false) {
  1990. // Just insert new coaches
  1991. $coachList[] = $courseCoachId;
  1992. }
  1993. }
  1994. $this->logger->addInfo("Session #$sessionId: course '$courseCode' coaches added: '".implode(', ', $coachList)."'");
  1995. SessionManager::updateCoaches(
  1996. $sessionId,
  1997. $courseId,
  1998. $coachList,
  1999. true
  2000. );
  2001. } else {
  2002. $this->logger->addInfo("No coaches added");
  2003. }
  2004. // Students
  2005. if (!empty($courseUsers)) {
  2006. $userList = [];
  2007. foreach ($courseUsers as $username) {
  2008. $userInfo = api_get_user_info_from_username(trim($username));
  2009. if (!empty($userInfo)) {
  2010. $userList[] = $userInfo['user_id'];
  2011. }
  2012. }
  2013. $this->logger->addInfo("Session #$sessionId: course '$courseCode': Students added '".implode(', ', $userList)."'");
  2014. SessionManager::subscribe_users_to_session_course(
  2015. $userList,
  2016. $sessionId,
  2017. $courseCode,
  2018. SESSION_VISIBLE_READ_ONLY,
  2019. true
  2020. );
  2021. } else {
  2022. $this->logger->addInfo("No users to register.");
  2023. }
  2024. }
  2025. } else {
  2026. $this->logger->addInfo(
  2027. 'SessionID not found in system.'
  2028. );
  2029. }
  2030. } else {
  2031. $this->logger->addInfo('SessionID does not exists');
  2032. }
  2033. }
  2034. } else {
  2035. $this->logger->addInfo($error_message);
  2036. }
  2037. if ($moveFile) {
  2038. $this->moveFile($file);
  2039. }
  2040. }
  2041. /**
  2042. * @param $file
  2043. * @param bool $moveFile
  2044. * @param array $teacherBackup
  2045. * @param array $groupBackup
  2046. */
  2047. private function importOpenSessions(
  2048. $file,
  2049. $moveFile = true,
  2050. &$teacherBackup = [],
  2051. &$groupBackup = []
  2052. ) {
  2053. $this->importSessions($file, $moveFile, $teacherBackup, $groupBackup);
  2054. }
  2055. /**
  2056. * @param string $file
  2057. * @param bool $moveFile
  2058. * @param array $teacherBackup
  2059. * @param array $groupBackup
  2060. */
  2061. private function importSessions(
  2062. $file,
  2063. $moveFile = true,
  2064. &$teacherBackup = [],
  2065. &$groupBackup = []
  2066. ) {
  2067. $avoid = null;
  2068. if (isset($this->conditions['importSessions']) &&
  2069. isset($this->conditions['importSessions']['update'])
  2070. ) {
  2071. $avoid = $this->conditions['importSessions']['update'];
  2072. }
  2073. $result = SessionManager::importCSV(
  2074. $file,
  2075. true,
  2076. $this->defaultAdminId,
  2077. $this->logger,
  2078. [
  2079. 'SessionID' => 'extra_'.$this->extraFieldIdNameList['session'],
  2080. 'CareerId' => 'extra_'.$this->extraFieldIdNameList['session_career'],
  2081. ],
  2082. $this->extraFieldIdNameList['session'],
  2083. $this->daysCoachAccessBeforeBeginning,
  2084. $this->daysCoachAccessAfterBeginning,
  2085. $this->defaultSessionVisibility,
  2086. $avoid,
  2087. false, // deleteUsersNotInList
  2088. false, // updateCourseCoaches
  2089. true, // sessionWithCoursesModifier
  2090. true, //$addOriginalCourseTeachersAsCourseSessionCoaches
  2091. false, //$removeAllTeachersFromCourse
  2092. 1, // $showDescription,
  2093. $teacherBackup,
  2094. $groupBackup
  2095. );
  2096. if (!empty($result['error_message'])) {
  2097. $this->logger->addError($result['error_message']);
  2098. }
  2099. $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
  2100. if ($moveFile) {
  2101. $this->moveFile($file);
  2102. }
  2103. }
  2104. /**
  2105. * @param string $file
  2106. * @param bool $moveFile
  2107. */
  2108. private function importSubscribeStatic($file, $moveFile = true)
  2109. {
  2110. $data = Import::csv_reader($file);
  2111. if (!empty($data)) {
  2112. $this->logger->addInfo(count($data)." records found.");
  2113. foreach ($data as $row) {
  2114. $chamiloUserName = $row['UserName'];
  2115. $chamiloCourseCode = $row['CourseCode'];
  2116. $chamiloSessionId = $row['SessionID'];
  2117. $type = $row['Type'];
  2118. $sessionInfo = api_get_session_info($chamiloSessionId);
  2119. if (empty($sessionInfo)) {
  2120. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  2121. continue;
  2122. }
  2123. $courseInfo = api_get_course_info($chamiloCourseCode);
  2124. if (empty($courseInfo)) {
  2125. $this->logger->addError('Course does not exists: '.$courseInfo);
  2126. continue;
  2127. }
  2128. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  2129. if (empty($userId)) {
  2130. $this->logger->addError('User does not exists: '.$chamiloUserName);
  2131. continue;
  2132. }
  2133. switch ($type) {
  2134. case 'student':
  2135. SessionManager::subscribe_users_to_session_course(
  2136. [$userId],
  2137. $chamiloSessionId,
  2138. $courseInfo['code'],
  2139. null,
  2140. false
  2141. );
  2142. break;
  2143. case 'teacher':
  2144. SessionManager::set_coach_to_course_session(
  2145. $userId,
  2146. $chamiloSessionId,
  2147. $courseInfo['real_id']
  2148. );
  2149. break;
  2150. }
  2151. $this->logger->addError(
  2152. "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: ".$courseInfo['code']
  2153. );
  2154. }
  2155. }
  2156. if ($moveFile) {
  2157. $this->moveFile($file);
  2158. }
  2159. }
  2160. /**
  2161. * @param $file
  2162. * @param bool $moveFile
  2163. */
  2164. private function importSubscribeUserToCourse($file, $moveFile = false, &$teacherBackup = [])
  2165. {
  2166. $data = Import::csv_reader($file);
  2167. if (!empty($data)) {
  2168. $this->logger->addInfo(count($data)." records found.");
  2169. foreach ($data as $row) {
  2170. $chamiloUserName = $row['UserName'];
  2171. $chamiloCourseCode = $row['CourseCode'];
  2172. $status = $row['Status'];
  2173. $courseInfo = api_get_course_info($chamiloCourseCode);
  2174. if (empty($courseInfo)) {
  2175. $this->logger->addError(
  2176. 'Course does not exists: '.$chamiloCourseCode
  2177. );
  2178. continue;
  2179. }
  2180. $userId = UserManager::get_user_id_from_username(
  2181. $chamiloUserName
  2182. );
  2183. if (empty($userId)) {
  2184. $this->logger->addError(
  2185. 'User does not exists: '.$chamiloUserName
  2186. );
  2187. continue;
  2188. }
  2189. $userCourseCategory = '';
  2190. if (isset($teacherBackup[$userId]) &&
  2191. isset($teacherBackup[$userId][$courseInfo['code']])
  2192. ) {
  2193. $courseUserData = $teacherBackup[$userId][$courseInfo['code']];
  2194. $userCourseCategory = $courseUserData['user_course_cat'];
  2195. }
  2196. $result = CourseManager::subscribeUser(
  2197. $userId,
  2198. $courseInfo['code'],
  2199. $status,
  2200. 0,
  2201. $userCourseCategory
  2202. );
  2203. if ($result) {
  2204. $this->logger->addInfo(
  2205. "User $userId added to course ".$courseInfo['code']." with status '$status' with course category: '$userCourseCategory'"
  2206. );
  2207. } else {
  2208. $this->logger->addInfo(
  2209. "User $userId was NOT ADDED to course ".$courseInfo['code']." with status '$status' with course category: '$userCourseCategory'"
  2210. );
  2211. }
  2212. }
  2213. }
  2214. if ($moveFile) {
  2215. $this->moveFile($file);
  2216. }
  2217. }
  2218. /**
  2219. * 23/4/2017 to datetime.
  2220. *
  2221. * @param $string
  2222. *
  2223. * @return mixed
  2224. */
  2225. private function createDateTime($string)
  2226. {
  2227. if (empty($string)) {
  2228. return null;
  2229. }
  2230. $date = DateTime::createFromFormat('j/m/Y', $string);
  2231. if ($date) {
  2232. return $date;
  2233. }
  2234. return null;
  2235. }
  2236. /**
  2237. * @param $file
  2238. * @param bool $moveFile
  2239. * @param array $teacherBackup
  2240. * @param array $groupBackup
  2241. *
  2242. * @return bool
  2243. */
  2244. private function importCareers(
  2245. $file,
  2246. $moveFile = false,
  2247. &$teacherBackup = [],
  2248. &$groupBackup = []
  2249. ) {
  2250. $data = Import::csv_reader($file);
  2251. if (!empty($data)) {
  2252. $this->logger->addInfo(count($data)." records found.");
  2253. $extraFieldValue = new ExtraFieldValue('career');
  2254. $extraFieldName = $this->extraFieldIdNameList['career'];
  2255. $externalEventId = null;
  2256. $extraField = new ExtraField('career');
  2257. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
  2258. $extraFieldName
  2259. );
  2260. if (empty($extraFieldInfo)) {
  2261. return false;
  2262. }
  2263. foreach ($data as $row) {
  2264. foreach ($row as $key => $value) {
  2265. $key = (string) trim($key);
  2266. // Remove utf8 bom
  2267. $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
  2268. $row[$key] = $value;
  2269. }
  2270. $itemId = $row['CareerId'];
  2271. $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  2272. $extraFieldName,
  2273. $itemId,
  2274. false,
  2275. false,
  2276. false
  2277. );
  2278. $career = new Career();
  2279. if (empty($item)) {
  2280. $params = [
  2281. 'status' => 1,
  2282. 'name' => $row['CareerName'],
  2283. ];
  2284. $careerId = $career->save($params);
  2285. if ($careerId) {
  2286. $params = [
  2287. 'item_id' => $careerId,
  2288. 'extra_'.$extraFieldName => $itemId,
  2289. ];
  2290. $links = isset($row['HLinks']) ? $row['HLinks'] : [];
  2291. if (!empty($links)) {
  2292. $extraFieldUrlName = $this->extraFieldIdNameList['career_urls'];
  2293. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
  2294. $extraFieldUrlName
  2295. );
  2296. if (!empty($extraFieldInfo)) {
  2297. $params['extra_'.$extraFieldUrlName] = $links;
  2298. }
  2299. }
  2300. $extraFieldValue->saveFieldValues($params);
  2301. }
  2302. } else {
  2303. if (isset($item['item_id'])) {
  2304. $params = [
  2305. 'id' => $item['item_id'],
  2306. 'name' => $row['CareerName'],
  2307. ];
  2308. $career->update($params);
  2309. $links = isset($row['HLinks']) ? $row['HLinks'] : [];
  2310. if (!empty($links)) {
  2311. $extraFieldUrlName = $this->extraFieldIdNameList['career_urls'];
  2312. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
  2313. $extraFieldUrlName
  2314. );
  2315. if (!empty($extraFieldInfo)) {
  2316. $params = [
  2317. 'item_id' => $item['item_id'],
  2318. 'extra_'.$extraFieldName => $itemId,
  2319. 'extra_'.$extraFieldUrlName => $links,
  2320. ];
  2321. $extraFieldValue->saveFieldValues($params);
  2322. }
  2323. }
  2324. }
  2325. }
  2326. }
  2327. }
  2328. }
  2329. /**
  2330. * @param $file
  2331. * @param bool $moveFile
  2332. * @param array $teacherBackup
  2333. * @param array $groupBackup
  2334. */
  2335. private function importCareersDiagram(
  2336. $file,
  2337. $moveFile = false,
  2338. &$teacherBackup = [],
  2339. &$groupBackup = []
  2340. ) {
  2341. $data = Import::csv_reader($file);
  2342. $extraFieldValue = new ExtraFieldValue('career');
  2343. $extraFieldName = $this->extraFieldIdNameList['career'];
  2344. $externalEventId = null;
  2345. $extraField = new ExtraField('career');
  2346. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
  2347. $extraFieldName
  2348. );
  2349. $careerDiagramExtraFieldName = $this->extraFieldIdNameList['career_diagram'];
  2350. $extraFieldDiagramInfo = $extraField->get_handler_field_info_by_field_variable(
  2351. $careerDiagramExtraFieldName
  2352. );
  2353. if (empty($extraFieldInfo) || empty($extraFieldDiagramInfo)) {
  2354. return false;
  2355. }
  2356. if (!empty($data)) {
  2357. $this->logger->addInfo(count($data)." records found.");
  2358. $values = [];
  2359. foreach ($data as $row) {
  2360. if (empty($row)) {
  2361. continue;
  2362. }
  2363. foreach ($row as $key => $value) {
  2364. $key = (string) trim($key);
  2365. // Remove utf8 bom
  2366. $key = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $key);
  2367. $row[$key] = $value;
  2368. }
  2369. $values[$row['Column']][] = $row;
  2370. }
  2371. $careerList = [];
  2372. $careerNameList = [];
  2373. ksort($values);
  2374. $careerChamiloIdList = [];
  2375. // 1. First create all items
  2376. foreach ($values as $column => $rowList) {
  2377. foreach ($rowList as $row) {
  2378. $careerId = $row['CareerId'];
  2379. $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  2380. $extraFieldName,
  2381. $careerId,
  2382. false,
  2383. false,
  2384. false
  2385. );
  2386. $chamiloCareerName = '';
  2387. if (empty($item)) {
  2388. $this->logger->addInfo("Career not found: $careerId");
  2389. continue;
  2390. } else {
  2391. if (isset($item['item_id'])) {
  2392. $careerChamiloId = $item['item_id'];
  2393. $career = new Career();
  2394. $career = $career->find($careerChamiloId);
  2395. $chamiloCareerName = $career['name'];
  2396. $careerNameList[$careerId] = $chamiloCareerName;
  2397. $careerChamiloIdList[$careerId] = $careerChamiloId;
  2398. } else {
  2399. continue;
  2400. }
  2401. }
  2402. if (empty($chamiloCareerName)) {
  2403. $this->logger->addInfo("Career not found: $careerId");
  2404. continue;
  2405. }
  2406. if (isset($careerList[$careerId])) {
  2407. $graph = $careerList[$careerId];
  2408. } else {
  2409. $graph = new Graph($careerId);
  2410. $graph->setAttribute('graphviz.graph.rankdir', 'LR');
  2411. $careerList[$careerId] = $graph;
  2412. }
  2413. $currentCourseId = (int) $row['CourseId'];
  2414. $name = $row['CourseName'];
  2415. $notes = $row['Notes'];
  2416. $groupValue = $row['Group'];
  2417. $boxColumn = $row['Column'];
  2418. $rowValue = $row['Row'];
  2419. $color = isset($row['DefinedColor']) ? $row['DefinedColor'] : '';
  2420. $arrow = isset($row['DrawArrowFrom']) ? $row['DrawArrowFrom'] : '';
  2421. $subGroup = isset($row['SubGroup']) ? $row['SubGroup'] : '';
  2422. $connections = isset($row['Connections']) ? $row['Connections'] : '';
  2423. $linkedElement = isset($row['LinkedElement']) ? $row['LinkedElement'] : '';
  2424. if ($graph->hasVertex($currentCourseId)) {
  2425. // Avoid double insertion
  2426. continue;
  2427. } else {
  2428. $current = $graph->createVertex($currentCourseId);
  2429. $current->setAttribute('graphviz.label', $name);
  2430. $current->setAttribute('DefinedColor', $color);
  2431. $current->setAttribute('Notes', $notes);
  2432. $current->setAttribute('Row', $rowValue);
  2433. $current->setAttribute('Group', $groupValue);
  2434. $current->setAttribute('Column', $boxColumn);
  2435. $current->setAttribute('DrawArrowFrom', $arrow);
  2436. $current->setAttribute('SubGroup', $subGroup);
  2437. $current->setAttribute('Connections', $connections);
  2438. $current->setAttribute('LinkedElement', $linkedElement);
  2439. $current->setAttribute('graphviz.shape', 'box');
  2440. $current->setGroup($column);
  2441. }
  2442. }
  2443. }
  2444. // 2. Create connections
  2445. // $column start with 1 (depending in Column row)
  2446. foreach ($values as $column => $rowList) {
  2447. foreach ($rowList as $row) {
  2448. $careerId = $row['CareerId'];
  2449. if (isset($careerList[$careerId])) {
  2450. $graph = $careerList[$careerId];
  2451. } else {
  2452. continue;
  2453. }
  2454. $currentCourseId = (int) $row['CourseId'];
  2455. if ($graph->hasVertex($currentCourseId)) {
  2456. $current = $graph->getVertex($currentCourseId);
  2457. } else {
  2458. continue;
  2459. }
  2460. if (isset($row['DependedOn']) && !empty($row['DependedOn'])) {
  2461. $parentList = explode(',', $row['DependedOn']);
  2462. foreach ($parentList as $parentId) {
  2463. $parentId = (int) $parentId;
  2464. if ($graph->hasVertex($parentId)) {
  2465. /** @var Vertex $parent */
  2466. $parent = $graph->getVertex($parentId);
  2467. /*$parent->setAttribute('graphviz.color', 'red');
  2468. $parent->setAttribute('graphviz.label', $name);
  2469. $parent->setAttribute('graphviz.shape', 'square');*/
  2470. $parent->createEdgeTo($current);
  2471. }
  2472. }
  2473. }
  2474. }
  2475. }
  2476. /** @var Graph $graph */
  2477. foreach ($careerList as $id => $graph) {
  2478. if (isset($careerChamiloIdList[$id])) {
  2479. $params = [
  2480. 'item_id' => $careerChamiloIdList[$id],
  2481. 'extra_'.$careerDiagramExtraFieldName => serialize($graph),
  2482. 'extra_'.$extraFieldName => $id,
  2483. ];
  2484. $extraFieldValue->saveFieldValues($params, true);
  2485. }
  2486. }
  2487. }
  2488. }
  2489. /**
  2490. * @param string $file
  2491. * @param bool $moveFile
  2492. * @param array $teacherBackup
  2493. * @param array $groupBackup
  2494. */
  2495. private function importUnsubscribeStatic(
  2496. $file,
  2497. $moveFile = false,
  2498. &$teacherBackup = [],
  2499. &$groupBackup = []
  2500. ) {
  2501. $data = Import::csv_reader($file);
  2502. if (!empty($data)) {
  2503. $this->logger->addInfo(count($data)." records found.");
  2504. foreach ($data as $row) {
  2505. $chamiloUserName = $row['UserName'];
  2506. $chamiloCourseCode = $row['CourseCode'];
  2507. $chamiloSessionId = $row['SessionID'];
  2508. $sessionInfo = api_get_session_info($chamiloSessionId);
  2509. if (empty($sessionInfo)) {
  2510. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  2511. continue;
  2512. }
  2513. $courseInfo = api_get_course_info($chamiloCourseCode);
  2514. if (empty($courseInfo)) {
  2515. $this->logger->addError('Course does not exists: '.$courseInfo);
  2516. continue;
  2517. }
  2518. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  2519. if (empty($userId)) {
  2520. $this->logger->addError('User does not exists: '.$chamiloUserName);
  2521. continue;
  2522. }
  2523. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  2524. WHERE
  2525. user_id = ".$userId." AND
  2526. c_id = '".$courseInfo['real_id']."'
  2527. ";
  2528. $result = Database::query($sql);
  2529. $rows = Database::num_rows($result);
  2530. if ($rows > 0) {
  2531. $userCourseData = Database::fetch_array($result, 'ASSOC');
  2532. if (!empty($userCourseData)) {
  2533. $teacherBackup[$userId][$courseInfo['code']] = $userCourseData;
  2534. }
  2535. }
  2536. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_USER)."
  2537. WHERE
  2538. user_id = ".$userId." AND
  2539. c_id = '".$courseInfo['real_id']."'
  2540. ";
  2541. $result = Database::query($sql);
  2542. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  2543. $groupBackup['user'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
  2544. }
  2545. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  2546. WHERE
  2547. user_id = ".$userId." AND
  2548. c_id = '".$courseInfo['real_id']."'
  2549. ";
  2550. $result = Database::query($sql);
  2551. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  2552. $groupBackup['tutor'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
  2553. }
  2554. CourseManager::unsubscribe_user(
  2555. $userId,
  2556. $courseInfo['code'],
  2557. $chamiloSessionId
  2558. );
  2559. $this->logger->addError(
  2560. "User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']
  2561. );
  2562. }
  2563. }
  2564. if ($moveFile) {
  2565. $this->moveFile($file);
  2566. }
  2567. }
  2568. /**
  2569. * Dump database tables.
  2570. */
  2571. private function dumpDatabaseTables()
  2572. {
  2573. echo 'Dumping tables'.PHP_EOL;
  2574. // User
  2575. $table = Database::get_main_table(TABLE_MAIN_USER);
  2576. $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
  2577. $sql = "DELETE FROM $table
  2578. WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
  2579. Database::query($sql);
  2580. echo $sql.PHP_EOL;
  2581. // Truncate tables
  2582. $truncateTables = [
  2583. Database::get_main_table(TABLE_MAIN_COURSE),
  2584. Database::get_main_table(TABLE_MAIN_COURSE_USER),
  2585. Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE),
  2586. Database::get_main_table(TABLE_MAIN_CATEGORY),
  2587. Database::get_main_table(TABLE_MAIN_COURSE_MODULE),
  2588. Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER),
  2589. Database::get_main_table(TABLE_MAIN_SESSION),
  2590. Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY),
  2591. Database::get_main_table(TABLE_MAIN_SESSION_COURSE),
  2592. Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER),
  2593. Database::get_main_table(TABLE_MAIN_SESSION_USER),
  2594. Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION),
  2595. Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
  2596. Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
  2597. Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES),
  2598. Database::get_main_table(TABLE_MAIN_USER_FIELD),
  2599. Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS),
  2600. Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
  2601. Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
  2602. Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
  2603. Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
  2604. Database::get_course_table(TABLE_AGENDA),
  2605. Database::get_course_table(TABLE_AGENDA_ATTACHMENT),
  2606. Database::get_course_table(TABLE_AGENDA_REPEAT),
  2607. Database::get_course_table(TABLE_AGENDA_REPEAT_NOT),
  2608. Database::get_main_table(TABLE_PERSONAL_AGENDA),
  2609. Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT_NOT),
  2610. Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT),
  2611. Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_VALUES),
  2612. Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS),
  2613. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS),
  2614. Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN),
  2615. Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS),
  2616. Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES),
  2617. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT),
  2618. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING),
  2619. Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT),
  2620. Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS),
  2621. Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
  2622. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY),
  2623. Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY),
  2624. Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION),
  2625. Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG),
  2626. Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT),
  2627. Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG),
  2628. Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK),
  2629. Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY),
  2630. Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE),
  2631. Database::get_course_table(TABLE_STUDENT_PUBLICATION),
  2632. Database::get_course_table(TABLE_QUIZ_QUESTION),
  2633. Database::get_course_table(TABLE_QUIZ_TEST),
  2634. Database::get_course_table(TABLE_QUIZ_ORDER),
  2635. Database::get_course_table(TABLE_QUIZ_ANSWER),
  2636. Database::get_course_table(TABLE_QUIZ_TEST_QUESTION),
  2637. Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION),
  2638. Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY),
  2639. Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY),
  2640. Database::get_course_table(TABLE_LP_MAIN),
  2641. Database::get_course_table(TABLE_LP_ITEM),
  2642. Database::get_course_table(TABLE_LP_VIEW),
  2643. Database::get_course_table(TABLE_LP_ITEM_VIEW),
  2644. Database::get_course_table(TABLE_DOCUMENT),
  2645. Database::get_course_table(TABLE_ITEM_PROPERTY),
  2646. Database::get_course_table(TABLE_TOOL_LIST),
  2647. Database::get_course_table(TABLE_TOOL_INTRO),
  2648. Database::get_course_table(TABLE_COURSE_SETTING),
  2649. Database::get_course_table(TABLE_SURVEY),
  2650. Database::get_course_table(TABLE_SURVEY_QUESTION),
  2651. Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION),
  2652. Database::get_course_table(TABLE_SURVEY_INVITATION),
  2653. Database::get_course_table(TABLE_SURVEY_ANSWER),
  2654. Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP),
  2655. Database::get_course_table(TABLE_SURVEY_REPORT),
  2656. Database::get_course_table(TABLE_GLOSSARY),
  2657. Database::get_course_table(TABLE_LINK),
  2658. Database::get_course_table(TABLE_LINK_CATEGORY),
  2659. Database::get_course_table(TABLE_GROUP),
  2660. Database::get_course_table(TABLE_GROUP_USER),
  2661. Database::get_course_table(TABLE_GROUP_TUTOR),
  2662. Database::get_course_table(TABLE_GROUP_CATEGORY),
  2663. Database::get_course_table(TABLE_DROPBOX_CATEGORY),
  2664. Database::get_course_table(TABLE_DROPBOX_FEEDBACK),
  2665. Database::get_course_table(TABLE_DROPBOX_POST),
  2666. Database::get_course_table(TABLE_DROPBOX_FILE),
  2667. Database::get_course_table(TABLE_DROPBOX_PERSON),
  2668. ];
  2669. foreach ($truncateTables as $table) {
  2670. $sql = "TRUNCATE $table";
  2671. Database::query($sql);
  2672. echo $sql.PHP_EOL;
  2673. }
  2674. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  2675. $sql = "DELETE FROM $table WHERE tool = 'calendar_event'";
  2676. Database::query($sql);
  2677. echo $sql.PHP_EOL;
  2678. }
  2679. /**
  2680. * If csv file ends with '"' character then a '";' is added.
  2681. *
  2682. * @param string $file
  2683. */
  2684. private function fixCSVFile($file)
  2685. {
  2686. /*$f = fopen($file, 'r+');
  2687. $cursor = -1;
  2688. fseek($f, $cursor, SEEK_END);
  2689. $char = fgetc($f);
  2690. while ($char === "\n" || $char === "\r") {
  2691. fseek($f, $cursor--, SEEK_END);
  2692. $char = fgetc($f);
  2693. }
  2694. if ($char === "\"") {
  2695. fseek($f, -1, SEEK_CUR);
  2696. fwrite($f, '";');
  2697. }*/
  2698. }
  2699. }
  2700. $logger = new Logger('cron');
  2701. $emails = isset($_configuration['cron_notification_mails']) ? $_configuration['cron_notification_mails'] : null;
  2702. $minLevel = Logger::DEBUG;
  2703. if (!is_array($emails)) {
  2704. $emails = [$emails];
  2705. }
  2706. $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
  2707. $from = api_get_setting('emailAdministrator');
  2708. /*
  2709. if (!empty($emails)) {
  2710. foreach ($emails as $email) {
  2711. $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
  2712. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  2713. }
  2714. }*/
  2715. $stream = new StreamHandler(
  2716. api_get_path(SYS_ARCHIVE_PATH).'import_csv.log',
  2717. $minLevel
  2718. );
  2719. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  2720. $logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
  2721. $cronImportCSVConditions = isset($_configuration['cron_import_csv_conditions']) ? $_configuration['cron_import_csv_conditions'] : null;
  2722. echo 'See the error log here: '.api_get_path(SYS_ARCHIVE_PATH).'import_csv.log'."\n";
  2723. $import = new ImportCsv($logger, $cronImportCSVConditions);
  2724. if (isset($_configuration['default_admin_user_id_for_cron'])) {
  2725. $import->defaultAdminId = $_configuration['default_admin_user_id_for_cron'];
  2726. }
  2727. // @todo in production disable the dump option
  2728. $dump = false;
  2729. if (isset($argv[1]) && $argv[1] = '--dump') {
  2730. $dump = true;
  2731. }
  2732. if (isset($_configuration['import_csv_disable_dump']) &&
  2733. $_configuration['import_csv_disable_dump'] == true
  2734. ) {
  2735. $import->setDumpValues(false);
  2736. } else {
  2737. $import->setDumpValues($dump);
  2738. }
  2739. $import->setUpdateEmailToDummy(api_get_configuration_value('update_users_email_to_dummy_except_admins'));
  2740. // Do not moves the files to treated
  2741. if (isset($_configuration['import_csv_test'])) {
  2742. $import->test = $_configuration['import_csv_test'];
  2743. } else {
  2744. $import->test = true;
  2745. }
  2746. $languageFilesToLoad = api_get_language_files_to_load($import->defaultLanguage);
  2747. foreach ($languageFilesToLoad as $languageFile) {
  2748. include $languageFile;
  2749. }
  2750. // Set default language to be loaded
  2751. $language = $import->defaultLanguage;
  2752. global $language_interface;
  2753. $language_interface = $language;
  2754. global $language_interface_initial_value;
  2755. $language_interface_initial_value = $language;
  2756. $timeStart = microtime(true);
  2757. $import->run();
  2758. $timeEnd = microtime(true);
  2759. $executionTime = round(($timeEnd - $timeStart) / 60, 2);
  2760. $logger->addInfo("Total execution Time $executionTime Min");
  2761. if (isset($_configuration['import_csv_fix_permissions']) &&
  2762. $_configuration['import_csv_fix_permissions'] == true
  2763. ) {
  2764. $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
  2765. echo "Executing: ".$command.PHP_EOL;
  2766. system($command);
  2767. $command = "sudo find ".api_get_path(SYS_CODE_PATH)."upload/users -type d -exec chmod 777 {} \;";
  2768. echo "Executing: ".$command.PHP_EOL;
  2769. system($command);
  2770. }