GelApplicationSubmit.php 39.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<?php

namespace Drupal\gel\Controller;

use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Controller\ControllerBase;

use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;

use Drupal\gel\Crypt;

18
//use Drupal\epal\ClientConsumer;
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

class GelApplicationSubmit extends ControllerBase
{
    const ERROR_DB = -1;
    const FULL_CLASS = -2;
    const NON_FULL_CLASS = -3;

    const UNIT_TYPE_NIP = 1;
    const UNIT_TYPE_DIM = 2;
    const UNIT_TYPE_GYM = 3;
    const UNIT_TYPE_LYK = 4;
    const UNIT_TYPE_EPAL = 5;

    const CERT_GYM = 'Απολυτήριο Γυμνασίου';
    const CERT_LYK = 'Απολυτήριο Λυκείου';

    const VALID_NAMES_PATTERN = '/^[A-Za-zΑ-ΩΆΈΉΊΙΎΌΏα-ωάέήίΐύόώ \-]*$/mu';
36
    const VALID_UCASE_NAMES_PATTERN = '/^[A-ZΑ-Ω]{2,}[A-ZΑ-Ω \-]*$/mu';
37 38 39 40 41 42
    const VALID_ADDRESS_PATTERN = '/^[0-9A-Za-zΑ-ΩΆΈΉΊΎΌΏα-ωάέήίύόώ\/\. \-]*$/mu';
    const VALID_ADDRESSTK_PATTERN = '/^[0-9]{5}$/';
    const VALID_DIGITS_PATTERN = '/^[0-9]*$/';
    const VALID_TELEPHONE_PATTERN = '/^2[0-9]{9}$/';
    const VALID_YEAR_PATTERN = '/^(19[6789][0-9]|20[0-1][0-9])$/';
    const VALID_CAPACITY_PATTERN = '/[0-9]*$/';
43
    const LIMIT_SCHOOL_YEAR = '2013-2014';
44 45 46 47 48 49 50 51 52 53 54 55 56

    protected $entityTypeManager;
    protected $logger;
    protected $connection;
    protected $client; // client consumer

    public function __construct(
        EntityTypeManagerInterface $entityTypeManager,
        Connection $connection,
        LoggerChannelFactoryInterface $loggerChannel
    ) {
        $this->entityTypeManager = $entityTypeManager;
        $this->connection = $connection;
57
        $this->logger = $loggerChannel->get('gel');
58

59
        /*
60 61 62 63 64 65
        $config = $this->config('epal.settings');
        $settings = [];
        foreach (['ws_endpoint', 'ws_username', 'ws_password', 'verbose', 'NO_SAFE_CURL'] as $setting) {
            $settings[$setting] = $config->get($setting);
        }
        $this->client = new ClientConsumer($settings, $entityTypeManager, $loggerChannel);
66
        */
67

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    }

    public static function create(ContainerInterface $container)
    {
        return new static(
            $container->get('entity_type.manager'),
            $container->get('database'),
            $container->get('logger.factory')
        );
    }

    public function appSubmit(Request $request)
    {
        if (!$request->isMethod('POST')) {
            return $this->respondWithStatus([
                "error_code" => 2001
            ], Response::HTTP_METHOD_NOT_ALLOWED);
        }
        $applicationForm = array();

        $content = $request->getContent();
        if (!empty($content)) {
            $applicationForm = json_decode($content, true);
        } else {
            return $this->respondWithStatus([
                "error_code" => 5002
            ], Response::HTTP_BAD_REQUEST);
        }

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        //user role validation
        $authToken = $request->headers->get('PHP_AUTH_USER');
        $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
        $user = reset($users);
        if (!$user) {
           return $this->respondWithStatus([
                   'message' => t("User not found"),
               ], Response::HTTP_FORBIDDEN);
        }

 			  $roles = $user->getRoles();
 			  $validRole = false;
 			  foreach ($roles as $role)
 				 if ($role === "applicant") {
 					 $validRole = true;
 					 break;
 				 }
 			  if (!$validRole) {
 					 return $this->respondWithStatus([
 									 'message' => t("User Invalid Role"),
 							 ], Response::HTTP_FORBIDDEN);
 			  }

120
        // configuration validation
121
        $eggrafesConfigs = $this->entityTypeManager->getStorage('eggrafes_config')->loadByProperties(array('name' => 'eggrafes_config_gel'));
122 123
        $eggrafesConfig = reset($eggrafesConfigs);
        if (!$eggrafesConfig) {
124 125 126 127
            return $this->respondWithStatus([
                "error_code" => 3001
            ], Response::HTTP_FORBIDDEN);
        }
128
        if ($eggrafesConfig->lock_application->value) {
129 130 131 132 133 134 135 136 137 138 139 140
            return $this->respondWithStatus([
                "error_code" => 3002
            ], Response::HTTP_FORBIDDEN);
        }

        $crypt = new Crypt();
        try {
            $name_encoded = $crypt->encrypt($applicationForm[0]['name']);
            $studentsurname_encoded = $crypt->encrypt($applicationForm[0]['studentsurname']);
            $fatherfirstname_encoded = $crypt->encrypt($applicationForm[0]['fatherfirstname']);
            $motherfirstname_encoded = $crypt->encrypt($applicationForm[0]['motherfirstname']);
            $regionaddress_encoded = $crypt->encrypt($applicationForm[0]['regionaddress']);
141 142
            //$regiontk_encoded = $crypt->encrypt($applicationForm[0]['regiontk']);
            //$regionarea_encoded = $crypt->encrypt($applicationForm[0]['regionarea']);
143 144 145 146 147
            $telnum_encoded = $crypt->encrypt($applicationForm[0]['telnum']);
            $guardian_name_encoded = $crypt->encrypt($applicationForm[0]['cu_name']);
            $guardian_surname_encoded = $crypt->encrypt($applicationForm[0]['cu_surname']);
            $guardian_fathername_encoded = $crypt->encrypt($applicationForm[0]['cu_fathername']);
            $guardian_mothername_encoded = $crypt->encrypt($applicationForm[0]['cu_mothername']);
148 149 150 151 152 153 154 155
            if ($applicationForm[0]['regiontk'] != null)
              $regiontk_encoded = $crypt->encrypt($applicationForm[0]['regiontk']);
            else
              $regiontk_encoded = $applicationForm[0]['regiontk'];
            if ($applicationForm[0]['regionarea'] != null)
              $regionarea_encoded = $crypt->encrypt($applicationForm[0]['regionarea']);
            else
              $regionarea_encoded = $applicationForm[0]['regionarea'];
156 157 158 159
            $am_encoded = "";
            if ( $applicationForm[0]['lastschool_schoolyear'] >= self::LIMIT_SCHOOL_YEAR)
                $am_encoded = $crypt->encrypt($applicationForm[0]['am']);

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
            return $this->respondWithStatus([
                "error_code" => 5001
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        unset($crypt);

        $transaction = $this->connection->startTransaction();
        try {
            //insert records in entity: gel_student
            $authToken = $request->headers->get('PHP_AUTH_USER');
            $applicantUsers = $this->entityTypeManager->getStorage('applicant_users')->loadByProperties(array('authtoken' => $authToken));
            $applicantUser = reset($applicantUsers);
            if (!$applicantUser) {
                return $this->respondWithStatus([
                    "error_code" => 4003
                ], Response::HTTP_FORBIDDEN);
            }

180
            $second_period = $eggrafesConfig->activate_second_period->value;
181 182 183 184 185

            $student = array(
                'langcode' => 'el',
                'user_id' => $applicantUser->user_id->target_id,
                'gel_userid' => $applicantUser->id(),
186 187
                'am' => $am_encoded,
                'myschool_id' => $applicationForm[0]['studentId'],
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
                'name' => $name_encoded,
                'studentsurname' => $studentsurname_encoded,
                'birthdate' => $applicationForm[0]['studentbirthdate'],
                'fatherfirstname' => $fatherfirstname_encoded,
                'motherfirstname' => $motherfirstname_encoded,
                'regionaddress' => $regionaddress_encoded,
                'regionarea' => $regionarea_encoded,
                'regiontk' => $regiontk_encoded,
                'lastschool_registrynumber' => $applicationForm[0]['lastschool_registrynumber'],
                'lastschool_unittypeid' => $applicationForm[0]['lastschool_unittypeid'],
                'lastschool_schoolname' => $applicationForm[0]['lastschool_schoolname'],
                'lastschool_schoolyear' => $applicationForm[0]['lastschool_schoolyear'],
                'lastschool_class' => $applicationForm[0]['lastschool_class'],
                'nextclass' => $applicationForm[0]['nextclass'],
                'guardian_name' => $guardian_name_encoded,
                'guardian_surname' => $guardian_surname_encoded,
                'guardian_fathername' => $guardian_fathername_encoded,
                'guardian_mothername' => $guardian_mothername_encoded,
                'agreement' => $applicationForm[0]['disclaimer_checked'],
                'hasright' => $applicationForm[0]['hasright'],
208
                'relationtostudent' => $applicationForm[0]['relationtostudent'],
209 210
                'telnum' => $telnum_encoded,
                'second_period' => $second_period,
211
                'myschool_currentsection' => $applicationForm[0]['section_name'],
212 213
                'myschool_currentlevelname' => $applicationForm[0]['level_name'],
                'myschool_currentunittype' => $applicationForm[0]['unittype_name'],
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
            );

            if (($errorCode = $this->validateStudent(array_merge(
                    $student, [
                        'name' => $applicationForm[0]['name'],
                        'studentsurname' => $applicationForm[0]['studentsurname'],
                        'fatherfirstname' => $applicationForm[0]['fatherfirstname'],
                        'motherfirstname' => $applicationForm[0]['motherfirstname'],
                        'regionaddress' => $applicationForm[0]['regionaddress'],
                        'regiontk' => $applicationForm[0]['regiontk'],
                        'regionarea' => $applicationForm[0]['regionarea'],
                        'relationtostudent' => $applicationForm[0]['relationtostudent'],
                        'telnum' => $applicationForm[0]['telnum'],
                        'guardian_name' => $applicationForm[0]['cu_name'],
                        'guardian_surname' => $applicationForm[0]['cu_surname'],
                        'guardian_fathername' => $applicationForm[0]['cu_fathername'],
                        'guardian_mothername' => $applicationForm[0]['cu_mothername']
                    ]),
232 233
                    $applicationForm[0]['nextclass'],
                    $applicationForm[1]['choice_id'],
234
                    $applicationForm[3][0]['choice_id'],
235
                    $applicationForm[2][0]['choice_id'],
236
                    $applicantUser, $eggrafesConfig->ws_ident->value, false)) > 0) {
237 238 239 240 241
                return $this->respondWithStatus([
                    "error_code" => $errorCode
                ], Response::HTTP_OK);
            }

242 243
            //καταχώρηση id σχολείου τελευταίας φοίτησης (ή 0 σε περίπτωση που δεν υπάρχει)
            //λειτουργεί για ΕΠΑΛ. Κάτι ανάλογο στα ΓΕΛ;
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
            /*
            $lastSchoolRegistryNumber = $student['lastschool_registrynumber'];
            $lastSchoolYear = (int)(substr($student['lastschool_schoolyear'], -4));
            if ((int)date("Y") === $lastSchoolYear && (int)$student['lastschool_unittypeid'] === 5) {
                $epalSchools = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('registry_no' => $lastSchoolRegistryNumber));
                $epalSchool = reset($epalSchools);
                if ($epalSchool) {
                    $student['currentepal'] = $epalSchool->id();
                } else {
                    $student['currentepal'] = 0;
                }
            } else {
                $student['currentepal'] = 0;
            }
            */

            $entity_storage_student = $this->entityTypeManager->getStorage('gel_student');
            $entity_object = $entity_storage_student->create($student);
            $entity_storage_student->save($entity_object);

            $created_student_id = $entity_object->id();
            //ομάδα προσανατολισμού
            $classIds = array("2", "3", "6", "7");
            if (in_array($applicationForm[0]['nextclass'], $classIds))  {
              //if ($applicationForm[0]['nextclass'] === "..."
              $studentchoice = array(
                  'student_id' => $created_student_id,
                  'choice_id' => $applicationForm[1]['choice_id'],
              );
              $entity_storage_studentchoices = $this->entityTypeManager->getStorage('gel_student_choices');
              $entity_object = $entity_storage_studentchoices->create($studentchoice);
              $entity_storage_studentchoices->save($entity_object);
          }

            //μαθήματα επιλογής
            $classIds = array("1", "3", "4");
            if (in_array($applicationForm[0]['nextclass'], $classIds))  {
              //$this->logger->warning("Message1");
              for ($i = 0; $i < sizeof($applicationForm[2]); $i++) {
                  $coursechosen = array(
                      'student_id' => $created_student_id,
                      'choice_id' => $applicationForm[2][$i]['choice_id'],
                      'order_id' => $applicationForm[2][$i]['order_id']
                  );
                  $entity_storage_coursechosen = $this->entityTypeManager->getStorage('gel_student_choices');
                  $entity_object = $entity_storage_coursechosen->create($coursechosen);
                  $entity_storage_coursechosen->save($entity_object);
              }
            }
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

            //μαθήματα ξένων γλωσσών
            $classIds = array("1","4");
            if (in_array($applicationForm[0]['nextclass'], $classIds))  {
              for ($i = 0; $i < sizeof($applicationForm[3]); $i++) {
                  $coursechosen = array(
                      'student_id' => $created_student_id,
                      'choice_id' => $applicationForm[3][$i]['choice_id'],
                      'order_id' => $applicationForm[3][$i]['order_id']
                  );
                  $entity_storage_langchosen = $this->entityTypeManager->getStorage('gel_student_choices');
                  $entity_object = $entity_storage_langchosen->create($coursechosen);
                  $entity_storage_langchosen->save($entity_object);
              }
            }

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
            return $this->respondWithStatus([
                "error_code" => 0
            ], Response::HTTP_OK);
        } catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
            $transaction->rollback();

            return $this->respondWithStatus([
                "error_code" => 5001
            ], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }



324 325

    public function appUpdate(Request $request, $studentId)
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    {
      if (!$request->isMethod('POST')) {
          return $this->respondWithStatus([
              "error_code" => 2001
          ], Response::HTTP_METHOD_NOT_ALLOWED);
      }
      $applicationForm = array();

      $content = $request->getContent();
      if (!empty($content)) {
          $applicationForm = json_decode($content, true);
      } else {
          return $this->respondWithStatus([
              "error_code" => 5002
          ], Response::HTTP_BAD_REQUEST);
      }

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
      //user role validation
      $authToken = $request->headers->get('PHP_AUTH_USER');
      $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
      $user = reset($users);
      if (!$user) {
         return $this->respondWithStatus([
                 'message' => t("User not found"),
             ], Response::HTTP_FORBIDDEN);
      }

      $roles = $user->getRoles();
      $validRole = false;
      foreach ($roles as $role)
       if ($role === "applicant") {
         $validRole = true;
         break;
       }
      if (!$validRole) {
         return $this->respondWithStatus([
                 'message' => t("User Invalid Role"),
             ], Response::HTTP_FORBIDDEN);
      }

366
      //configuration validation
367
      $eggrafesConfigs = $this->entityTypeManager->getStorage('eggrafes_config')->loadByProperties(array('name' => 'eggrafes_config_gel'));
368 369
      $eggrafesConfig = reset($eggrafesConfigs);
      if (!$eggrafesConfig) {
370 371 372 373
          return $this->respondWithStatus([
              "error_code" => 3001
          ], Response::HTTP_FORBIDDEN);
      }
374
      if ($eggrafesConfig->lock_application->value) {
375 376 377 378 379 380 381 382 383 384 385 386
          return $this->respondWithStatus([
              "error_code" => 3002
          ], Response::HTTP_FORBIDDEN);
      }

      $crypt = new Crypt();
      try {
          $name_encoded = $crypt->encrypt($applicationForm[0]['name']);
          $studentsurname_encoded = $crypt->encrypt($applicationForm[0]['studentsurname']);
          $fatherfirstname_encoded = $crypt->encrypt($applicationForm[0]['fatherfirstname']);
          $motherfirstname_encoded = $crypt->encrypt($applicationForm[0]['motherfirstname']);
          $regionaddress_encoded = $crypt->encrypt($applicationForm[0]['regionaddress']);
387 388
          //$regiontk_encoded = $crypt->encrypt($applicationForm[0]['regiontk']);
          //$regionarea_encoded = $crypt->encrypt($applicationForm[0]['regionarea']);
389 390 391 392 393
          $telnum_encoded = $crypt->encrypt($applicationForm[0]['telnum']);
          $guardian_name_encoded = $crypt->encrypt($applicationForm[0]['cu_name']);
          $guardian_surname_encoded = $crypt->encrypt($applicationForm[0]['cu_surname']);
          $guardian_fathername_encoded = $crypt->encrypt($applicationForm[0]['cu_fathername']);
          $guardian_mothername_encoded = $crypt->encrypt($applicationForm[0]['cu_mothername']);
394 395 396 397 398 399 400 401
          if ($applicationForm[0]['regiontk'] != null)
            $regiontk_encoded = $crypt->encrypt($applicationForm[0]['regiontk']);
          else
            $regiontk_encoded = $applicationForm[0]['regiontk'];
          if ($applicationForm[0]['regionarea'] != null)
            $regionarea_encoded = $crypt->encrypt($applicationForm[0]['regionarea']);
          else
            $regionarea_encoded = $applicationForm[0]['regionarea'];
402 403 404 405
          $am_encoded = "";
          if ( $applicationForm[0]['lastschool_schoolyear'] >= self::LIMIT_SCHOOL_YEAR)
              $am_encoded = $crypt->encrypt($applicationForm[0]['am']);

406 407 408 409 410 411 412 413 414 415
      } catch (\Exception $e) {
          $this->logger->error($e->getMessage());
          return $this->respondWithStatus([
              "error_code" => 5001
          ], Response::HTTP_INTERNAL_SERVER_ERROR);
      }
      unset($crypt);

      $transaction = $this->connection->startTransaction();
      try {
416
          //insert records in entity: gel_student
417
          $authToken = $request->headers->get('PHP_AUTH_USER');
418 419 420
          $applicantUsers = $this->entityTypeManager->getStorage('applicant_users')->loadByProperties(array('authtoken' => $authToken));
          $applicantUser = reset($applicantUsers);
          if (!$applicantUser) {
421 422 423 424 425
              return $this->respondWithStatus([
                  "error_code" => 4003
              ], Response::HTTP_FORBIDDEN);
          }

426
          $second_period = $eggrafesConfig->activate_second_period->value;
427

428 429
          $student = array(
              'langcode' => 'el',
430 431
              'user_id' => $applicantUser->user_id->target_id,
              'gel_userid' => $applicantUser->id(),
432 433
              'am' => $am_encoded,
              'myschool_id' => $applicationForm[0]['studentId'],
434 435 436 437 438 439 440 441 442 443 444 445 446
              'name' => $name_encoded,
              'studentsurname' => $studentsurname_encoded,
              'birthdate' => $applicationForm[0]['studentbirthdate'],
              'fatherfirstname' => $fatherfirstname_encoded,
              'motherfirstname' => $motherfirstname_encoded,
              'regionaddress' => $regionaddress_encoded,
              'regionarea' => $regionarea_encoded,
              'regiontk' => $regiontk_encoded,
              'lastschool_registrynumber' => $applicationForm[0]['lastschool_registrynumber'],
              'lastschool_unittypeid' => $applicationForm[0]['lastschool_unittypeid'],
              'lastschool_schoolname' => $applicationForm[0]['lastschool_schoolname'],
              'lastschool_schoolyear' => $applicationForm[0]['lastschool_schoolyear'],
              'lastschool_class' => $applicationForm[0]['lastschool_class'],
447
              'nextclass' => $applicationForm[0]['nextclass'],
448 449 450 451 452
              'guardian_name' => $guardian_name_encoded,
              'guardian_surname' => $guardian_surname_encoded,
              'guardian_fathername' => $guardian_fathername_encoded,
              'guardian_mothername' => $guardian_mothername_encoded,
              'agreement' => $applicationForm[0]['disclaimer_checked'],
453
              'hasright' => $applicationForm[0]['hasright'],
454
              'relationtostudent' => $applicationForm[0]['relationtostudent'],
455
              'telnum' => $telnum_encoded,
456
              'second_period' => $second_period,
457
              'myschool_currentsection' => $applicationForm[0]['section_name'],
458 459
              'myschool_currentlevelname' => $applicationForm[0]['level_name'],
              'myschool_currentunittype' => $applicationForm[0]['unittype_name'],
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
          );

          if (($errorCode = $this->validateStudent(array_merge(
                  $student, [
                      'name' => $applicationForm[0]['name'],
                      'studentsurname' => $applicationForm[0]['studentsurname'],
                      'fatherfirstname' => $applicationForm[0]['fatherfirstname'],
                      'motherfirstname' => $applicationForm[0]['motherfirstname'],
                      'regionaddress' => $applicationForm[0]['regionaddress'],
                      'regiontk' => $applicationForm[0]['regiontk'],
                      'regionarea' => $applicationForm[0]['regionarea'],
                      'relationtostudent' => $applicationForm[0]['relationtostudent'],
                      'telnum' => $applicationForm[0]['telnum'],
                      'guardian_name' => $applicationForm[0]['cu_name'],
                      'guardian_surname' => $applicationForm[0]['cu_surname'],
                      'guardian_fathername' => $applicationForm[0]['cu_fathername'],
                      'guardian_mothername' => $applicationForm[0]['cu_mothername']
477 478 479
                  ]),
                  $applicationForm[0]['nextclass'],
                  $applicationForm[1]['choice_id'],
480
                  $applicationForm[3][0]['choice_id'],
481
                  $applicationForm[2][0]['choice_id'],
482
                  $applicantUser, $eggrafesConfig->ws_ident->value, true)) > 0) {
483 484 485 486 487
              return $this->respondWithStatus([
                  "error_code" => $errorCode
              ], Response::HTTP_OK);
          }

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
          //ενημέρωση (update) του gel_student
          $entity_storage_student = $this->entityTypeManager->getStorage('gel_student');
          $gelStudents = $entity_storage_student->loadByProperties(array('id' => $studentId));
          $gelStudent = reset($gelStudents);
          if (!$gelStudent) {
             return $this->respondWithStatus([
                     'message' => t("GelStudent Enity not found"),
                 ], Response::HTTP_FORBIDDEN);
          }
          else  {
            $gelStudent->set('name', $name_encoded);
            $gelStudent->set('studentsurname', $studentsurname_encoded);
            $gelStudent->set('birthdate', $applicationForm[0]['studentbirthdate']);
            $gelStudent->set('fatherfirstname', $fatherfirstname_encoded);
            $gelStudent->set('motherfirstname', $motherfirstname_encoded);
            $gelStudent->set('regionaddress', $regionaddress_encoded);
            $gelStudent->set('regionarea', $regionarea_encoded);
            $gelStudent->set('regiontk', $regiontk_encoded);
            $gelStudent->set('lastschool_registrynumber', $applicationForm[0]['lastschool_registrynumber']);
            $gelStudent->set('lastschool_unittypeid', $applicationForm[0]['lastschool_unittypeid']);
            $gelStudent->set('lastschool_schoolname', $applicationForm[0]['lastschool_schoolname']);
            $gelStudent->set('lastschool_schoolyear', $applicationForm[0]['lastschool_schoolyear']);
            $gelStudent->set('lastschool_class', $applicationForm[0]['lastschool_class']);
            $gelStudent->set('lastschool_schoolyear', $applicationForm[0]['lastschool_schoolyear']);
            $gelStudent->set('nextclass', $applicationForm[0]['nextclass']);
            $gelStudent->set('guardian_name', $guardian_name_encoded);
            $gelStudent->set('guardian_surname', $guardian_surname_encoded);
            $gelStudent->set('guardian_fathername', $guardian_fathername_encoded);
            $gelStudent->set('guardian_mothername', $guardian_mothername_encoded);
517
            $gelStudent->set('relationtostudent', $applicationForm[0]['relationtostudent']);
518 519
            $gelStudent->set('telnum', $telnum_encoded);

520 521 522
            $gelStudent->set('am', $am_encoded);
            $gelStudent->set('myschool_id', $applicationForm[0]['studentId']);
            $gelStudent->set('myschool_currentsection', $applicationForm[0]['section_name']);
523 524
            $gelStudent->set('myschool_currentlevelname', $applicationForm[0]['level_name']);
            $gelStudent->set('myschool_currentunittype', $applicationForm[0]['unittype_name']);
525

526 527
            $gelStudent->set('second_period', $second_period);

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            $gelStudent->save();
          }
          $entity_storage_student->resetCache();

          //διαγραφή αντίστοιχων εγγραφών από gel_student_choices
          $entity_storage_gel_student_choices = $this->entityTypeManager->getStorage('gel_student_choices');
          $ids  = $entity_storage_gel_student_choices->getQuery()
            ->condition('student_id', $studentId, '=')
            ->execute();
          $choices = $entity_storage_gel_student_choices->loadMultiple($ids);
          $entity_storage_gel_student_choices->delete($choices);
          $entity_storage_gel_student_choices->resetCache();

          //εισαγωγή νέων εγγραφών στo gel_student_choices (ομάδα προσανατολισμού)
          $classIds = array("2", "3", "6", "7");
          if (in_array($applicationForm[0]['nextclass'], $classIds))  {
              $orientationchosen = array(
                  'student_id' => $studentId,
                  'choice_id' => $applicationForm[1]['choice_id']
                );
              $entity_storage_studentorientation = $this->entityTypeManager->getStorage('gel_student_choices');
              $entity_object = $entity_storage_studentorientation->create($orientationchosen);
              $entity_storage_studentorientation->save($entity_object);
551 552
          }

553 554 555 556 557 558 559 560 561 562 563 564 565 566
          //εισαγωγή νέων εγγραφών στo gel_student_choices (μαθήματα επιλογής)
          $classIds = array("1", "3", "4");
          if (in_array($applicationForm[0]['nextclass'], $classIds))  {
              for ($i = 0; $i < sizeof($applicationForm[2]); $i++) {
                  $coursechosen = array(
                      'student_id' => $studentId,
                      'choice_id' => $applicationForm[2][$i]['choice_id'],
                      'order_id' => $applicationForm[2][$i]['order_id']
                  );
                  $entity_storage_studentchoices = $this->entityTypeManager->getStorage('gel_student_choices');
                  $entity_object = $entity_storage_studentchoices->create($coursechosen);
                  $entity_storage_studentchoices->save($entity_object);
              }
          }
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
          //εισαγωγή νέων εγγραφών στo gel_student_choices (μαθήματα ξένων γλωσσών)
          $classIds = array("1","4");
          if (in_array($applicationForm[0]['nextclass'], $classIds))  {
            for ($i = 0; $i < sizeof($applicationForm[3]); $i++) {
                $coursechosen = array(
                    'student_id' => $studentId,
                    'choice_id' => $applicationForm[3][$i]['choice_id'],
                    'order_id' => $applicationForm[3][$i]['order_id']
                );
                $entity_storage_langchosen = $this->entityTypeManager->getStorage('gel_student_choices');
                $entity_object = $entity_storage_langchosen->create($coursechosen);
                $entity_storage_langchosen->save($entity_object);
            }
          }

583 584 585 586

          return $this->respondWithStatus([
              "error_code" => 0
          ], Response::HTTP_OK);
587

588 589 590 591 592 593 594 595 596 597 598
      } catch (\Exception $e) {
          $this->logger->warning($e->getMessage());
          $transaction->rollback();

          return $this->respondWithStatus([
              "error_code" => 5001
          ], Response::HTTP_INTERNAL_SERVER_ERROR);
      }


    }
599

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624




    private function respondWithStatus($arr, $s)
    {
        $res = new JsonResponse($arr);
        $res->setStatusCode($s);
        return $res;
    }

    /**
     *
     * @return int error code ελέγχου; 0 εάν ο έλεγχος επιτύχει, μη μηδενικό εάν αποτύχει:
     *  1001 δεν επιλέχθηκε το πλαίσιο συμφωνης γνώμης
     *  1002 λανθασμένο τελευταίο έτος φοίτησης
     *  1003 λανθασμένη ημερομηνία
     *  1004-> 1023: λανθασμένα πεδία αίτησης
     *  8000 μη αναμενόμενο λάθος
     *  8001 δικτυακό λάθος κλήσης υπηρεσίας επιβεβαίωσης στοιχείων
     *  8002 τα στοιχεία φοίτησης δεν επικυρώθηκαν
     *  8003 τα στοιχεία φοίτησης δεν είναι έγκυρα
     */


625

626
    private function validateStudent($student, $chosenClass, $chosenOrientation, $chosenLangCourse, $chosenElectiveCourse, $applicantUser = null, $wsEnabled, $appUpdate)
627 628 629 630
    {
        if (!$student["hasright"] && $appUpdate == false) {
            return 997;
        }
631 632 633 634 635 636
        if (($chosenClass === "2" || $chosenClass === "3" || $chosenClass === "6" || $chosenClass === "7") && !isset($chosenOrientation)) {
            return 998;
        }
        if ( ($chosenClass === "1" || $chosenClass === "3" || $chosenClass === "4") && !isset($chosenElectiveCourse)) {
            return 999;
        }
637 638 639
        if ( ($chosenClass === "1" || $chosenClass === "4") && !isset($chosenLangCourse)) {
            return 1000;
        }
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
        if (!$student["agreement"] && $appUpdate == false) {
            return 1001;
        }
        if (!$student["lastschool_schoolyear"] || strlen($student["lastschool_schoolyear"]) !== 9) {
            return 1002;
        }
        // date in YYY-MM-DD, out d-m-Y
        $date_parts = explode('-', $student['birthdate'], 3);
        if ((count($date_parts) !== 3) ||
            (checkdate($date_parts[1], $date_parts[2], $date_parts[0]) !== true)) {
            return 1003;
        }
        if (intval($date_parts[0]) >= ((int)date("Y") - 13)) {
            return 1003;
        }
        $birthdate = "{$date_parts[2]}-{$date_parts[1]}-{$date_parts[0]}";

        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["name"]) !== 1) {
            return 1004;
        }
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["studentsurname"]) !== 1) {
            return 1005;
        }
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["fatherfirstname"]) !== 1) {
            return 1006;
        }
        if (preg_match(self::VALID_UCASE_NAMES_PATTERN, $student["motherfirstname"]) !== 1) {
            return 1007;
        }
669 670
        if (( ($wsEnabled === 1 && $student["lastschool_schoolyear"] < self::LIMIT_SCHOOL_YEAR) || ($wsEnabled === 0) )
          && preg_match(self::VALID_ADDRESS_PATTERN, $student["regionaddress"]) !== 1) {
671 672
            return 1008;
        }
673
        /*
674 675
        if (  ( ($wsEnabled === 1 && $student["lastschool_schoolyear"] < self::LIMIT_SCHOOL_YEAR) || ($wsEnabled === 0) )
          && preg_match(self::VALID_ADDRESSTK_PATTERN, $student["regiontk"]) !== 1) {
676 677
            return 1009;
        }
678
        */
679 680 681 682
        if (  ( ($wsEnabled === 1 && $student["lastschool_schoolyear"] < self::LIMIT_SCHOOL_YEAR) || ($wsEnabled === 0) )
          && preg_match(self::VALID_NAMES_PATTERN, $student["regionarea"]) !== 1) {
            return 1010;
        }
683 684 685
        //if (preg_match(self::VALID_ADDRESSTK_PATTERN, $student["regionarea"]) !== 1) {
        //    return 1010;
        //}
686 687 688

        $classIds = array("1", "2", "3", "4", "5", "6", "7");
        if (!in_array($student["nextclass"], $classIds))  {
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
            return 1013;
        }
        if (!$student["relationtostudent"]) {
            return 1014;
        }
        if (preg_match(self::VALID_TELEPHONE_PATTERN, $student["telnum"]) !== 1) {
            return 1015;
        }
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_name"]) !== 1) {
            return 1016;
        }
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_surname"]) !== 1) {
            return 1017;
        }
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_fathername"]) !== 1) {
            return 1018;
        }
        if (preg_match(self::VALID_NAMES_PATTERN, $student["guardian_mothername"]) !== 1) {
            return 1019;
        }
        if (!$student["lastschool_registrynumber"]) {
            return 1020;
        }
        if (!$student["lastschool_unittypeid"]) {
            return 1021;
        }
        if (!$student["lastschool_schoolname"]) {
            return 1022;
        }
718 719 720 721 722 723 724
        /*
        if (( ($wsEnabled === 1 && $student["lastschool_schoolyear"] < self::LIMIT_SCHOOL_YEAR) || ($wsEnabled === 0) )
          && $student["am"] && !$student["lastschool_class"]) {
            return 1023;
        }
        */
        if (!$student["lastschool_class"] || $student["lastschool_class"] == -1) {
725 726
            return 1023;
        }
727 728 729
        if ($student["myschool_id"] && $student["lastschool_schoolyear"] < self::LIMIT_SCHOOL_YEAR) {
            return 1024;
        }
730
        if ($wsEnabled === 1 &&  !$student["myschool_id"] && $student["lastschool_schoolyear"] >= self::LIMIT_SCHOOL_YEAR) {
731 732
            return 1025;
        }
733

734
        //validate class mobility in GEL schools
735 736 737

        //$this->logger->error($student["lastschool_class"]);
        $isNight = $this->isNightSchool($student["lastschool_registrynumber"]);
738
        //από ΓΕΛ
739
        /*
740 741
        if ( $student["lastschool_unittypeid"] == "4"  )  {
            if ($isNight &&  $student["lastschool_class"] == "1" && $student["nextclass"] != 1 && $student["nextclass"] != 5) {
742
              //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 1 Ή 8");
743 744 745
              return 1026;
            }
            if (!$isNight &&  $student["lastschool_class"] == "1" && $student["nextclass"] != 2 && $student["nextclass"] != 6)  {
746
              //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 3 Ή 10");
747 748 749
              return 1026;
            }
            if ($isNight &&  $student["lastschool_class"] == "2" && $student["nextclass"] != 2 && $student["nextclass"] != 6)  {
750
              //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 4 Ή 9");
751 752 753
              return 1026;
            }
            if (!$isNight &&  $student["lastschool_class"] == "2" && $student["nextclass"] != 3 && $student["nextclass"] != 7)  {
754
              //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 5 Ή 12");
755 756 757
              return 1026;
            }
            if ($isNight &&  $student["lastschool_class"] == "3" && $student["nextclass"] != 3 && $student["nextclass"] != 7)  {
758
              //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 6 Ή 11");
759 760 761
              return 1026;
            }
            if (!$isNight &&  $student["lastschool_class"] == "3" )  {
762
              //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 13");
763 764 765
              return 1026;
            }
        }
766
        */
767

768
        //από Γυμνάσιο
769 770
        //Προσοχή! Δεν αντιμετωπίζουμε τα Γυμνάσια με Λυκειακες Τάξεις
        //if ($student["lastschool_unittypeid"] == "3"   && $student["nextclass"] != 1 && $student["nextclass"] != 4)  {
771
          //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 2 Ή 7");
772 773
        //  return 1026;
        //}
774

775
        //από ΕΠΑΛ
776 777 778
        //if ($student["lastschool_unittypeid"] == "5"   && $student["nextclass"] != 2 && $student["nextclass"] != 6
        //  &&  (!isNight )  )
        // {
779
          //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 14 Ή 15");
780 781 782 783 784 785 786 787 788
        //  return 1026;
        //}

        //if ($student["lastschool_unittypeid"] == "5"   && $student["nextclass"] != 2 && $student["nextclass"] != 6
        //  &&  $student["nextclass"] != 4  )
        // {
          //$this->logger->error("ΠΕΡΙΠΤΩΣΗ 14 Ή 15");
        //  return 1026;
        //}
789

790
        // check if application exists in eithe gel_student or epal_student entity
791
        if (/*$student['second_period'] == 1 &&*/ $applicantUser !== null && $appUpdate == false) {
792
            $retCode = $this->existApp("gel_student", "gel_userid", $applicantUser, $student);
793
            if ($retCode === -1) {
794
              $retCode = $this->existApp("epal_student", "epaluser_id", $applicantUser, $student);
795 796 797
            }
            if ($retCode !== -1)
              return $retCode;
798 799
        }

800
        return 0;
801 802
    }

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
    private function isNightSchool($school_regisrty_no)  {
      try {
          $schoolCon = $this->connection->select('gel_school', 'schoolType')
              ->fields('schoolType', array('operation_shift'))
              ->condition('schoolType.registry_no', $school_regisrty_no, '=');
          $results = $schoolCon->execute()->fetchAll(\PDO::FETCH_OBJ);
      } catch (\Exception $e) {
          $this->logger->error($e->getMessage());
          return self::ERROR_DB;
      }

      if (sizeof($results) > 0)  {
        $row = reset($results);
        if ($row->operation_shift === 'ΕΣΠΕΡΙΝΟ')
          return 1;
      }
      return 0;
    }

822

823
    private function existApp($entityName, $userIdField, $applicantUser, $student) {
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
        if (!$student["myschool_id"]) {
            $esQuery = $this->connection->select($entityName, 'es')
                                    ->fields('es',
                                    array('name',
                                            'studentsurname',
                                            'birthdate',
                                        ));
            $esQuery->condition('es.' . $userIdField, $applicantUser->id(), '=');
            $esQuery->condition('es.delapp' , 0, '=');
            $existing = $esQuery->execute()->fetchAll(\PDO::FETCH_OBJ);
            if ($existing && sizeof($existing) > 0) {
                $crypt = new Crypt();
                foreach ($existing as $candidate) {
                    if (($crypt->decrypt($candidate->name) == $student['name'])
                        && ($crypt->decrypt($candidate->studentsurname) == $student['studentsurname'])
                        && ($candidate->birthdate == $student['birthdate'])
                        ) {
                        return 8004;
                    }
                }
            }
            return -1;
846
      }
847

848 849 850 851 852 853 854 855 856 857
      else {
          $esQuery = $this->connection->select($entityName, 'es')
                                      ->fields('es',array('myschool_id'));
          $esQuery->condition('es.myschool_id', $student["myschool_id"], '=');
          $esQuery->condition('es.delapp' , 0, '=');
          $existing = $esQuery->execute()->fetchAll(\PDO::FETCH_OBJ);
          if ($existing && sizeof($existing) > 0)
            return 8004;
          return -1;
      }
858

859
    }
860 861

}