/**
  * login method
  *
  * @return void
  */
 public function login()
 {
     $user_id = $this->Session->read('user_id');
     $group_id = $this->Auth->user('group_id');
     if (!isset($this->data['User']['username'])) {
         $this->Auth->authenticate['Form'] = array('fields' => array('username' => 'email'));
     }
     if (!isset($user_id)) {
         //            if (empty($this->data)) {
         //                $cookie = $this->Cookie->read('Auth.User');
         //                if (!is_null($cookie)) {
         //                    if ($this->Auth->login($cookie)) {
         //                        $id_user = $this->Auth->user('id');
         //                        $this->Session->write('user_id', $id_user);
         //                        $username = $this->Auth->user('full_name');
         //                        $this->Session->write('username', $username);
         //                        $email = $this->Auth->user('email');
         //                        $this->Session->write('email', $email);
         //                        $group_id = $this->Auth->user('group_id');
         //                        $this->Session->write('group_id', $group_id);
         //                        $image = $this->Auth->user('image');
         //                        if (isset($image)) {
         //                            $extension = $this->Auth->user('image_extension');
         //                            $image = 'data:' . $extension . ';base64,' . base64_encode($this->Auth->user('image'));
         //                        }
         //                        $this->Session->write('image', $image);
         //
         //
         //                        if ($group_id == 1)
         //                            $this->redirect(array('controller' => 'Projects', 'action' => 'index'));
         //                        else
         //                            $this->redirect(array('controller' => 'usersRounds', 'action' => 'index'));
         //                    } else {// Delete invalid Cookie
         //                        $this->Cookie->destroy('Auth.User');
         //                        $this->Session->setFlash(__('Your username or pasword is incorrect'));
         //                        $this->redirect(array('controller' => 'Posts', 'action' => 'publicIndex'));
         //                    }
         //                }
         //
         //                $this->Session->setFlash(__('You are not authorized to access this location (user Login)'));
         //            }
         if ($this->request->is('post')) {
             if ($this->Auth->login()) {
                 $user_id = $this->Auth->user('id');
                 $this->Session->write('user_id', $user_id);
                 $username = $this->Auth->user('full_name');
                 $this->Session->write('username', $username);
                 $email = $this->Auth->user('email');
                 $this->Session->write('email', $email);
                 $group_id = $this->Auth->user('group_id');
                 $this->Session->write('group_id', $group_id);
                 $image = $this->Auth->user('image');
                 if (isset($image)) {
                     $extension = $this->Auth->user('image_type');
                     $image = 'data:' . $extension . ';base64,' . base64_encode($this->Auth->user('image'));
                 }
                 $this->Session->write('image', $image);
                 //                    if (!empty($this->data) && $this->data['User']['remember_me']) {
                 //                        $cookie = array();
                 //                        $cookie['username'] = $username;
                 //                        $cookie['password'] = $this->data['User']['password'];
                 //                        $cookie['user_id'] = $id_user;
                 //                        $cookie['group_id'] = $group_id;
                 //                        $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
                 //                        unset($this->data['User']['remember_me']);
                 //                    }
                 //ver si el usuario esta ya logueado
                 App::uses('CakeTime', 'Utility');
                 $date = $this->Auth->user('logged_until');
                 $isPast = CakeTime::isPast($date);
                 if (!$isPast) {
                     return $this->redirect(array('action' => 'logout', true));
                 }
                 $connectionLog = Configure::read('connectionLog');
                 if ($connectionLog) {
                     $ip = $this->request->clientIp();
                     //                        $ip = "4.4.4.4";
                     $connectionLogProxy = Configure::read('connectionLogProxy');
                     if ($connectionLogProxy && isset($this->request->data['User']['connection-details'])) {
                         $details = $this->request->data['User']['connection-details'];
                         $copyDetails = json_decode($details, true);
                         $ip = $copyDetails['ip'];
                     } else {
                         $details = @file_get_contents("http://ipinfo.io/{$ip}/json");
                     }
                     if ($details && $ip != '127.0.0.1') {
                         $details = json_decode($details, true);
                     } else {
                         $details = array();
                         $details['city'] = "unknown";
                         $details['country'] = "unknown";
                     }
                     $region = "";
                     if (isset($details['region'])) {
                         $region = $details['region'];
                     }
                     $data = array('user_id' => $user_id, 'ip' => $ip, 'city' => $details['city'] . " ({$region}) ", 'country' => $details['country'], 'session_time' => '00:00:00');
                     $this->User->Connection->create();
                     $this->User->Connection->save($data);
                     $this->Session->write('connection_id', $this->User->Connection->id);
                 }
                 if ($group_id == 1) {
                     $this->redirect(array('controller' => 'Projects', 'action' => 'index'));
                 } else {
                     $this->redirect(array('controller' => 'rounds', 'action' => 'index'));
                 }
             } else {
                 $this->Session->setFlash(__('The username or the password is incorrect.'));
             }
         }
         if (isset($this->request->data)) {
             $this->Session->write('loginIntent', $this->request->data);
             return $this->redirect(array('controller' => 'Posts', 'action' => 'publicIndex'));
         }
         $this->redirect(array('controller' => 'Posts', 'action' => 'publicIndex'));
     } else {
         $this->autoRender = false;
         $this->redirect(array('action' => 'logout'));
     }
 }
 public function start($round_id = null, $user_id = null, $operation = null)
 {
     $this->Round = $this->AnnotatedDocument->Round;
     $this->User = $this->Round->User;
     $this->UsersRound = $this->Round->UsersRound;
     $this->Project = $this->Round->Project;
     $this->Document = $this->Project->Document;
     $this->Type = $this->Round->Type;
     $this->Relation = $this->Project->Relation;
     $this->DocumentsProject = $this->Project->DocumentsProject;
     $this->Annotation = $this->Round->Annotation;
     $this->AnnotationsInterRelation = $this->Annotation->AnnotationsInterRelation;
     $this->Job = $this->User->Job;
     $find = false;
     $isReviewAutomaticAnnotation = false;
     switch ($operation) {
         case "find":
             $find = true;
             break;
         case "lastAutomatic":
             $isReviewAutomaticAnnotation = true;
             break;
     }
     $this->Round->id = $round_id;
     if (!$this->Round->exists()) {
         throw new NotFoundException(__('Invalid round'));
     }
     //
     $group_id = $this->Session->read('group_id');
     if ($group_id > 1) {
         $redirect = array('controller' => 'rounds', 'action' => 'index');
         $user_id = $this->Session->read('user_id');
     } else {
         $redirect = array('controller' => 'rounds', 'action' => 'view', $round_id);
     }
     if ($isReviewAutomaticAnnotation) {
         $documents = $this->Job->find('first', array('recursive' => -1, 'fields' => array("comments"), 'conditions' => array('Job.comments IS NOT NULL', 'Job.exception IS NULL', 'Job.user_id' => $user_id, 'Job.round_id' => $round_id, 'program' => 'Automatic_Dictionary_Annotation'), 'order' => array('Job.modified DESC')));
         if (!empty($documents)) {
             $documents = json_decode($documents['Job']['comments'], true);
             if (json_last_error() == JSON_ERROR_NONE) {
                 $documents = array_keys($documents["documentsWithAnnotations"]);
                 if (empty($documents)) {
                     $this->Session->setFlash(__('There are no recommendations for you [JSON empty]'));
                     $this->redirect($redirect);
                 }
             } else {
                 $this->Session->setFlash(__('There are no recommendations for you [JSON parser error]'));
                 $this->redirect($redirect);
             }
         } else {
             $this->Session->setFlash(__('There are no recommendations for you'));
             $this->redirect($redirect);
         }
     }
     $this->User->id = $user_id;
     if (!$this->User->exists()) {
         throw new NotFoundException(__('Invalid User'));
     }
     //
     $userRound = $this->UsersRound->find('first', array('recursive' => -1, 'fields' => 'id', 'conditions' => array('user_id' => $user_id, 'round_id' => $round_id)));
     $users_round_id = $userRound['UsersRound']['id'];
     $this->UsersRound->id = $userRound['UsersRound']['id'];
     if ($this->UsersRound->field('state') != 0) {
         $this->Session->setFlash(__('There are one process working in this documents'));
         $this->redirect($redirect);
     }
     $isMultiDocument = Configure::read('documentsPerPage') > 1;
     if ($find && $group_id == 1) {
         $isMultiDocument = false;
     } else {
         $find = false;
     }
     $round_id = $this->UsersRound->field('round_id');
     //        $round = Cache::read('round-id-' . $round_id, 'short');
     //        if (!$round) {
     //buscamos el round para saber la fecha de finalizacion
     $round = $this->Round->find('first', array('recursive' => -1, 'conditions' => array('Round.id' => $round_id)));
     //            Cache::write('round-id-' . $round_id, $round, 'short');
     //        }
     if (empty($round)) {
         throw new NotFoundException(__('Empty round data'));
     }
     App::uses('CakeTime', 'Utility');
     $isEnd = CakeTime::isPast($round['Round']['ends_in_date']);
     if ($group_id > 1) {
         if (isset($round['Round']['start_document'])) {
             $offset = $round['Round']['start_document'] - 1;
             if ($offset < 0) {
                 $offset = 0;
             }
             $limit = $round['Round']['end_document'];
         } else {
             $offset = 0;
             $limit = 0;
         }
     } else {
         $offset = 0;
         $limit = 0;
         $isEnd = true;
     }
     $projectId = $round['Round']['project_id'];
     $onlyAnnotated = false;
     if ($group_id == 1 || $isEnd) {
         $onlyAnnotated = true;
     }
     //buscamos todos los documentos del proyecto para el selector
     if ($isReviewAutomaticAnnotation) {
         $setDocumentsToAnnotateByRound = Cache::read('documents-automatic-of-user' . $round_id . $user_id . count($documents), 'short');
         $documentsListByRound = Cache::read('documents-list-by-round' . $round_id . $user_id . count($documents), 'short');
     } else {
         if ($onlyAnnotated) {
             $setDocumentsToAnnotateByRound = Cache::read('documents-annotated-of-user' . $round_id . $user_id . $offset . $limit, 'short');
             $documentsListByRound = Cache::read('documents-list-by-round' . $round_id . $user_id . $offset . $limit, 'short');
         } else {
             $setDocumentsToAnnotateByRound = Cache::read('documents-to-annotate-round' . $round_id . $offset . $limit, 'short');
             $documentsListByRound = Cache::read('documents-list-by-round' . $round_id . $offset . $limit, 'short');
         }
     }
     if (empty($setDocumentsToAnnotateByRound)) {
         if ($isReviewAutomaticAnnotation) {
             $setDocumentsToAnnotateByRound = $this->Document->find('all', array('recursive' => -1, 'fields' => array('id', 'title', 'external_id'), 'joins' => array(array('table' => 'annotated_documents', 'alias' => 'AnnotatedDocument', 'type' => 'LEFT', 'conditions' => array('AnnotatedDocument.document_id = Document.id', 'AnnotatedDocument.text_marked IS NOT NULL'))), 'conditions' => array('AnnotatedDocument.round_id' => $round_id, 'AnnotatedDocument.user_id' => $user_id, 'AnnotatedDocument.document_id' => $documents), 'order' => array('document_id ASC')));
         } else {
             if ($onlyAnnotated) {
                 $setDocumentsToAnnotateByRound = $this->Document->find('all', array('recursive' => -1, 'fields' => array('id', 'title', 'external_id'), 'joins' => array(array('table' => 'annotated_documents', 'alias' => 'AnnotatedDocument', 'type' => 'LEFT', 'conditions' => array('AnnotatedDocument.document_id = Document.id', 'AnnotatedDocument.text_marked IS NOT NULL'))), 'conditions' => array('AnnotatedDocument.round_id' => $round_id, 'AnnotatedDocument.user_id' => $user_id), 'limit' => $limit, 'offset' => $offset, 'order' => array('document_id ASC')));
             } else {
                 $setDocumentsToAnnotateByRound = $this->Document->find('all', array('recursive' => -1, 'fields' => array('id', 'title', 'external_id'), 'joins' => array(array('table' => 'documents_projects', 'alias' => 'DocumentsProject', 'type' => 'INNER', 'conditions' => array('DocumentsProject.document_id = Document.id'))), 'conditions' => array('DocumentsProject.project_id' => $projectId), 'limit' => $limit, 'offset' => $offset, 'order' => array('document_id ASC')));
             }
         }
         $documentsListByRound = array();
         //            $documentsListByRound = Set::format($setDocumentsToAnnotateByRound, '{1} - {0}', array(
         //                        '{n}.Document.external_id', '{n}.Document.title'));
         //
         //            $setDocumentsToAnnotateByRound = Set::combine($setDocumentsToAnnotateByRound, '{n}.Document.id', '{n}.Document');
         $documentsListByRound = array();
         $copySetDocumentsToAnnotateByRound = array();
         $cont = 0;
         foreach ($setDocumentsToAnnotateByRound as $document) {
             $id = $document['Document']['id'];
             $copySetDocumentsToAnnotateByRound[$id] = $document['Document'];
             array_push($documentsListByRound, array('name' => $document['Document']['external_id'] . " - " . $document['Document']['title'], 'value' => $cont, 'data-document-id' => $id));
             $cont++;
         }
         $setDocumentsToAnnotateByRound = $copySetDocumentsToAnnotateByRound;
         if ($isReviewAutomaticAnnotation) {
             Cache::write('documents-automatic-of-user' . $round_id . $user_id . count($documents), $setDocumentsToAnnotateByRound, 'short');
             Cache::write('documents-list-by-round' . $round_id . $user_id . count($documents), $documentsListByRound, 'short');
         } else {
             if ($onlyAnnotated) {
                 Cache::write('documents-annotated-of-user' . $round_id . $user_id . $offset . $limit, $setDocumentsToAnnotateByRound, 'short');
                 Cache::write('documents-list-by-round' . $round_id . $user_id . $offset . $limit, $documentsListByRound, 'short');
             } else {
                 Cache::write('documents-to-annotate-round' . $projectId . $offset . $limit, $setDocumentsToAnnotateByRound, 'short');
                 Cache::write('documents-list-by-round' . $round_id . $offset . $limit, $documentsListByRound, 'short');
             }
         }
     }
     $idsDocumentsToAnnotateByRound = array_keys($setDocumentsToAnnotateByRound);
     if (isset($this->params['named']['page'])) {
         $page = $this->params['named']['page'];
         if ($page <= 0) {
             $page = 1;
         }
         if (!$isMultiDocument) {
             $document_id = $idsDocumentsToAnnotateByRound[$page - 1];
         }
     } else {
         $page = 1;
         if (!$isMultiDocument) {
             $document_id = $idsDocumentsToAnnotateByRound[0];
         }
     }
     if ($isMultiDocument) {
         /* ================================================================================= */
         /* ==================================Multidocument================================== */
         /* ================================================================================= */
         $this->paginate = array('recursive' => -1, 'order' => array('DocumentsProject.document_id' => 'asc'), 'conditions' => array('DocumentsProject.document_id' => $idsDocumentsToAnnotateByRound, 'DocumentsProject.project_id' => $projectId), 'limit' => Configure::read('documentsPerPage'), 'order' => 'document_id ASC');
         $documentsProject = $this->paginate($this->DocumentsProject);
         $idsDocumentsOfPage = Hash::extract($documentsProject, '{n}.DocumentsProject.document_id');
         if (empty($idsDocumentsOfPage)) {
             $this->Session->setFlash(__('There are no documents annotated'));
             $this->redirect($redirect);
         }
         if ($group_id > 1) {
             //delete annotation
             $deleteCascade = Configure::read('deleteCascade');
             $this->Annotation->deleteAll(array('Annotation.round_id' => $round_id, 'Annotation.user_id' => $user_id, 'Annotation.document_id' => $idsDocumentsOfPage, 'Annotation.init IS NULL', 'Annotation.end IS NULL'), $deleteCascade);
         }
         $annotatedDocuments = $this->AnnotatedDocument->find('all', array('fields' => array('id', 'document_id', 'text_marked'), 'recursive' => -1, 'conditions' => array('round_id' => $round_id, 'user_id' => $user_id, 'document_id' => $idsDocumentsOfPage), 'order' => array('AnnotatedDocument.document_id Asc')));
         $documentsAnnotatedIds = Hash::extract($annotatedDocuments, '{n}.AnnotatedDocument.document_id');
         $annotatedDocuments = Set::combine($annotatedDocuments, '{n}.AnnotatedDocument.document_id', '{n}.AnnotatedDocument');
         //            $diff = array_diff($documentsAnnotatedIds, $documentsIds);
         $documentsOfPage = Cache::read('documents-page' . $page, 'short');
         if (!$documentsOfPage) {
             $documentsOfPage = $this->Document->find('all', array('recursive' => -1, 'fields' => array('html', 'id', 'title', 'external_id'), 'conditions' => array('Document.id' => $idsDocumentsOfPage)));
             $documentsOfPage = Set::combine($documentsOfPage, '{n}.Document.id', '{n}.Document');
             Cache::write('documents-page' . $page . $user_id, $documentsOfPage, 'short');
         }
         //
         //            $documentsTitles = Cache::read('documents-titles', 'short');
         //            if (!$documentsTitles) {
         //                $documentsTitles = $this->UsersRound->Round->Project->Document->find('all', array(
         //                    'recursive' => -1,
         //                    'fields' => array('id', 'title', 'external_id'),
         //                    'conditions' => array(
         //                        'Document.id' => $documentsIds,
         //                    )
         //                ));
         //                $documentsTitles = Set::combine($documentsTitles, '{n}.Document.id', '{n}.Document.external_idDocument.title');
         //                Cache::write('documents-titles', $documentsTitles, 'short');
         //            }
         $size = count($idsDocumentsOfPage);
         for ($i = 0; $i < $size; $i++) {
             $document_id = intval($idsDocumentsOfPage[$i]);
             if (!empty($annotatedDocuments[$document_id])) {
                 if (strlen(trim($annotatedDocuments[$document_id]['text_marked'])) == 0) {
                     $annotatedDocuments[$document_id]['text_marked'] = $documentsOfPage[$document_id]['html'];
                 }
                 //                    debug(strlen(trim($userRounds[$document_id]['text_marked'])));
                 //                    debug($documents[$document_id]['html']);
             } else {
                 if (strlen(trim($documentsOfPage[$document_id]['html'])) !== 0) {
                     $annotatedDocuments[$document_id] = array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => $document_id, 'annotation_minutes' => 0);
                     if ($group_id > 1 && !$isEnd) {
                         if (empty($annotatedDocuments[$document_id]['html'])) {
                             //                        $this->AnnotatedDocument->id = $annotatedDocuments[$document_id]['id'];
                             $this->AnnotatedDocument->create();
                             if (!$this->AnnotatedDocument->save($annotatedDocuments[$document_id])) {
                                 debug($annotatedDocuments);
                                 debug($this->AnnotatedDocument->validationErrors);
                                 $this->Session->setFlash(__('ops! error creating AnnotatedDocument '));
                                 throw new Exception();
                                 //                            $this->redirect($redirect);
                             }
                             $annotatedDocuments[$document_id]['id'] = $this->AnnotatedDocument->id;
                         }
                     } else {
                         $annotatedDocuments[$document_id]['id'] = -1;
                     }
                     $annotatedDocuments[$document_id]['text_marked'] = $documentsOfPage[$document_id]['html'];
                     $annotatedDocuments[$document_id]['document_id'] = $document_id;
                 }
             }
             $title = "Title: " . $setDocumentsToAnnotateByRound[$document_id]['title'];
             if (isset($setDocumentsToAnnotateByRound[$document_id]['external_id'])) {
                 $title = "ID: " . $setDocumentsToAnnotateByRound[$document_id]['external_id'];
             }
             $annotatedDocuments[$document_id]['title'] = $title;
         }
         $documentAssessment = $this->Document->DocumentsAssessment->find('list', array('recursive' => -1, 'fields' => array('document_id', 'document_id'), 'conditions' => array('user_id' => $user_id, 'project_id' => $projectId, 'document_id' => $idsDocumentsOfPage)));
         $this->set('documentAssessments', $documentAssessment);
         $this->set('annotatedDocuments', $annotatedDocuments);
         $triada = array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => -1, 'users_round_id' => $users_round_id);
         $this->set('DocumentsProject', $documentsProject);
     } else {
         /* ================================================================================= */
         /* ==================================No multidocument=============================== */
         /* ================================================================================= */
         $document = Cache::read('document-id-' . $document_id, 'short');
         if (!$document) {
             $document = $this->Document->find('first', array('recursive' => -1, 'fields' => array('html', 'title', 'external_id'), 'joins' => array(array('table' => 'documents_projects', 'alias' => 'DocumentsProject', 'type' => 'INNER', 'conditions' => array('DocumentsProject.document_id = Document.id'))), 'conditions' => array('DocumentsProject.project_id' => $projectId, 'DocumentsProject.document_id' => $document_id)));
             Cache::write('first-doc-project-id-' . $document_id, $document, 'short');
         }
         $annotatedDocuments = $this->AnnotatedDocument->find('first', array('recursive' => -1, 'conditions' => array('round_id' => $round_id, 'user_id' => $user_id, 'document_id' => $document_id), 'order' => array('AnnotatedDocument.document_id Asc')));
         if (!empty($annotatedDocuments)) {
             if (strlen(trim($annotatedDocuments['AnnotatedDocument']['text_marked'])) !== 0) {
                 $this->set('text', $annotatedDocuments['AnnotatedDocument']['text_marked']);
                 $this->set('document_annotated_id', $annotatedDocuments['AnnotatedDocument']['id']);
             } else {
                 $this->set('document_annotated_id', -1);
                 $this->set('text', $document['Document']['html']);
             }
         } else {
             if (!empty($document) && strlen(trim($document['Document']['html'])) !== 0) {
                 $annotatedDocuments = array('AnnotatedDocument' => array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => $document_id, 'text_marked' => $document['Document']['html'], 'annotation_minutes' => 0));
                 if ($group_id > 1 && !$isEnd) {
                     if (!$this->AnnotatedDocument->save($annotatedDocuments)) {
                         debug($this->AnnotatedDocument->validationErrors);
                         $this->Session->setFlash(__('ops! error creating AnnotatedDocument '));
                         $this->redirect($redirect);
                     }
                     $annotatedDocuments['AnnotatedDocument']['id'] = $this->AnnotatedDocument->id;
                 } else {
                     $annotatedDocuments['AnnotatedDocument']['id'] = -1;
                 }
                 $title = "Title: " . $setDocumentsToAnnotateByRound[$document_id]['title'];
                 if (isset($setDocumentsToAnnotateByRound[$document_id]['external_id'])) {
                     $title = "ID: " . $setDocumentsToAnnotateByRound[$document_id]['external_id'];
                 }
                 $annotatedDocuments[$document_id]['title'] = $title;
                 $this->set('document_annotated_id', $annotatedDocuments['AnnotatedDocument']['id']);
                 $this->set('text', $document['Document']['html']);
             } else {
                 $this->Session->setFlash(__('There are no documents associated with this project'));
                 $this->redirect($redirect);
             }
         }
         if ($group_id > 1) {
             //delete annotation
             $deleteCascade = Configure::read('deleteCascade');
             $this->Annotation->deleteAll(array('Annotation.round_id' => $round_id, 'Annotation.user_id' => $user_id, 'Annotation.init IS NULL', 'Annotation.end IS NULL'), $deleteCascade);
         }
         $this->paginate = array('recursive' => -1, 'order' => array('DocumentsProject.document_id' => 'asc'), 'conditions' => array('document_id' => array_keys($setDocumentsToAnnotateByRound)), 'limit' => 1, 'offset' => $offset);
         $this->set('DocumentsProject', $this->paginate($this->DocumentsProject, array('DocumentsProject.project_id' => $projectId)));
         $title = "Title: " . $document['Document']['title'];
         if (isset($document['Document']['external_id'])) {
             $title = "ID: " . $document['Document']['external_id'];
         }
         $this->set('title', $title);
         //variable que contiene User.round.Document.user_round_id
         $triada = array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => $document_id, 'users_round_id' => $users_round_id, 'document_annotated_id' => $annotatedDocuments['AnnotatedDocument']['id']);
     }
     /* ======================================= */
     $highlight = 2;
     if (isset($round['Round']['highlight'])) {
         $highlight = $round['Round']['highlight'];
     }
     $trim_helper = $round['Round']['trim_helper'];
     $whole_word_helper = $round['Round']['whole_word_helper'];
     $punctuation_helper = $round['Round']['punctuation_helper'];
     //escribimos la variable en una variable de session puesto que nos sera util a la hora de verificar la fecha cuando se intente crear anotaciones o editarlas
     $this->Session->write('isEnd', $isEnd);
     //esta variable sera usada para constatar que no se intentan modificar dichas variables
     $this->Session->write('triada', $triada);
     //        App::uses('CakeTime', 'Utility');
     //        $date = CakeTime::format('+0 seconds', '%Y-%m-%d %H:M:%S');
     $relations = Cache::read('relations-project-id-' . $projectId, 'short');
     if (!$relations) {
         $relations = $this->Relation->find('all', array('recursive' => -1, 'conditions' => array('Relation.project_id' => $projectId)));
         Cache::write('relations-project-id-' . $projectId, $relations, 'short');
     }
     $types = Cache::read('usersRoundTypes-round-id-' . $round_id, 'short');
     if (!$types) {
         $types = $this->Type->find('all', array('recursive' => -1, 'contain' => array('Question'), 'joins' => array(array('table' => 'types_rounds', 'alias' => 'TypesRound', 'type' => 'LEFT', 'conditions' => array('TypesRound.type_id = Type.id'))), 'conditions' => array('TypesRound.round_id' => $round_id)));
         Cache::write('usersRoundTypes-round-id-' . $round_id, $types, 'short');
     }
     if (!$find) {
         $relationIds = Hash::extract($relations, '{n}.Relation.id');
         $annotationsInterRelations = $this->AnnotationsInterRelation->find('all', array('recursive' => -1, 'fields' => array('id', 'relation_id', 'AnnotationB.annotated_text', 'AnnotationA.annotated_text', 'AnnotationB.type_id', 'AnnotationA.type_id', 'AnnotationB.document_id', 'AnnotationA.document_id', 'AnnotationB.id', 'AnnotationA.id'), 'joins' => array(array('table' => 'annotations', 'alias' => 'AnnotationA', 'type' => 'INNER', 'conditions' => array('AnnotationA.id = AnnotationsInterRelation.annotation_a_id', 'AnnotationsInterRelation.relation_id' => $relationIds, 'AnnotationA.document_id' => $idsDocumentsOfPage)), array('table' => 'annotations', 'alias' => 'AnnotationB', 'type' => 'INNER', 'conditions' => array('AnnotationB.id = AnnotationsInterRelation.annotation_b_id', 'AnnotationsInterRelation.relation_id' => $relationIds, 'AnnotationB.document_id' => $idsDocumentsOfPage)))));
         $this->set('relationsMap', Set::combine($relations, '{n}.Relation.id', '{n}.Relation'));
         $this->set('typesMap', Set::combine($types, '{n}.Type.id', '{n}.Type'));
         $this->set('documentsMap', $documentsOfPage);
         $this->set('annotationsInterRelations', $annotationsInterRelations);
         $this->set('isReviewAutomaticAnnotation', $isReviewAutomaticAnnotation);
     }
     if (!$this->Session->check('start_step') && $group_id > 1) {
         $this->Session->write('start_step', new DateTime(''));
     }
     $this->set('document_id', $document_id);
     $this->set('findMode', $find);
     $this->set('isMultiDocument', $isMultiDocument);
     /* ================================================================================= */
     /* ==================================No Ajax================================== */
     /* ================================================================================= */
     if (!$this->request->is('ajax')) {
         if (empty($types)) {
             $this->Session->setFlash(__('There are no types associated with this round'));
             return $this->redirect($redirect);
         }
         //buscamos el primer documento del proyecto
         $nonTypes = Cache::read('nonTypes-round-id-' . $round_id, 'short');
         if (!$nonTypes) {
             $listTypes = Set::classicExtract($types, '{n}.Type.id');
             $nonTypes = $this->Type->find('list', array('fields' => 'Type.name', 'recursive' => -1, 'conditions' => array('Type.project_id' => $projectId, "NOT" => array('Type.id' => $listTypes))));
             Cache::write('nonTypes-round-id-' . $round_id, $nonTypes, 'short');
         }
         //            debug($nonTypes);
         //            throw new Exception;
         //            debug($setDocumentsToAnnotateByRound);
         $this->set('documentList', $documentsListByRound);
         if ($page > 0) {
             $page--;
         }
         $this->set('documentsPerPage', Configure::read('documentsPerPage'));
         $this->set('documentsMap', array_flip($idsDocumentsToAnnotateByRound));
         $this->set('relations', $relations);
         $this->set('operation', $operation);
         $this->set('page', $page);
         $this->set('round_id', $round_id);
         $this->set('project_id', $projectId);
         $this->set('types', $types);
         //lo utilizaremos para eliminar las anotaciones de un tipo eliminado
         $this->set('nonTypes', $nonTypes);
         $this->set('isEnd', $isEnd);
         $this->set('user_id', $user_id);
         if (isset($document['Document']['external_id'])) {
             $title = "ID: " . $document['Document']['external_id'];
         }
         $this->set('title', $title);
         $this->set('trim_helper', $trim_helper);
         $this->set('highlight', $highlight);
         $this->set('whole_word_helper', $whole_word_helper);
         $this->set('punctuation_helper', $punctuation_helper);
         $this->set('annotationMenu', true);
         $this->render("start");
     } else {
         $this->layout = 'ajax';
         //            $title = "Title: " . $document['Document']['title'];
         //            if (isset($document['Document']['external_id'])) {
         //                $title = "ID: " . $document['Document']['external_id'];
         //            }
         $this->set('title', $title);
         $this->set('isEnd', $isEnd);
         $this->render("ajax");
     }
     //            $this->autoRender = false;
 }
 /**
  *    Days in theme
  *    @param int $theme_id
  */
 public function days($theme_id = null, $user_id = null)
 {
     if (!$theme_id) {
         return;
     }
     $options = array('recursive' => -1, 'conditions' => array('Day.theme_id' => $theme_id), 'order' => array('data ASC'));
     $rows = $this->Day->find('all', $options);
     foreach ($rows as $key => $row) {
         $row['Day']['isFuture'] = false;
         $row['Day']['isPast'] = false;
         $row['Day']['isToday'] = false;
         $row['Day']['comments'] = $this->Comment->find('count', array('conditions' => array('Comment.user_id' => !$this->isUser() ? $user_id : $this->getUserId(), 'Comment.day_id' => $row['Day']['id'])));
         if (CakeTime::isFuture($row['Day']['data'])) {
             $row['Day']['isFuture'] = true;
         }
         if (CakeTime::isPast($row['Day']['data'])) {
             $row['Day']['isPast'] = true;
         }
         if (CakeTime::isToday($row['Day']['data'])) {
             $row['Day']['isToday'] = true;
         }
         $data[] = $row['Day'];
     }
     $this->set($data);
     $this->set('_serialize', array_keys($data));
 }
 public function start2($round_id = null, $user_id = null, $find = null)
 {
     $group_id = $this->Session->read('group_id');
     if ($group_id > 1) {
         $redirect = array('controller' => 'rounds', 'action' => 'index');
         $user_id = $this->Session->read('user_id');
     } else {
         if (!$this->Session->check('users_round_id')) {
             $this->Session->write('users_round_id', $user_id);
         } else {
             $last_user_id = $this->Session->read('users_round_id');
             if (isset($user_id) && $user_id != $last_user_id) {
                 $this->Session->write('users_round_id', $user_id);
             }
             $user_id = $this->Session->read('users_round_id');
         }
         $redirect = array('controller' => 'rounds', 'action' => 'view', $round_id);
     }
     $multiDocument = Configure::read('documentsPerPage') > 1;
     if ($find && $group_id == 1) {
         $multiDocument = false;
     } else {
         $find = false;
     }
     $round = Cache::read('round-id-' . $round_id, 'short');
     if (!$round) {
         //buscamos el round para saber la fecha de finalizacion
         $round = $this->UsersRound->Round->find('first', array('recursive' => -1, 'conditions' => array('Round.id' => $round_id)));
         Cache::write('round-id-' . $round_id, $round, 'short');
     }
     if (empty($round)) {
         throw new NotFoundException(__('Invalid round'));
     }
     App::uses('CakeTime', 'Utility');
     $isEnd = CakeTime::isPast($round['Round']['ends_in_date']);
     if ($group_id > 1) {
         if (isset($round['Round']['start_document'])) {
             $offset = $round['Round']['start_document'] - 1;
             if ($offset < 0) {
                 $offset = 0;
             }
             $limit = $round['Round']['end_document'];
         } else {
             $offset = 0;
             $limit = 0;
         }
     } else {
         $offset = 0;
         $limit = 0;
         $isEnd = true;
     }
     $projectId = $round['Round']['project_id'];
     $onlyAnnotated = false;
     if ($group_id == 1 || $isEnd) {
         $onlyAnnotated = true;
     }
     //buscamos todos los documentos del proyecto para el selector
     if ($onlyAnnotated) {
         $documents = Cache::read('documents-list-project-id-onlyAnnotated' . $round_id . '-' . $user_id, 'short');
     } else {
         $documents = Cache::read('documents-list-project-id-' . $projectId, 'short');
     }
     if (!$documents) {
         if ($onlyAnnotated) {
             $documentsAll = $this->UsersRound->Round->Project->Document->find('all', array('recursive' => -1, 'fields' => array('id', 'title', 'external_id'), 'joins' => array(array('table' => 'users_rounds', 'alias' => 'UsersRounds', 'type' => 'LEFT', 'conditions' => array('UsersRounds.document_id = Document.id', 'UsersRounds.text_marked IS NOT NULL'))), 'conditions' => array('UsersRounds.round_id' => $round_id, 'UsersRounds.user_id' => $user_id), 'limit' => $limit, 'offset' => $offset, 'order' => array('document_id Asc')));
         } else {
             $documentsAll = $this->UsersRound->Round->Project->Document->find('all', array('recursive' => -1, 'fields' => array('id', 'title', 'external_id'), 'joins' => array(array('table' => 'documents_projects', 'alias' => 'DocumentsProject', 'type' => 'INNER', 'conditions' => array('DocumentsProject.document_id = Document.id'))), 'conditions' => array('DocumentsProject.project_id' => $projectId), 'limit' => $limit, 'offset' => $offset, 'order' => array('document_id Asc')));
         }
         $documents = array();
         $tam = count($documentsAll);
         for ($index = 0; $index < $tam; $index++) {
             $id = $documentsAll[$index]['Document']['id'];
             $title = "";
             if (isset($documentsAll[$index]['Document']['external_id'])) {
                 $title .= $documentsAll[$index]['Document']['external_id'] . " - ";
             }
             $title .= $documentsAll[$index]['Document']['title'];
             $documents[$id] = $title;
         }
         if ($onlyAnnotated) {
             Cache::write('documents-list-project-id-onlyAnnotated' . $round_id . '-' . $user_id, $documents, 'short');
         } else {
             Cache::write('documents-list-project-id-' . $projectId, $documents, 'short');
         }
     }
     $ids = array_keys($documents);
     if (isset($this->params['named']['page'])) {
         $page = $this->params['named']['page'];
         if ($page <= 0) {
             $page = 1;
         }
         if (!$multiDocument) {
             $document_id = $ids[$page - 1];
         }
     } else {
         $page = 1;
         if (!$multiDocument) {
             $document_id = $ids[0];
         }
     }
     /* ===============No Ajax=================== */
     if (!$this->request->is('ajax')) {
         $types = Cache::read('usersRoundTypes-round-id-' . $round_id, 'short');
         if (!$types) {
             $types = $this->UsersRound->Round->Type->find('all', array('recursive' => -1, 'contain' => array('Question'), 'joins' => array(array('table' => 'types_rounds', 'alias' => 'TypesRound', 'type' => 'LEFT', 'conditions' => array('TypesRound.type_id = Type.id'))), 'conditions' => array('TypesRound.round_id' => $round_id)));
             Cache::write('usersRoundTypes-round-id-' . $round_id, $types, 'short');
         }
         if (empty($types)) {
             $this->Session->setFlash(__('There are no types associated with this round'));
             return $this->redirect($redirect);
         }
         //buscamos el primer documento del proyecto
         $nonTypes = Cache::read('nonTypes-round-id-' . $round_id, 'short');
         if (!$nonTypes) {
             $listTypes = Set::classicExtract($types, '{n}.Type.id');
             $nonTypes = $this->UsersRound->Round->Type->find('list', array('fields' => 'Type.name', 'recursive' => -1, 'conditions' => array('Type.project_id' => $projectId, "NOT" => array('Type.id' => $listTypes))));
             Cache::write('nonTypes-round-id-' . $round_id, $nonTypes, 'short');
         }
         $relations = Cache::read('relations-project-id-' . $projectId, 'short');
         if (!$relations) {
             $relations = $this->UsersRound->Round->Project->Relation->find('all', array('recursive' => -1, 'conditions' => array('Relation.project_id' => $projectId)));
             Cache::write('relations-project-id-' . $projectId, $relations, 'short');
         }
     }
     if ($multiDocument) {
         /* ================================================================================= */
         /* ==================================Multidocument================================== */
         /* ================================================================================= */
         $this->paginate = array('recursive' => -1, 'order' => array('DocumentsProject.document_id' => 'asc'), 'conditions' => array('document_id' => array_keys($documents)), 'limit' => Configure::read('documentsPerPage'), 'offset' => $offset);
         $documentsProject = $this->paginate($this->UsersRound->Round->Project->DocumentsProject, array('DocumentsProject.project_id' => $projectId));
         $documentsIds = Hash::extract($documentsProject, '{n}.DocumentsProject.document_id');
         if (empty($documentsIds)) {
             $this->Session->setFlash(__('There are no documents associated with this project'));
             $this->redirect($redirect);
         }
         if ($group_id > 1) {
             //delete annotation
             $deleteCascade = Configure::read('deleteCascade');
             $this->UsersRound->Annotation->deleteAll(array('Annotation.round_id' => $round_id, 'Annotation.user_id' => $user_id, 'Annotation.document_id' => $documentsIds, 'Annotation.init IS NULL', 'Annotation.end IS NULL'), $deleteCascade);
         }
         $userRounds = $this->UsersRound->find('all', array('fields' => array('id', 'document_id', 'text_marked'), 'recursive' => -1, 'conditions' => array('round_id' => $round_id, 'user_id' => $user_id, 'document_id' => $documentsIds), 'order' => array('UsersRound.document_id Asc')));
         $documentsAnnotatedIds = Hash::extract($userRounds, '{n}.UsersRound.document_id');
         $userRounds = Set::combine($userRounds, '{n}.UsersRound.document_id', '{n}.UsersRound');
         //            $diff = array_diff($documentsAnnotatedIds, $documentsIds);
         $documents = Cache::read('documents-page' . $page, 'short');
         if (!$documents) {
             $documents = $this->UsersRound->Round->Project->Document->find('all', array('recursive' => -1, 'fields' => array('html', 'id', 'title', 'external_id'), 'conditions' => array('Document.id' => $documentsIds)));
             $documents = Set::combine($documents, '{n}.Document.id', '{n}.Document');
             Cache::write('documents-page' . $page, $documents, 'short');
         }
         //            $documentsTitles = Cache::read('documents-titles-page' . $page, 'short');
         //            if (!$documentsTitles) {
         //                $documentsTitles = $this->UsersRound->Round->Project->Document->find('all', array(
         //                    'recursive' => -1,
         //                    'fields' => array('id', 'title', 'external_id'),
         //                    'conditions' => array(
         //                        'Document.id' => $documentsIds,
         //                    )
         //                ));
         //                $documentsTitles = Set::combine($documentsTitles, '{n}.Document.id', '{n}.Document');
         //                Cache::write('documents-titles-page' . $page, $documentsTitles, 'short');
         //            }
         $size = count($documentsIds);
         for ($i = 0; $i < $size; $i++) {
             $document_id = intval($documentsIds[$i]);
             if (!empty($userRounds[$document_id])) {
                 if (strlen(trim($userRounds[$document_id]['text_marked'])) == 0) {
                     $userRounds[$document_id]['text_marked'] = $documents[$document_id]['html'];
                 }
                 //                    debug(strlen(trim($userRounds[$document_id]['text_marked'])));
                 //                    debug($documents[$document_id]['html']);
             } else {
                 if (strlen(trim($documents[$document_id]['html'])) !== 0) {
                     $userRounds[$document_id] = array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => $document_id, 'text_marked' => $documents[$document_id]['html']);
                     if ($group_id > 1) {
                         $this->UsersRound->create();
                         if (!$this->UsersRound->save($userRounds[$document_id])) {
                             debug($this->UsersRound->validationErrors);
                             $this->Session->setFlash(__('ops! error creating user round ' . $this->UsersRound->validationErrors));
                             $this->redirect($redirect);
                         }
                         $userRounds[$document_id]['id'] = $this->UsersRound->id;
                     }
                     $userRounds[$document_id]['text_marked'] = $documents[$document_id]['html'];
                     $userRounds[$document_id]['document_id'] = $document_id;
                 }
             }
             $title = "Title: " . $documents[$document_id]['title'];
             if (isset($documents[$document_id]['external_id'])) {
                 $title = "ID: " . $documents[$document_id]['external_id'];
             }
             $userRounds[$document_id]['title'] = $title;
         }
         $documentAssessment = $this->UsersRound->Round->Project->Document->DocumentsAssessment->find('list', array('recursive' => -1, 'fields' => array('document_id', 'document_id'), 'conditions' => array('user_id' => $user_id, 'project_id' => $projectId, 'document_id' => $ids)));
         $this->set('documentAssessments', $documentAssessment);
         $this->set('userRounds', $userRounds);
         $triada = array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => -1, 'users_round_id' => -1);
         $this->set('DocumentsProject', $documentsProject);
     } else {
         /* ================================================================================= */
         /* ==================================No multidocument=============================== */
         /* ================================================================================= */
         $document = Cache::read('document-id-' . $document_id, 'short');
         if (!$document) {
             $document = $this->UsersRound->Round->Project->Document->find('first', array('recursive' => -1, 'fields' => array('html', 'title', 'external_id'), 'joins' => array(array('table' => 'documents_projects', 'alias' => 'DocumentsProject', 'type' => 'INNER', 'conditions' => array('DocumentsProject.document_id = Document.id'))), 'conditions' => array('DocumentsProject.project_id' => $projectId, 'DocumentsProject.document_id' => $document_id)));
             Cache::write('first-doc-project-id-' . $document_id, $document, 'short');
         }
         $userRound = $this->UsersRound->find('first', array('recursive' => -1, 'conditions' => array('round_id' => $round_id, 'user_id' => $user_id, 'document_id' => $document_id), 'order' => array('UsersRound.document_id Asc')));
         if (!empty($userRound)) {
             if (strlen(trim($userRound['UsersRound']['text_marked'])) !== 0) {
                 $this->set('text', $userRound['UsersRound']['text_marked']);
             } else {
                 //para el primer user round vacio
                 $this->set('text', $document['Document']['html']);
             }
         } else {
             if (!empty($document) && strlen(trim($document['Document']['html'])) !== 0) {
                 $userRound = array('UsersRound' => array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => $document_id, 'text_marked' => $document['Document']['html']));
                 if ($group_id > 1) {
                     if (!$this->UsersRound->save($userRound)) {
                         debug($this->UsersRound->validationErrors);
                         $this->Session->setFlash(__('ops! error creating user round ' . $this->UsersRound->validationErrors));
                         $this->redirect($redirect);
                     }
                 }
                 $userRound['UsersRound']['id'] = $this->UsersRound->id;
                 $this->set('text', $document['Document']['html']);
             } else {
                 $this->Session->setFlash(__('There are no documents associated with this project'));
                 $this->redirect($redirect);
             }
         }
         if ($group_id > 1) {
             //delete annotation
             $deleteCascade = Configure::read('deleteCascade');
             $this->UsersRound->Annotation->deleteAll(array('Annotation.round_id' => $userRound['UsersRound']['round_id'], 'Annotation.user_id' => $user_id, 'Annotation.users_round_id' => $userRound['UsersRound']['id'], 'Annotation.init IS NULL', 'Annotation.end IS NULL'), $deleteCascade);
         }
         $this->paginate = array('recursive' => -1, 'order' => array('DocumentsProject.document_id' => 'asc'), 'conditions' => array('document_id' => array_keys($documents)), 'limit' => 1, 'offset' => $offset);
         $this->set('DocumentsProject', $this->paginate($this->UsersRound->Round->Project->DocumentsProject, array('DocumentsProject.project_id' => $projectId)));
         $title = "Title: " . $document['Document']['title'];
         if (isset($document['Document']['external_id'])) {
             $title = "ID: " . $document['Document']['external_id'];
         }
         $this->set('title', $title);
         $this->set('users_round_id', $userRound['UsersRound']['id']);
         //variable que contiene User.round.Document.user_round_id
         $triada = array('user_id' => $user_id, 'round_id' => $round_id, 'document_id' => $document_id, 'users_round_id' => $userRound['UsersRound']['id']);
     }
     $trim_helper = $round['Round']['trim_helper'];
     $whole_word_helper = $round['Round']['whole_word_helper'];
     $punctuation_helper = $round['Round']['punctuation_helper'];
     //escribimos la variable en una variable de session puesto que nos sera util a la hora de verificar la fecha cuando se intente crear anotaciones o editarlas
     $this->Session->write('isEnd', $isEnd);
     //esta variable sera usada para constatar que no se intentan modificar dichas variables
     $this->Session->write('triada', $triada);
     //        App::uses('CakeTime', 'Utility');
     //        $date = CakeTime::format('+0 seconds', '%Y-%m-%d %H:M:%S');
     if (!$this->Session->check('start_step') && $group_id > 1) {
         $this->Session->write('start_step', new DateTime(''));
     }
     $this->set('document_id', $document_id);
     $this->set('multiDocument', $multiDocument);
     $this->set('findMode', $find);
     if (!$this->request->is('ajax')) {
         $this->set('documents', array_values($documents));
         if ($page > 0) {
             $page--;
         }
         $this->set('page', $page);
         $this->set('round_id', $round_id);
         $this->set('project_id', $projectId);
         $this->set('types', $types);
         $this->set('relations', $relations);
         //lo utilizaremos para eliminar las anotaciones de un tipo eliminado
         $this->set('nonTypes', $nonTypes);
         $this->set('isEnd', $isEnd);
         $this->set('user_id', $user_id);
         if (isset($document['Document']['external_id'])) {
             $title = "ID: " . $document['Document']['external_id'];
         }
         $this->set('title', $title);
         $this->set('trim_helper', $trim_helper);
         $this->set('whole_word_helper', $whole_word_helper);
         $this->set('punctuation_helper', $punctuation_helper);
         $this->set('annotationMenu', true);
         $this->render("start");
     } else {
         $this->layout = 'ajax';
         $title = "Title: " . $document['Document']['title'];
         if (isset($document['Document']['external_id'])) {
             $title = "ID: " . $document['Document']['external_id'];
         }
         $this->set('title', $title);
         $this->set('isEnd', $isEnd);
         $this->render("ajax");
     }
     //            $this->autoRender = false;
 }
 /**
  *Agrega entrada a la bitácora actual
  */
 public function addEntry($uId, $pId)
 {
     if ($this->request->is('post') || $this->request->is('get')) {
         $record = $this->Record->findByUserIdAndProjectIdAndActiva($uId, $pId, true);
         $this->set('proyecto', $this->Record->Project->findById($pId));
         $this->set('usuario', $this->Record->User->findById($uId));
         if ($record) {
             if (CakeTime::isPast($record['Record']['fecha_fin'])) {
                 //Se cambia para que no esté activa la bitácora actual
                 $this->Record->id = $record['Record']['id'];
                 $this->Record->save(array('activa' => false));
                 //Se crea la nueva bitácora
                 $this->Record->create();
                 $entrada = $this->request->data;
                 //como las bitácoras son semanales hay que hacerlo con fechas secuenciales
                 $entrada['Record']['fecha_inicio'] = date("Y-m-d", strtotime("+1 days", strtotime($record['Record']['fecha_fin'])));
                 $entrada['Record']['fecha_fin'] = date("Y-m-d", strtotime("+8 days", strtotime($record['Record']['fecha_fin'])));
                 $entrada['Record']['project_id'] = $pId;
                 $entrada['Record']['user_id'] = $uId;
                 if ($this->Record->save($entrada)) {
                     $RecId = $this->Record->id;
                     $this->Record->RecordEntry->create();
                     $this->Record->RecordEntry->save(array('RecordEntry' => array('timestamp' => CakeTime::format(time(), '%B %e, %Y %H:%M %p'), 'cuerpo' => $this->request->data['Record']['cuerpo'], 'record_id' => $RecId)));
                     $this->Flash->success('Nueva bitácora creada.');
                     if ($this->Auth->user()['rol'] == 3) {
                         return $this->redirect(array('pm' => true, 'action' => 'displayRecords', $uId, $pId));
                     }
                     return $this->redirect(array('action' => 'displayRecords', $uId, $pId));
                 } else {
                     $this->Flash->set(__('No se puedo crear la nueva bitácora.'));
                 }
             } else {
                 if ($this->request->is('post') && $this->request->data) {
                     $this->Record->id = $record['Record']['id'];
                     $entrada = $this->request->data;
                     if ($this->Record->save($entrada)) {
                         $RecId = $this->Record->id;
                         $this->Record->RecordEntry->create();
                         $this->Record->RecordEntry->save(array('RecordEntry' => array('timestamp' => CakeTime::format(time(), '%B %e, %Y %H:%M %p'), 'cuerpo' => $this->request->data['Record']['cuerpo'], 'record_id' => $RecId)));
                         $this->Flash->success('Entrada añadida.');
                         if ($this->Auth->user()['rol'] == 3) {
                             return $this->redirect(array('pm' => true, 'action' => 'displayRecords', $uId, $pId));
                         }
                         return $this->redirect(array('action' => 'displayRecords', $uId, $pId));
                     } else {
                         $this->Flash->set(__('No se puedo salvar la entrada.'));
                     }
                 }
             }
         } else {
             $this->Record->create();
             $entrada = $this->request->data;
             $entrada['Record']['fecha_inicio'] = CakeTime::format(time(), '%y-%m-%d');
             $entrada['Record']['fecha_fin'] = CakeTime::format('+7 days', '%y-%m-%d');
             $entrada['Record']['project_id'] = $pId;
             $entrada['Record']['user_id'] = $uId;
             if ($this->Record->save($entrada)) {
                 $RecId = $this->Record->id;
                 $this->Record->RecordEntry->create();
                 $this->Record->RecordEntry->save(array('RecordEntry' => array('timestamp' => CakeTime::format(time(), '%B %e, %Y %H:%M %p'), 'cuerpo' => $this->request->data['Record']['cuerpo'], 'record_id' => $RecId)));
                 $this->Flash->success('Bitácora creada.');
                 if ($this->Auth->user()['rol'] == 3) {
                     return $this->redirect(array('pm' => true, 'action' => 'displayRecords', $uId, $pId));
                 }
                 return $this->redirect(array('action' => 'displayRecords', $uId, $pId));
             } else {
                 $this->Flash->set(__('No se puedo crear la bitácora.'));
             }
         }
     }
 }
 function automaticAnnotation()
 {
     $this->Job = $this->Round->User->Job;
     $this->UsersRound = $this->Round->UsersRound;
     $this->User = $this->Round->User;
     $enableJavaActions = Configure::read('enableJavaActions');
     if ($this->request->is('post') && $enableJavaActions) {
         $user_id = $this->request->data['user_id'];
         $round_id = $this->request->data['round_id'];
         $group_id = $this->Session->read('group_id');
         if ($group_id > 1) {
             $user_id = $this->Session->read('user_id');
             $this->User->id = $user_id;
         }
         $this->Round->id = $this->request->data['round_id'];
         $userRound = $this->UsersRound->find('first', array('recursive' => -1, 'fields' => array('id', 'state'), 'conditions' => array('user_id' => $user_id, 'round_id' => $round_id)));
         if (empty($userRound)) {
             throw new NotFoundException(__('Invalid Round'));
         }
         $operation = $this->request->data['operation'];
         App::uses('CakeTime', 'Utility');
         $group_id = $this->Session->read('group_id');
         $isEnd = false;
         if ($group_id > 1) {
             $isEnd = CakeTime::isPast($this->Round->field('ends_in_date'));
         }
         //            $this->Job->find->hasAny(array('user_id'))
         if ($operation == -1) {
             $this->killJob($this->request->data['job_id']);
         } else {
             $programName = "Automatic_Dictionary_Annotation";
             if (!$isEnd && $userRound['UsersRound']['state'] == 0) {
                 $this->Job->create();
                 $data = array('user_id' => $user_id, 'round_id' => $round_id, 'percentage' => 0, '' => $programName, 'status' => 'Starting...');
                 if ($this->Job->save($data)) {
                     $id = $this->Job->id;
                     switch ($operation) {
                         // Kill process
                         case -1:
                             break;
                             // Anotacion en base a las anotaciones del usuario.
                         // Anotacion en base a las anotaciones del usuario.
                         case 1:
                             $operationId = 6;
                             $types = json_encode($this->request->data['types']);
                             if (!empty($types)) {
                                 $arguments = "{$operationId}\t{$id}\t{$user_id}\t{$round_id}\t{$types}";
                                 return $this->sendJob($id, $programName, $arguments);
                             } else {
                                 return $this->correctResponseJson(json_encode(array('success' => false, 'message' => "The task could not be performed successfully. Other operation is in progress. Please select at least one type")));
                             }
                             break;
                         case 2:
                             $operationId = 9;
                             App::uses('Folder', 'Utility');
                             $dictionary = new File($this->request->data['File']['tmp_name'], false, 0777);
                             if ($dictionary->exists()) {
                                 $path = Configure::read('uploadFolder');
                                 $newPath = $path . uniqid();
                                 $dictionary->copy($newPath);
                                 $project_id = $this->Round->field('project_id');
                                 $arguments = "{$operationId}\t{$id}\t{$user_id}\t{$round_id}\t{$project_id}\t{$newPath}";
                                 $this->sendJob($id, $programName, $arguments, false);
                                 if ($this->request->is("ajax")) {
                                     return $this->correctResponseJson(json_encode(array('success' => true)));
                                 } else {
                                     return $this->redirect(array('controller' => 'jobs', 'action' => 'index'));
                                 }
                                 break;
                             }
                     }
                 }
             }
             if ($this->request->is("ajax")) {
                 return $this->correctResponseJson(json_encode(array('success' => false, 'message' => "The task could not be performed successfully. ")));
             } else {
                 $this->Session->setFlash(__('The task could not be performed successfully'));
                 return $this->redirect(array('controller' => 'jobs', 'action' => 'index'));
             }
         }
     }
 }
 function uploadFinalPredictions()
 {
     $this->Cookie = $this->Components->load('Cookie');
     $this->Cookie->type('rijndael');
     //        $this->Cookie->time = '999 hours';
     if ($this->request->is(array('post', 'put'))) {
         //            debug($this->request->data);
         $email = $this->request->data['Participant']['email'];
         $code = $this->request->data['Participant']['code'];
         $task = $this->request->data['Participant']["task"];
         $run = $this->request->data['Participant']["run"];
         $maxUploadTask = Configure::read('max_participant_task_upload');
         $tasks = Configure::read('biocreative_tasks');
         $finalDate = Configure::read('final_date_to_upload_tasks');
         $startDate = Configure::read('initial_date_to_upload_tasks');
         if (!in_array($task, $tasks) && $run < 0 && $run > 5) {
             $this->Session->setFlash("Incorrect data");
             return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
         }
         App::uses('CakeTime', 'Utility');
         $isEnd = CakeTime::isPast($finalDate);
         $isFuture = CakeTime::isFuture($startDate);
         if ($isEnd || $isFuture) {
             $this->Session->setFlash("The final delivery date has expired");
             return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
         }
         $project_id = -1;
         if ($this->data['Participant']['remember_me'] && isset($code) && isset($email)) {
             $cookie = array();
             $cookie['email'] = $email;
             $cookie['code'] = $code;
             $this->Cookie->write('participantData', $cookie, true, '+2 weeks');
         } else {
             if ($this->Cookie->check('participantData')) {
                 $this->Cookie->destroy('participantData');
             }
         }
         App::uses('Folder', 'Utility');
         App::uses('File', 'Utility');
         //            debug($this->request->data);
         if ($this->request->data['Participant']['final_prediction']['size'] > 0) {
             /* ============================================= */
             /* ==============Load analysis=================== */
             /* ============================================= */
             if ($this->request->data['Participant']['final_prediction']['size'] > $this->filesize2bytes(Configure::read('max_file_size'))) {
                 $this->Session->setFlash("The file can not be more than " . Configure::read('max_file_size'));
                 return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
             }
             $file = $this->request->data['Participant']['final_prediction']['name'];
             if (pathinfo($file, PATHINFO_EXTENSION) != 'tsv') {
                 $this->Session->setFlash("The file must be in TSV format");
                 return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
             }
             $file = new File($this->request->data['Participant']['final_prediction']['tmp_name']);
             if ($file->readable()) {
                 $content = $file->read();
                 $file->close();
                 $lines = explode("\n", $content);
                 $incorrectFormat = empty($lines);
                 $count = 0;
                 $size = count($lines);
                 $correctColumns = 5;
                 if ($task == "CPD") {
                     $correctColumns = 4;
                 }
                 for ($index = 0; $index < $size; $index++) {
                     if (strlen(trim($lines[$index])) > 0) {
                         if (!$incorrectFormat) {
                             $columns = explode("\t", $lines[$index]);
                             for ($i = 0; $i < count($columns); $i++) {
                                 if (strlen(trim($columns[$i])) == 0) {
                                     $incorrectFormat = true;
                                 }
                             }
                             $incorrectFormat = $incorrectFormat || sizeof($columns) != $correctColumns;
                             $count++;
                         } else {
                             break;
                         }
                     }
                 }
                 //                    $correctFormat = $this->correctTsvFormat($file, 5);
                 if ($incorrectFormat) {
                     //                        $count=$this->incorrecLineTsvFormat($file);
                     if ($task == "CPD") {
                         $this->Session->setFlash("Incorrect content file. Line {$count} is incorrect. " . "Content file must be contain 4 columns");
                     } else {
                         $this->Session->setFlash("Incorrect content file. Line {$count} is incorrect. " . "Content file must be in this format WO2009026621A1->A:12:24->1->0.99->paliperidone");
                     }
                     return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
                 }
                 $participant = $this->Participant->find('first', array("recursive" => -1, "fields" => array("id", "team_id"), "conditions" => array('Participant.email' => $email, 'Participant.code' => $code)));
                 $participantID = $participant["Participant"]["id"];
                 $team_id = $participant["Participant"]["team_id"];
                 $this->request->data['Participant']['id'] = $participantID;
                 $this->participantSaveConnection($this->request->data['Participant'], "uploadTeamPrediction");
                 $path = Configure::read('participantsPath');
                 $path = $path . DS . $task . DS . $team_id;
                 $dir = new Folder($path, true, 0755);
                 $tempPath = $this->request->data['Participant']['final_prediction']['tmp_name'];
                 $file = new File($tempPath);
                 if ($file->readable()) {
                     $content = $file->read();
                     $newPath = $dir->pwd() . DS . "{$run}.tsv";
                     $file->copy($newPath);
                     $path = $newPath;
                     chmod($newPath, 0200);
                     $data = array('participant_id' => $participantID, 'biocreative_task' => $task, 'run' => $run);
                     $finalfile = $this->Participant->FinalPrediction->find('first', array("conditions" => $data, 'fields' => 'id'));
                     if (!empty($finalfile)) {
                         $this->Participant->FinalPrediction->id = $finalfile['FinalPrediction']['id'];
                         $this->Session->setFlash("The file has been updated successfully", "success");
                         $type = "updated";
                     } else {
                         $this->Participant->FinalPrediction->create();
                         $this->Session->setFlash("The file has been created successfully", "success");
                         $type = "uploaded";
                     }
                     $data = array('participant_id' => $participantID, 'run' => $run, 'email' => $email, 'biocreative_task' => $task, 'file' => $content, 'file_name' => $this->request->data['Participant']['final_prediction']['name']);
                     if (!$this->Participant->FinalPrediction->save($data)) {
                         $this->Session->setFlash("File could not be saved");
                         return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
                     } else {
                         $this->sendMailWithAttachment("finalPredictionSuccess", $email, "[MARKYT - BIOCREATIVE V (CHEMDNER)] Final submision", array("run" => $run, "type" => $type, "task" => $task), array("{$run}.tsv" => $tempPath));
                     }
                     return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
                 }
             } else {
                 throw new Exception("Ops! file could not be readed");
             }
         } else {
             $this->Session->setFlash("One team prediction file is needed");
             return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis'));
         }
     }
 }