import_csv.php 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. if (PHP_SAPI !='cli') {
  4. die('Run this script through the command line or comment this line in the code');
  5. }
  6. if (file_exists('multiple_url_fix.php')) {
  7. require 'multiple_url_fix.php';
  8. }
  9. require_once __DIR__.'/../inc/global.inc.php';
  10. ini_set('memory_limit', -1);
  11. ini_set('max_execution_time', 0);
  12. /**
  13. * Class ImportCsv
  14. */
  15. class ImportCsv
  16. {
  17. private $logger;
  18. private $dumpValues;
  19. public $test;
  20. public $defaultLanguage = 'dutch';
  21. public $extraFieldIdNameList = array(
  22. 'session' => 'external_session_id',
  23. 'course' => 'external_course_id',
  24. 'user' => 'external_user_id',
  25. 'calendar_event' => 'external_calendar_event_id'
  26. );
  27. public $defaultAdminId = 1;
  28. public $defaultSessionVisibility = 1;
  29. /**
  30. * When creating a user the expiration date is set to registration date + this value
  31. * @var int number of years
  32. */
  33. public $expirationDateInUserCreation = 1;
  34. /**
  35. * When updating a user the expiration date is set to update date + this value
  36. * @var int number of years
  37. */
  38. public $expirationDateInUserUpdate = 1;
  39. public $daysCoachAccessBeforeBeginning = 14;
  40. public $daysCoachAccessAfterBeginning = 14;
  41. public $conditions;
  42. /**
  43. * @param Logger $logger
  44. * @param array
  45. */
  46. public function __construct($logger, $conditions)
  47. {
  48. $this->logger = $logger;
  49. $this->conditions = $conditions;
  50. }
  51. /**
  52. * @param bool $dump
  53. */
  54. public function setDumpValues($dump)
  55. {
  56. $this->dumpValues = $dump;
  57. }
  58. /**
  59. * @return mixed
  60. */
  61. public function getDumpValues()
  62. {
  63. return $this->dumpValues;
  64. }
  65. /**
  66. * Runs the import process
  67. */
  68. public function run()
  69. {
  70. $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
  71. if (!is_dir($path)) {
  72. echo "The folder! $path does not exits";
  73. return 0;
  74. }
  75. if ($this->getDumpValues()) {
  76. $this->dumpDatabaseTables();
  77. }
  78. echo "Reading files: ".PHP_EOL.PHP_EOL;
  79. $files = scandir($path);
  80. $fileToProcess = array();
  81. $fileToProcessStatic = array();
  82. if (!empty($files)) {
  83. foreach ($files as $file) {
  84. $fileInfo = pathinfo($file);
  85. if ($fileInfo['extension'] == 'csv') {
  86. // Checking teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
  87. $parts = explode('_', $fileInfo['filename']);
  88. $preMethod = ucwords($parts[1]);
  89. $preMethod = str_replace('-static', 'Static', $preMethod);
  90. $method = 'import'.$preMethod;
  91. $isStatic = strpos($method, 'Static');
  92. if (method_exists($this, $method)) {
  93. if (($method == 'importUnsubscribeStatic' ||
  94. $method == 'importSubscribeStatic') ||
  95. empty($isStatic)
  96. ) {
  97. $fileToProcess[$parts[1]][] = array(
  98. 'method' => $method,
  99. 'file' => $path.$fileInfo['basename']
  100. );
  101. } else {
  102. $fileToProcessStatic[$parts[1]][] = array(
  103. 'method' => $method,
  104. 'file' => $path.$fileInfo['basename']
  105. );
  106. }
  107. } else {
  108. echo "Error - This file '$file' can't be processed.".PHP_EOL;
  109. echo "Trying to call $method".PHP_EOL;
  110. echo "The file have to has this format:".PHP_EOL;
  111. echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
  112. exit;
  113. }
  114. }
  115. }
  116. if (empty($fileToProcess) && empty($fileToProcessStatic)) {
  117. echo 'Error - no files to process.';
  118. return 0;
  119. }
  120. $this->prepareImport();
  121. $sections = array(
  122. 'students',
  123. 'teachers',
  124. 'courses',
  125. 'sessions',
  126. 'subscribe-static',
  127. 'unsubscribe-static'
  128. );
  129. foreach ($sections as $section) {
  130. $this->logger->addInfo("-- Import $section --");
  131. if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
  132. $files = $fileToProcess[$section];
  133. foreach ($files as $fileInfo) {
  134. $method = $fileInfo['method'];
  135. $file = $fileInfo['file'];
  136. echo 'File: '.$file.PHP_EOL;
  137. $this->logger->addInfo("Reading file: $file");
  138. $this->$method($file, true);
  139. }
  140. }
  141. }
  142. $sections = array(
  143. 'students-static',
  144. 'teachers-static',
  145. 'courses-static',
  146. 'sessions-static',
  147. 'calendar-static',
  148. );
  149. foreach ($sections as $section) {
  150. $this->logger->addInfo("-- Import static files $section --");
  151. if (isset($fileToProcessStatic[$section]) &&
  152. !empty($fileToProcessStatic[$section])
  153. ) {
  154. $files = $fileToProcessStatic[$section];
  155. foreach ($files as $fileInfo) {
  156. $method = $fileInfo['method'];
  157. $file = $fileInfo['file'];
  158. echo 'Static file: '.$file.PHP_EOL;
  159. $this->logger->addInfo("Reading static file: $file");
  160. $this->$method($file, true);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. /**
  167. * Prepares extra fields before the import
  168. */
  169. private function prepareImport()
  170. {
  171. // Create user extra field: extra_external_user_id
  172. UserManager::create_extra_field(
  173. $this->extraFieldIdNameList['user'],
  174. 1,
  175. 'External user id',
  176. null
  177. );
  178. // Create course extra field: extra_external_course_id
  179. CourseManager::create_course_extra_field(
  180. $this->extraFieldIdNameList['course'],
  181. 1,
  182. 'External course id'
  183. );
  184. // Create session extra field extra_external_session_id
  185. SessionManager::create_session_extra_field(
  186. $this->extraFieldIdNameList['session'],
  187. 1,
  188. 'External session id'
  189. );
  190. // Create calendar_event extra field extra_external_session_id
  191. $extraField = new ExtraField('calendar_event');
  192. $extraField->save(array(
  193. 'field_type' => ExtraField::FIELD_TYPE_TEXT,
  194. 'variable' => $this->extraFieldIdNameList['calendar_event'],
  195. 'display_text' => 'External calendar event id'
  196. ));
  197. }
  198. /**
  199. * @param string $file
  200. */
  201. private function moveFile($file)
  202. {
  203. $moved = str_replace('incoming', 'treated', $file);
  204. if ($this->test) {
  205. $result = 1;
  206. } else {
  207. $result = rename($file, $moved);
  208. }
  209. if ($result) {
  210. $this->logger->addInfo("Moving file to the treated folder: $file");
  211. } else {
  212. $this->logger->addError("Error - Cant move file to the treated folder: $file");
  213. }
  214. }
  215. /**
  216. * @param array $row
  217. *
  218. * @return array
  219. */
  220. private function cleanUserRow($row)
  221. {
  222. $row['lastname'] = $row['LastName'];
  223. $row['firstname'] = $row['FirstName'];
  224. $row['email'] = $row['Email'];
  225. $row['username'] = $row['UserName'];
  226. $row['password'] = $row['Password'];
  227. $row['auth_source'] = $row['AuthSource'];
  228. $row['official_code'] = $row['OfficialCode'];
  229. $row['phone'] = $row['PhoneNumber'];
  230. if (isset($row['StudentID'])) {
  231. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
  232. }
  233. if (isset($row['TeacherID'])) {
  234. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
  235. }
  236. return $row;
  237. }
  238. /**
  239. * @param array $row
  240. *
  241. * @return array
  242. */
  243. private function cleanCourseRow($row)
  244. {
  245. $row['title'] = $row['Title'];
  246. $row['course_code'] = $row['Code'];
  247. $row['course_category'] = $row['CourseCategory'];
  248. $row['email'] = $row['Teacher'];
  249. $row['language'] = $row['Language'];
  250. $row['teachers'] = array();
  251. if (isset($row['Teacher']) && !empty($row['Teacher'])) {
  252. $teachers = explode(',', $row['Teacher']);
  253. if (!empty($teachers)) {
  254. foreach ($teachers as $teacherUserName) {
  255. $teacherUserName = trim($teacherUserName);
  256. $userInfo = api_get_user_info_from_username($teacherUserName);
  257. if (!empty($userInfo)) {
  258. $row['teachers'][] = $userInfo['user_id'];
  259. }
  260. }
  261. }
  262. }
  263. if (isset($row['CourseID'])) {
  264. $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
  265. }
  266. return $row;
  267. }
  268. /**
  269. * File to import
  270. * @param string $file
  271. */
  272. private function importTeachersStatic($file)
  273. {
  274. $this->importTeachers($file, false);
  275. }
  276. /**
  277. * File to import
  278. * @param string $file
  279. * @param bool $moveFile
  280. */
  281. private function importTeachers($file, $moveFile = true)
  282. {
  283. $data = Import::csvToArray($file);
  284. /* Unique identifier: official-code username.
  285. Email address and password should never get updated. *ok
  286. The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
  287. A slight edit of these fields should be taken into account. ???
  288. Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
  289. We’ll handle that manually if applicable.
  290. No delete!
  291. */
  292. $language = $this->defaultLanguage;
  293. if (!empty($data)) {
  294. $this->logger->addInfo(count($data)." records found.");
  295. foreach ($data as $row) {
  296. $row = $this->cleanUserRow($row);
  297. $user_id = UserManager::get_user_id_from_original_id(
  298. $row['extra_' . $this->extraFieldIdNameList['user']],
  299. $this->extraFieldIdNameList['user']
  300. );
  301. $userInfo = array();
  302. $userInfoByOfficialCode = null;
  303. if (!empty($user_id)) {
  304. $userInfo = api_get_user_info($user_id);
  305. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  306. }
  307. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  308. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  309. // Create user
  310. $userId = UserManager::create_user(
  311. $row['firstname'],
  312. $row['lastname'],
  313. COURSEMANAGER,
  314. $row['email'],
  315. $row['username'],
  316. $row['password'],
  317. $row['official_code'],
  318. $language, //$row['language'],
  319. $row['phone'],
  320. null, //$row['picture'], //picture
  321. PLATFORM_AUTH_SOURCE, // ?
  322. $expirationDate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  323. 1, //active
  324. 0,
  325. null, // extra
  326. null, //$encrypt_method = '',
  327. false //$send_mail = false
  328. );
  329. if ($userId) {
  330. foreach ($row as $key => $value) {
  331. if (substr($key, 0, 6) == 'extra_') {
  332. //an extra field
  333. UserManager::update_extra_field_value($userId, substr($key, 6), $value);
  334. }
  335. }
  336. $this->logger->addInfo("Teachers - User created: ".$row['username']);
  337. } else {
  338. $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  339. }
  340. } else {
  341. if (empty($userInfo)) {
  342. $this->logger->addError("Teachers - Can't update user :".$row['username']);
  343. continue;
  344. }
  345. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  346. // Update user
  347. $result = UserManager::update_user(
  348. $userInfo['user_id'],
  349. $row['firstname'], // <<-- changed
  350. $row['lastname'], // <<-- changed
  351. $userInfo['username'],
  352. null, //$password = null,
  353. PLATFORM_AUTH_SOURCE,
  354. $userInfo['email'],
  355. COURSEMANAGER,
  356. $userInfo['official_code'],
  357. $userInfo['phone'],
  358. $userInfo['picture_uri'],
  359. $expirationDate,
  360. $userInfo['active'],
  361. null, //$creator_id = null,
  362. 0, //$hr_dept_id = 0,
  363. null, // $extra = null,
  364. null, //$language = 'english',
  365. null, //$encrypt_method = '',
  366. false, //$send_email = false,
  367. 0 //$reset_password = 0
  368. );
  369. if ($result) {
  370. foreach ($row as $key => $value) {
  371. if (substr($key, 0, 6) == 'extra_') {
  372. //an extra field
  373. UserManager::update_extra_field_value(
  374. $userInfo['user_id'],
  375. substr($key, 6),
  376. $value
  377. );
  378. }
  379. }
  380. $this->logger->addInfo("Teachers - User updated: ".$row['username']);
  381. } else {
  382. $this->logger->addError("Teachers - User not updated: ".$row['username']);
  383. }
  384. }
  385. }
  386. }
  387. if ($moveFile) {
  388. $this->moveFile($file);
  389. }
  390. }
  391. /**
  392. * @param string $file
  393. */
  394. private function importStudentsStatic($file)
  395. {
  396. $this->importStudents($file, false);
  397. }
  398. /**
  399. * @param string $file
  400. * @param bool $moveFile
  401. */
  402. private function importStudents($file, $moveFile = true)
  403. {
  404. $data = Import::csvToArray($file);
  405. $userRepository = UserManager::getRepository();
  406. /*
  407. * Another users import.
  408. Unique identifier: official code and username . ok
  409. Password should never get updated. ok
  410. If an update should need to occur (because it changed in the .csv),
  411. we’ll want that logged. We will handle this manually in that case.
  412. All other fields should be updateable, though passwords should of course not get updated. ok
  413. If a user gets deleted (not there anymore),
  414. He should be set inactive one year after the current date.
  415. So I presume you’ll just update the expiration date. We want to grant access to courses up to a year after deletion.
  416. */
  417. if (!empty($data)) {
  418. $language = $this->defaultLanguage;
  419. $this->logger->addInfo(count($data)." records found.");
  420. foreach ($data as $row) {
  421. $row = $this->cleanUserRow($row);
  422. $user_id = UserManager::get_user_id_from_original_id(
  423. $row['extra_'.$this->extraFieldIdNameList['user']],
  424. $this->extraFieldIdNameList['user']
  425. );
  426. $userInfo = array();
  427. $userInfoByOfficialCode = null;
  428. if (!empty($user_id)) {
  429. $userInfo = api_get_user_info($user_id);
  430. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  431. }
  432. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  433. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  434. // Create user
  435. $result = UserManager::create_user(
  436. $row['firstname'],
  437. $row['lastname'],
  438. STUDENT,
  439. $row['email'],
  440. $row['username'],
  441. $row['password'],
  442. $row['official_code'],
  443. $language, //$row['language'],
  444. $row['phone'],
  445. null, //$row['picture'], //picture
  446. PLATFORM_AUTH_SOURCE, // ?
  447. $expirationDate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  448. 1, //active
  449. 0,
  450. null, // extra
  451. null, //$encrypt_method = '',
  452. false //$send_mail = false
  453. );
  454. if ($result) {
  455. foreach ($row as $key => $value) {
  456. if (substr($key, 0, 6) == 'extra_') {
  457. //an extra field
  458. UserManager::update_extra_field_value($result, substr($key, 6), $value);
  459. }
  460. }
  461. $this->logger->addInfo("Students - User created: ".$row['username']);
  462. } else {
  463. $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  464. }
  465. } else {
  466. if (empty($userInfo)) {
  467. $this->logger->addError("Students - Can't update user :".$row['username']);
  468. continue;
  469. }
  470. if ($row['action'] == 'delete') {
  471. // Inactive one year later
  472. $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
  473. }
  474. $password = $row['password']; // change password
  475. $email = $row['email']; // change email
  476. $resetPassword = 2; // allow password change
  477. // Conditions that disables the update of password and email:
  478. if (isset($this->conditions['importStudents'])) {
  479. if (isset($this->conditions['importStudents']['update']) &&
  480. isset($this->conditions['importStudents']['update']['avoid'])
  481. ) {
  482. // Blocking email update -
  483. // 1. Condition
  484. $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
  485. if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
  486. $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
  487. // Do not change email keep the old email.
  488. $email = $userInfo['email'];
  489. }
  490. // 2. Condition
  491. if (!in_array($userInfo['email'], $avoidUsersWithEmail) &&
  492. !in_array($row['email'], $avoidUsersWithEmail)
  493. ) {
  494. $email = $userInfo['email'];
  495. }
  496. // 3. Condition
  497. if (in_array($userInfo['email'], $avoidUsersWithEmail) &&
  498. !in_array($row['email'], $avoidUsersWithEmail)
  499. ) {
  500. $email = $row['email'];
  501. }
  502. // Blocking password update
  503. $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
  504. $user = $userRepository->find($userInfo['user_id']);
  505. if ($userInfo['password'] != UserManager::encryptPassword($row['password'], $user) &&
  506. in_array($row['password'], $avoidUsersWithPassword)
  507. ) {
  508. $this->logger->addInfo("Students - User password is not updated: ".$row['username']." because the avoid conditions (password).");
  509. $password = null;
  510. $resetPassword = 0; // disallow password change
  511. }
  512. }
  513. }
  514. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  515. // Update user
  516. $result = UserManager::update_user(
  517. $userInfo['user_id'],
  518. $row['firstname'], // <<-- changed
  519. $row['lastname'], // <<-- changed
  520. $row['username'], // <<-- changed
  521. $password, //$password = null,
  522. PLATFORM_AUTH_SOURCE,
  523. $email,
  524. STUDENT,
  525. $userInfo['official_code'],
  526. $userInfo['phone'],
  527. $userInfo['picture_uri'],
  528. $expirationDate,
  529. $userInfo['active'],
  530. null, //$creator_id = null,
  531. 0, //$hr_dept_id = 0,
  532. null, // $extra = null,
  533. null, //$language = 'english',
  534. null, //$encrypt_method = '',
  535. false, //$send_email = false,
  536. $resetPassword //$reset_password = 0
  537. );
  538. if ($result) {
  539. if ($row['username'] != $userInfo['username']) {
  540. $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
  541. }
  542. foreach ($row as $key => $value) {
  543. if (substr($key, 0, 6) == 'extra_') {
  544. //an extra field
  545. UserManager::update_extra_field_value(
  546. $userInfo['user_id'],
  547. substr($key, 6),
  548. $value
  549. );
  550. }
  551. }
  552. $this->logger->addInfo("Students - User updated: ".$row['username']);
  553. } else {
  554. $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  555. }
  556. }
  557. }
  558. }
  559. if ($moveFile) {
  560. $this->moveFile($file);
  561. }
  562. }
  563. /**
  564. * @param string $file
  565. */
  566. private function importCoursesStatic($file)
  567. {
  568. $this->importCourses($file, false);
  569. }
  570. /**
  571. * @param string $file
  572. * @param bool $moveFile
  573. *
  574. * @return int
  575. */
  576. private function importCalendarStatic($file, $moveFile = true)
  577. {
  578. $data = Import::csvToArray($file);
  579. if ($this->getDumpValues()) {
  580. // Remove all calendar items
  581. $truncateTables = array(
  582. Database::get_course_table(TABLE_AGENDA),
  583. Database::get_course_table(TABLE_AGENDA_ATTACHMENT),
  584. Database::get_course_table(TABLE_AGENDA_REPEAT),
  585. Database::get_course_table(TABLE_AGENDA_REPEAT_NOT),
  586. Database::get_main_table(TABLE_PERSONAL_AGENDA),
  587. Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT_NOT),
  588. Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT)
  589. );
  590. foreach ($truncateTables as $table) {
  591. $sql = "TRUNCATE $table";
  592. Database::query($sql);
  593. }
  594. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  595. $sql = "DELETE FROM $table WHERE tool = 'calendar_event'";
  596. Database::query($sql);
  597. }
  598. if (!empty($data)) {
  599. $this->logger->addInfo(count($data) . " records found.");
  600. $eventsToCreate = array();
  601. $errorFound = false;
  602. foreach ($data as $row) {
  603. $sessionId = null;
  604. $externalSessionId = null;
  605. if (isset($row['external_sessionID'])) {
  606. $externalSessionId = $row['external_sessionID'];
  607. $sessionId = SessionManager::getSessionIdFromOriginalId(
  608. $externalSessionId,
  609. $this->extraFieldIdNameList['session']
  610. );
  611. }
  612. $courseCode = null;
  613. if (isset($row['coursecode'])) {
  614. $courseCode = $row['coursecode'];
  615. }
  616. $courseInfo = api_get_course_info($courseCode);
  617. if (empty($courseInfo)) {
  618. $this->logger->addInfo("Course '$courseCode' does not exists");
  619. }
  620. if (empty($sessionId)) {
  621. $this->logger->addInfo("external_sessionID: ".$externalSessionId." does not exists.");
  622. }
  623. $teacherId = null;
  624. if (!empty($sessionId) && !empty($courseInfo)) {
  625. $courseIncluded = SessionManager::relation_session_course_exist(
  626. $sessionId,
  627. $courseInfo['real_id']
  628. );
  629. if ($courseIncluded == false) {
  630. $this->logger->addInfo(
  631. "Course '$courseCode' is not included in session: $sessionId"
  632. );
  633. $errorFound = true;
  634. } else {
  635. $teachers = CourseManager::get_coach_list_from_course_code(
  636. $courseInfo['code'],
  637. $sessionId
  638. );
  639. // Getting first teacher.
  640. if (!empty($teachers)) {
  641. $teacher = current($teachers);
  642. $teacherId = $teacher['user_id'];
  643. } else {
  644. $sessionInfo = api_get_session_info($sessionId);
  645. $teacherId = $sessionInfo['id_coach'];
  646. }
  647. }
  648. } else {
  649. $errorFound = true;
  650. }
  651. if (empty($teacherId)) {
  652. $errorFound = true;
  653. $this->logger->addInfo(
  654. "No teacher found in course code : '$courseCode' and session: '$sessionId'"
  655. );
  656. }
  657. $date = $row['date'];
  658. $startTime = $row['time_start'];
  659. $endTime = $row['time_end'];
  660. $title = $row['title'];
  661. $startDateYear = substr($date, 0, 4);
  662. $startDateMonth = substr($date, 4, 2);
  663. $startDateDay = substr($date, 6, 8);
  664. $startDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$startTime.":00";
  665. $endDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$endTime.":00";
  666. if (!api_is_valid_date($startDate) OR !api_is_valid_date($endDate)) {
  667. $this->logger->addInfo(
  668. "Verify your dates: '$startDate' : '$endDate' "
  669. );
  670. $errorFound = true;
  671. }
  672. if ($errorFound == false) {
  673. $eventsToCreate[] = array(
  674. 'start' => $startDate,
  675. 'end' => $endDate,
  676. 'title' => $title,
  677. 'sender_id' => $teacherId,
  678. 'course_id' => $courseInfo['real_id'],
  679. 'session_id' => $sessionId,
  680. $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID']
  681. );
  682. }
  683. }
  684. if (empty($eventsToCreate)) {
  685. $this->logger->addInfo(
  686. "No events to add"
  687. );
  688. return 0;
  689. }
  690. $this->logger->addInfo(
  691. "Ready to insert events"
  692. );
  693. $content = null;
  694. $agenda = new Agenda();
  695. $extraFieldValue = new ExtraFieldValue('calendar_event');
  696. $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
  697. $externalEventId = null;
  698. $extraField = new ExtraField('calendar_event');
  699. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable($extraFieldName);
  700. if (empty($extraFieldInfo)) {
  701. $this->logger->addInfo(
  702. "No calendar event extra field created: $extraFieldName"
  703. );
  704. return 0;
  705. }
  706. foreach ($eventsToCreate as $event) {
  707. if (!isset($event[$extraFieldName])) {
  708. $this->logger->addInfo(
  709. "No external_calendar_itemID found. Skipping ..."
  710. );
  711. continue;
  712. } else {
  713. $externalEventId = $event[$extraFieldName];
  714. $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  715. $extraFieldName,
  716. $externalEventId
  717. );
  718. if (!empty($item) || empty($externalEventId)) {
  719. $this->logger->addInfo(
  720. "Event #$externalEventId was already added . Skipping ..."
  721. );
  722. continue;
  723. }
  724. }
  725. $courseInfo = api_get_course_info_by_id($event['course_id']);
  726. $agenda->set_course($courseInfo);
  727. $agenda->setType('course');
  728. $agenda->setSessionId($event['session_id']);
  729. $agenda->setSenderId($event['sender_id']);
  730. $agenda->setIsAllowedToEdit(true);
  731. $eventComment = $event['comment'];
  732. if (empty($courseInfo)) {
  733. $this->logger->addInfo(
  734. "No course found for added: #".$event['course_id']." Skipping ..."
  735. );
  736. continue;
  737. }
  738. if (empty($event['sender_id'])) {
  739. $this->logger->addInfo(
  740. "No sender found: #".$event['sender_id']." Skipping ..."
  741. );
  742. continue;
  743. }
  744. $eventId = $agenda->addEvent(
  745. $event['start'],
  746. $event['end'],
  747. false,
  748. $event['title'],
  749. $content,
  750. array('everyone'), // send to
  751. false, //$addAsAnnouncement = false
  752. null, // $parentEventId
  753. array(), //$attachmentArray = array(),
  754. null, //$attachmentComment = null,
  755. $eventComment
  756. );
  757. if (!empty($eventId)) {
  758. $extraFieldValue->save(
  759. array(
  760. 'value' => $externalEventId,
  761. 'field_id' => $extraFieldInfo['id'],
  762. 'item_id' => $eventId
  763. )
  764. );
  765. $this->logger->addInfo(
  766. "Event added: #$eventId"
  767. );
  768. } else {
  769. $this->logger->addInfo(
  770. "Error while creating event."
  771. );
  772. }
  773. }
  774. }
  775. if ($moveFile) {
  776. $this->moveFile($file);
  777. }
  778. }
  779. /**
  780. * @param string $file
  781. * @param bool $moveFile
  782. */
  783. private function importCourses($file, $moveFile = true)
  784. {
  785. $data = Import::csvToArray($file);
  786. if (!empty($data)) {
  787. $this->logger->addInfo(count($data)." records found.");
  788. foreach ($data as $row) {
  789. $row = $this->cleanCourseRow($row);
  790. $courseId = CourseManager::getCourseInfoFromOriginalId(
  791. $row['extra_' . $this->extraFieldIdNameList['course']],
  792. $this->extraFieldIdNameList['course']
  793. );
  794. $courseInfo = api_get_course_info_by_id($courseId);
  795. if (empty($courseInfo)) {
  796. // Create
  797. $params = array();
  798. $params['title'] = $row['title'];
  799. $params['exemplary_content'] = false;
  800. $params['wanted_code'] = $row['course_code'];
  801. $params['course_category'] = $row['course_category'];
  802. $params['course_language'] = $row['language'];
  803. $params['teachers'] = $row['teachers'];
  804. $courseInfo = CourseManager::create_course($params);
  805. if (!empty($courseInfo)) {
  806. CourseManager::update_course_extra_field_value(
  807. $courseInfo['code'],
  808. 'external_course_id',
  809. $row['extra_'.$this->extraFieldIdNameList['course']]
  810. );
  811. $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
  812. } else {
  813. $this->logger->addError("Courses - Can't create course:".$row['title']);
  814. }
  815. } else {
  816. // Update
  817. $params = array(
  818. 'title' => $row['title'],
  819. );
  820. $result = CourseManager::update_attributes($courseInfo['real_id'], $params);
  821. $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
  822. if ($addTeacherToSession) {
  823. CourseManager::updateTeachers($courseInfo['real_id'], $row['teachers'], false, true, false);
  824. } else {
  825. CourseManager::updateTeachers($courseInfo['real_id'], $row['teachers'], false, false);
  826. }
  827. if ($result) {
  828. $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
  829. } else {
  830. $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
  831. }
  832. }
  833. }
  834. }
  835. if ($moveFile) {
  836. $this->moveFile($file);
  837. }
  838. }
  839. /**
  840. * Updates the session synchronize with the csv file.
  841. * @param string $file
  842. */
  843. private function importSessionsStatic($file)
  844. {
  845. $content = file($file);
  846. $sessions = array();
  847. if (!api_strstr($content[0], ';')) {
  848. $error_message = get_lang('NotCSV');
  849. } else {
  850. $tag_names = array();
  851. foreach ($content as $key => $enreg) {
  852. $enreg = explode(';', trim($enreg));
  853. if ($key) {
  854. foreach ($tag_names as $tag_key => $tag_name) {
  855. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  856. }
  857. } else {
  858. foreach ($enreg as $tag_name) {
  859. $tag_names[] = api_preg_replace(
  860. '/[^a-zA-Z0-9_\-]/',
  861. '',
  862. $tag_name
  863. );
  864. }
  865. if (!in_array('SessionName', $tag_names) || !in_array(
  866. 'DateStart',
  867. $tag_names
  868. ) || !in_array('DateEnd', $tag_names)
  869. ) {
  870. $error_message = get_lang('NoNeededData');
  871. break;
  872. }
  873. }
  874. }
  875. }
  876. if (!empty($sessions)) {
  877. // Looping the sessions.
  878. foreach ($sessions as $session) {
  879. if (!empty($session['SessionID'])) {
  880. $sessionId = SessionManager::getSessionIdFromOriginalId(
  881. $session['SessionID'],
  882. $this->extraFieldIdNameList['session']
  883. );
  884. $coachUserName = isset($session['Coach']) ? $session['Coach'] : null;
  885. $categoryId = isset($session['category_id']) ? $session['category_id'] : null;
  886. // 2014-06-30
  887. $dateStart = str_replace('/', '-', $session['DateStart']);
  888. $dateEnd = str_replace('/', '-', $session['DateEnd']);
  889. $visibility = $this->defaultSessionVisibility;
  890. $coachId = null;
  891. if (!empty($coachUserName)) {
  892. $coachInfo = api_get_user_info_from_username($coachUserName);
  893. $coachId = $coachInfo['user_id'];
  894. }
  895. $coachStartDate = null;
  896. if (!empty($this->daysCoachAccessBeforeBeginning)) {
  897. $day = intval($this->daysCoachAccessBeforeBeginning);
  898. $coachStartDate = date('Y-m-d ', strtotime($dateStart. ' + '.$day.' days'));
  899. }
  900. $coachEndDate = null;
  901. if (!empty($this->daysCoachAccessAfterBeginning)) {
  902. $day = intval($this->daysCoachAccessAfterBeginning);
  903. $coachEndDate = date('Y-m-d ', strtotime($dateEnd. ' + '.$day.' days'));
  904. }
  905. if (empty($sessionId)) {
  906. $result = SessionManager::create_session(
  907. $session['SessionName'],
  908. $dateStart,
  909. $dateEnd,
  910. $dateStart,
  911. $dateEnd,
  912. $coachStartDate,
  913. $coachEndDate,
  914. $coachId,
  915. $categoryId,
  916. $visibility
  917. );
  918. if (is_numeric($result)) {
  919. $sessionId = $result;
  920. SessionManager::update_session_extra_field_value(
  921. $sessionId,
  922. $this->extraFieldIdNameList['session'],
  923. $session['SessionID']
  924. );
  925. }
  926. } else {
  927. $sessionInfo = api_get_session_info($sessionId);
  928. $showDescription = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : 1;
  929. $result = SessionManager::edit_session(
  930. $sessionId,
  931. $session['SessionName'],
  932. $dateStart,
  933. $dateEnd,
  934. $dateStart,
  935. $dateEnd,
  936. $sessionInfo['coach_access_start_date'],
  937. $sessionInfo['coach_access_end_date'],
  938. $coachId,
  939. $categoryId,
  940. $visibility,
  941. null, //$description
  942. $showDescription // $showDescription = null,
  943. );
  944. if (is_numeric($result)) {
  945. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  946. $params = array(
  947. 'description' => $session['SessionDescription'],
  948. );
  949. Database::update(
  950. $tbl_session,
  951. $params,
  952. array('id = ?' => $sessionId)
  953. );
  954. }
  955. }
  956. // Courses
  957. $courses = explode('|', $session['Courses']);
  958. $courseList = array();
  959. foreach ($courses as $course) {
  960. $courseArray = bracketsToArray($course);
  961. $courseCode = $courseArray[0];
  962. if (CourseManager::course_exists($courseCode)) {
  963. $courseList[] = $courseCode;
  964. }
  965. }
  966. SessionManager::add_courses_to_session(
  967. $sessionId,
  968. $courseList,
  969. true
  970. );
  971. if (!empty($sessionId)) {
  972. $courses = explode('|', $session['Courses']);
  973. foreach ($courses as $course) {
  974. $courseArray = bracketsToArray($course);
  975. $courseCode = $courseArray[0];
  976. $courseInfo = api_get_course_info($courseCode);
  977. if (CourseManager::course_exists($courseCode)) {
  978. // Coaches
  979. $courseCoaches = isset($courseArray[1]) ? $courseArray[1] : null;
  980. $courseCoaches = explode(',', $courseCoaches);
  981. if (!empty($courseCoaches)) {
  982. $coachList = array();
  983. foreach ($courseCoaches as $courseCoach) {
  984. $courseCoachId = UserManager::get_user_id_from_username($courseCoach);
  985. if ($courseCoachId !== false) {
  986. // Just insert new coaches
  987. $coachList[] = $courseCoachId;
  988. }
  989. }
  990. SessionManager::updateCoaches(
  991. $sessionId,
  992. $courseInfo['real_id'],
  993. $coachList,
  994. true
  995. );
  996. }
  997. // Students
  998. $courseUsers = isset($courseArray[2]) ? $courseArray[2] : null;
  999. $courseUsers = explode(',', $courseUsers);
  1000. if (!empty($courseUsers)) {
  1001. $userList = array();
  1002. foreach ($courseUsers as $username) {
  1003. $userInfo = api_get_user_info_from_username(trim($username));
  1004. if (!empty($userInfo)) {
  1005. $userList[] = $userInfo['user_id'];
  1006. }
  1007. }
  1008. SessionManager::subscribe_users_to_session_course(
  1009. $userList,
  1010. $sessionId,
  1011. $courseCode,
  1012. SESSION_VISIBLE_READ_ONLY,
  1013. true
  1014. );
  1015. } else {
  1016. $this->logger->addInfo("No users to register.");
  1017. }
  1018. } else {
  1019. $this->logger->addInfo("Course does not exists $courseCode");
  1020. }
  1021. }
  1022. } else {
  1023. $this->logger->addInfo('SessionID not found in system.');
  1024. }
  1025. } else {
  1026. $this->logger->addInfo('SessionID does not exists');
  1027. }
  1028. }
  1029. } else {
  1030. $this->logger->addInfo($error_message);
  1031. }
  1032. }
  1033. /**
  1034. * @param string $file
  1035. * @param bool $moveFile
  1036. */
  1037. private function importSessions($file, $moveFile = true)
  1038. {
  1039. $avoid = null;
  1040. if (isset($this->conditions['importSessions']) &&
  1041. isset($this->conditions['importSessions']['update'])
  1042. ) {
  1043. $avoid = $this->conditions['importSessions']['update'];
  1044. }
  1045. $result = SessionManager::importCSV(
  1046. $file,
  1047. true,
  1048. $this->defaultAdminId,
  1049. $this->logger,
  1050. array('SessionID' => 'extra_'.$this->extraFieldIdNameList['session']),
  1051. $this->extraFieldIdNameList['session'],
  1052. $this->daysCoachAccessBeforeBeginning,
  1053. $this->daysCoachAccessAfterBeginning,
  1054. $this->defaultSessionVisibility,
  1055. $avoid,
  1056. false, // deleteUsersNotInList
  1057. false, // updateCourseCoaches
  1058. true, // sessionWithCoursesModifier
  1059. true, //$addOriginalCourseTeachersAsCourseSessionCoaches
  1060. true, //$removeAllTeachersFromCourse
  1061. 1 // $showDescription
  1062. );
  1063. if (!empty($result['error_message'])) {
  1064. $this->logger->addError($result['error_message']);
  1065. }
  1066. $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
  1067. if ($moveFile) {
  1068. $this->moveFile($file);
  1069. }
  1070. }
  1071. /**
  1072. * @param string $file
  1073. */
  1074. private function importSubscribeStatic($file)
  1075. {
  1076. $data = Import::csv_reader($file);
  1077. if (!empty($data)) {
  1078. $this->logger->addInfo(count($data) . " records found.");
  1079. foreach ($data as $row) {
  1080. $chamiloUserName = $row['UserName'];
  1081. $chamiloCourseCode = $row['CourseCode'];
  1082. $chamiloSessionId = $row['SessionID'];
  1083. $type = $row['Type'];
  1084. $sessionInfo = api_get_session_info($chamiloSessionId);
  1085. if (empty($sessionInfo)) {
  1086. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1087. continue;
  1088. }
  1089. $courseInfo = api_get_course_info($chamiloCourseCode);
  1090. if (empty($courseInfo)) {
  1091. $this->logger->addError('Course does not exists: '.$courseInfo);
  1092. continue;
  1093. }
  1094. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1095. if (empty($userId)) {
  1096. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1097. continue;
  1098. }
  1099. $status = null;
  1100. switch ($type) {
  1101. case 'student':
  1102. SessionManager::subscribe_users_to_session_course(
  1103. array($userId),
  1104. $chamiloSessionId,
  1105. $courseInfo['code'],
  1106. null,
  1107. false
  1108. );
  1109. break;
  1110. case 'teacher':
  1111. SessionManager::set_coach_to_course_session(
  1112. $userId,
  1113. $chamiloSessionId,
  1114. $courseInfo['real_id']
  1115. );
  1116. break;
  1117. }
  1118. $this->logger->addError(
  1119. "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: " . $courseInfo['code']
  1120. );
  1121. }
  1122. }
  1123. }
  1124. /**
  1125. * @param string $file
  1126. */
  1127. private function importUnsubscribeStatic($file)
  1128. {
  1129. $data = Import::csv_reader($file);
  1130. if (!empty($data)) {
  1131. $this->logger->addInfo(count($data)." records found.");
  1132. foreach ($data as $row) {
  1133. $chamiloUserName = $row['UserName'];
  1134. $chamiloCourseCode = $row['CourseCode'];
  1135. $chamiloSessionId = $row['SessionID'];
  1136. $sessionInfo = api_get_session_info($chamiloSessionId);
  1137. if (empty($sessionInfo)) {
  1138. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1139. continue;
  1140. }
  1141. $courseInfo = api_get_course_info($chamiloCourseCode);
  1142. if (empty($courseInfo)) {
  1143. $this->logger->addError('Course does not exists: '.$courseInfo);
  1144. continue;
  1145. }
  1146. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1147. if (empty($userId)) {
  1148. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1149. continue;
  1150. }
  1151. CourseManager::unsubscribe_user($userId, $courseInfo['code'], $chamiloSessionId);
  1152. $this->logger->addError(
  1153. "User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']
  1154. );
  1155. }
  1156. }
  1157. }
  1158. /**
  1159. * Dump database tables
  1160. */
  1161. private function dumpDatabaseTables()
  1162. {
  1163. echo 'Dumping tables'.PHP_EOL;
  1164. // User
  1165. $table = Database::get_main_table(TABLE_MAIN_USER);
  1166. $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
  1167. $sql = "DELETE FROM $table
  1168. WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
  1169. Database::query($sql);
  1170. echo $sql.PHP_EOL;
  1171. // Course
  1172. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  1173. $sql = "DELETE FROM $table";
  1174. Database::query($sql);
  1175. echo $sql.PHP_EOL;
  1176. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  1177. $sql = "DELETE FROM $table";
  1178. Database::query($sql);
  1179. echo $sql.PHP_EOL;
  1180. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1181. $sql = "DELETE FROM $table";
  1182. Database::query($sql);
  1183. echo $sql.PHP_EOL;
  1184. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  1185. $sql = "DELETE FROM $table";
  1186. Database::query($sql);
  1187. echo $sql.PHP_EOL;
  1188. // Sessions
  1189. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  1190. $sql = "DELETE FROM $table";
  1191. Database::query($sql);
  1192. echo $sql.PHP_EOL;
  1193. $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  1194. $sql = "DELETE FROM $table";
  1195. Database::query($sql);
  1196. echo $sql.PHP_EOL;
  1197. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  1198. $sql = "DELETE FROM $table";
  1199. Database::query($sql);
  1200. echo $sql.PHP_EOL;
  1201. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  1202. $sql = "DELETE FROM $table";
  1203. Database::query($sql);
  1204. echo $sql.PHP_EOL;
  1205. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  1206. $sql = "DELETE FROM $table";
  1207. Database::query($sql);
  1208. echo $sql.PHP_EOL;
  1209. // Extra fields
  1210. $table = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
  1211. $sql = "DELETE FROM $table";
  1212. Database::query($sql);
  1213. echo $sql.PHP_EOL;
  1214. }
  1215. }
  1216. use Monolog\Handler\BufferHandler;
  1217. use Monolog\Handler\RotatingFileHandler;
  1218. use Monolog\Handler\StreamHandler;
  1219. use Monolog\Logger;
  1220. $logger = new Logger('cron');
  1221. $emails = isset($_configuration['cron_notification_mails']) ? $_configuration['cron_notification_mails'] : null;
  1222. $minLevel = Logger::DEBUG;
  1223. if (!is_array($emails)) {
  1224. $emails = array($emails);
  1225. }
  1226. $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
  1227. $from = api_get_setting('emailAdministrator');
  1228. /*
  1229. if (!empty($emails)) {
  1230. foreach ($emails as $email) {
  1231. $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
  1232. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  1233. }
  1234. }*/
  1235. $stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
  1236. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  1237. $logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
  1238. $cronImportCSVConditions = isset($_configuration['cron_import_csv_conditions']) ? $_configuration['cron_import_csv_conditions'] : null;
  1239. echo 'See the error log here: '.api_get_path(SYS_ARCHIVE_PATH).'import_csv.log'."\n";
  1240. $import = new ImportCsv($logger, $cronImportCSVConditions);
  1241. if (isset($_configuration['default_admin_user_id_for_cron'])) {
  1242. $import->defaultAdminId = $_configuration['default_admin_user_id_for_cron'];
  1243. }
  1244. // @todo in production disable the dump option
  1245. $dump = false;
  1246. if (isset($argv[1]) && $argv[1] = '--dump') {
  1247. $dump = true;
  1248. }
  1249. if (isset($_configuration['import_csv_disable_dump']) &&
  1250. $_configuration['import_csv_disable_dump'] == true
  1251. ) {
  1252. $import->setDumpValues(false);
  1253. } else {
  1254. $import->setDumpValues($dump);
  1255. }
  1256. // Do not moves the files to treated
  1257. if (isset($_configuration['import_csv_test'])) {
  1258. $import->test = $_configuration['import_csv_test'];
  1259. } else {
  1260. $import->test = true;
  1261. }
  1262. $import->run();
  1263. if (isset($_configuration['import_csv_fix_permissions']) &&
  1264. $_configuration['import_csv_fix_permissions'] == true
  1265. ) {
  1266. $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
  1267. echo "Executing: ".$command.PHP_EOL;
  1268. system($command);
  1269. $command = "sudo find ".api_get_path(SYS_UPLOAD_PATH)."users -type d -exec chmod 777 {} \;";
  1270. echo "Executing: ".$command.PHP_EOL;
  1271. system($command);
  1272. }