import_csv.php 123 KB

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