Exemple #1
0
 public function afterFind($results, $primary = false)
 {
     Configure::write('debug', 2);
     App::uses("CakeTime", "Utility");
     $gc = new CakeTime();
     parent::afterFind($results, $primary);
     if (isset($results[0]['Order']['timestamp'])) {
         foreach ($results as $key => $val) {
             $results[$key]['Order']['created'] = $gc->timeAgoInWords($results[$key]['Order']['timestamp']);
         }
     }
     return $results;
 }
 /**
  * Relatórios
  */
 public function index()
 {
     // Carrega o model Schedules
     $this->loadModel('Schedule');
     // Se a requisição é do tipo post
     if ($this->request->is('post')) {
         $this->layout = "print";
         $this->set('orientation', 'landscape');
         // Opções de busca
         $options = array('conditions' => array('Schedule.created >' => CakeTime::format($this->request->data['Reports']['start'], "%Y-%m-%d %H:%M"), 'Schedule.created <' => CakeTime::format($this->request->data['Reports']['end'], "%Y-%m-%d %H:%M")), 'order' => array('Patient.name' => 'asc', 'Schedule.created' => 'asc'));
         //debuga options
         $this->set(compact('options'));
         // Resultados de busca
         $schedules = $this->Schedule->find('all', $options);
         // Compacta para view
         $this->set(compact('schedules'));
         $this->render('results');
         $this->generated_pdf("relatorio_consolidado_");
     } else {
         $this->set('orientation', 'landscape');
         //$this->layout = "print";
         // Faz uma busca e compacta todas as requisições cadastradas
         $schedules = $this->Schedule->find('all', array('order' => array('Patient.name' => 'asc', 'Schedule.created' => 'asc')));
         $this->set(compact('schedules'));
         //$this->render('results');
         //$this->generated_pdf("relatorio_teste");
     }
 }
 public function getByComponente()
 {
     $this->layout = "ajax";
     $incidencias = $this->Incidencia->Componente->find("first", array("contain" => array("Incidencia" => array("conditions" => array("Incidencia.estado" => 1, "Incidencia.fecha between ? and ?" => array(CakeTime::format($this->request->data["Componente"]["fechaInicio"], "%Y-%m-%d"), CakeTime::format($this->request->data["Componente"]["fechaFin"], "%Y-%m-%d")))), "Incidencia.Cruce"), "conditions" => array("Componente.idComponente" => $this->request->data["Componente"]["idComponente"])));
     $incidencias = $incidencias["Incidencia"];
     $this->set("incidencias", $incidencias);
 }
 /**
  * HtmlExtHelperTest::testTime()
  *
  * @return void
  */
 public function testTime()
 {
     $time = time();
     $is = $this->Html->time($time);
     $time = CakeTime::i18nFormat($time, '%Y-%m-%d %T');
     $expected = '<time datetime="' . $time . '">' . $time . '</time>';
     $this->assertEquals($expected, $is);
 }
 public function afterFind($results, $primary = false)
 {
     App::uses('CakeTime', 'Utility');
     foreach ($results as &$result) {
         if (isset($result[$this->alias]['modified'])) {
             $result[$this->alias]['niceday'] = CakeTime::niceShort($result[$this->alias]['modified']);
         }
     }
     return $results;
 }
Exemple #6
0
 public function timeAgo($timestamp)
 {
     $timeAgo = CakeTime::timeAgoInWords($timestamp, array('accuracy' => array('hour' => 'hour'), 'end' => '1 year'));
     $timeAgo = trim(str_replace('ago', '', str_replace('second', 'seconde', str_replace('hour', 'heure', str_replace('day', 'jour', str_replace('week', 'semaine', str_replace('month', 'mois', $timeAgo)))))));
     if ($timeAgo == 'just now') {
         $timeAgo = 'il y a quelques secondes';
     } else {
         $timeAgo = 'il y a ' . $timeAgo;
     }
     return $timeAgo;
 }
Exemple #7
0
 /**
  * getHolidayInYear
  * 指定された年の祝日日付を返す
  * getHolidayのラッパー関数 YYYYに年始まりの日付と最終日付を付与してgetHolidayを呼び出す
  *
  * @param string $year 指定年(西暦)‘YYYY’ 形式の文字列
  * @return array期間内のholidayテーブルのデータ配列が返る
  */
 public function getHolidayInYear($year = null)
 {
     // $yearがnullの場合は現在年
     if ($year === null) {
         // 未設定時は現在年
         $year = CakeTime::format((new NetCommonsTime())->getNowDatetime(), '%Y');
     }
     $from = $year . '-01-01';
     $to = $year . '-12-31';
     $holidays = $this->getHoliday($from, $to);
     return $holidays;
 }
 /**
  * Used for GMT offset for a timezone
  * @param string $timezone: timezone name
  * @return string GMT offset for the given timezone
  * @author Laxmi Saini
  */
 function getTimezoneOffset($timezone = null)
 {
     if ($timezone != '') {
         $dateTimeObj = new DateTime();
         $date_time_zone = CakeTime::timezone($timezone);
         $dateTimeObj->setTimeZone($date_time_zone);
         $offset = $dateTimeObj->getOffset();
         return $this->formatGmtOffset($offset);
     } else {
         return "";
     }
 }
Exemple #9
0
 /**
  * Calculates the current age of someone born on $birthdate.
  * Source: stackoverflow.com/questions/3776682/php-calculate-age
  * @param sing $birthdate The birthdate.
  * @return integer The calculated age.
  * @access public
  * @static
  */
 public static function ageFromBirthdate($birthdate)
 {
     // convert to format: YYYY-MM-DD
     $clean_birthdate = date('Y-m-d', CakeTime::fromString($birthdate));
     if (CakeTime::isFuture($clean_birthdate)) {
         throw new OutOfRangeException("Birthdate is in the future: {$clean_birthdate}", BedrockTime::EXCEPTION_CODE_FUTURE_BIRTHDATE);
     }
     //explode the date to get month, day and year
     $parts = explode('-', $clean_birthdate);
     //get age from date or birthdate
     $age = intval(date('md', date('U', mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]))) > date('md') ? date('Y') - $parts[0] - 1 : date('Y') - $parts[0]);
     return $age;
 }
 public function isTokenValid($token)
 {
     $tokenAuth = $this->find('first', array('conditions' => array('Token.token' => $token)));
     if ($tokenAuth) {
         $expiryDate = $tokenAuth['Token']['token_expiry_date'];
         if (CakeTime::gmt($expiryDate) < CakeTime::gmt()) {
             return false;
         } else {
             return $tokenAuth['Token'];
         }
     } else {
         return false;
     }
 }
 /**
  * index method
  *
  * @return void
  */
 public function index()
 {
     $targetYear = null;
     // 指定年取り出し
     if (isset($this->params['named']['targetYear'])) {
         $targetYear = $this->params['named']['targetYear'];
     } else {
         $targetYear = CakeTime::format((new NetCommonsTime())->getNowDatetime(), '%Y');
     }
     // 祝日設定リスト取り出し
     $holidays = $this->Holiday->getHolidayInYear($targetYear);
     // View変数設定
     $this->set('holidays', $holidays);
     $this->set('targetYear', $targetYear);
 }
 /**
  * Auth Login page
  */
 public function admin_login()
 {
     if (Configure::read('Backend.Auth.enabled') !== true) {
         if (isset($this->Auth)) {
             $this->redirect($this->Auth->loginAction);
         } else {
             $this->redirect('/');
         }
     }
     $this->layout = "Backend.auth";
     $defaultRedirect = Configure::read('Backend.Dashboard.url') ? Configure::read('Backend.Dashboard.url') : array('plugin' => 'backend', 'controller' => 'backend', 'action' => 'dashboard');
     $redirect = false;
     if ($this->request->is('post')) {
         if (!$this->Auth->login()) {
             //Event Backend.Auth.onLoginFail
             $eventData = array('user' => $this->request->data['BackendUser'], 'ip' => $this->request->clientIp());
             // $event = new CakeEvent('Backend.Controller.Auth.onLoginFail', $this, $eventData);
             // $this->getEventManager()->dispatch($event);
             $this->Session->setFlash(__d('backend', 'Login failed'), 'error', array(), 'auth');
         } else {
             //Event Backend.Auth.onLogin
             $event = new CakeEvent('Backend.Controller.Auth.onLogin', $this, $this->Auth->user());
             //$this->getEventManager()->dispatch($event);
             $this->Session->setFlash(__d('backend', 'Login successful'), 'success');
             if ($this->Auth->user('lastlogin')) {
                 $this->Session->setFlash(__d('backend', 'Last login: %s', CakeTime::timeAgoInWords($this->Auth->user('last_login'))), 'default', array(), 'auth');
             }
             //TODO should the event result return an redirect url?
             if ($event->result) {
                 $redirect = $event->result;
             } else {
                 $redirect = $this->Auth->redirect();
             }
             $redirect = Router::normalize($redirect);
             if ($redirect == '/' || !preg_match('/^\\/admin\\//', $redirect) || $redirect == '/admin/backend') {
                 $redirect = $defaultRedirect;
             }
             $this->redirect($redirect);
         }
     } elseif ($this->Auth->user()) {
         $redirect = $this->referer($defaultRedirect, true);
         $this->redirect($redirect);
     }
     $this->set(compact('redirect'));
 }
 /**
  * Loop through active controllers and generate sitemap data.
  */
 public function index()
 {
     $controllers = App::objects('Controller');
     $sitemap = array();
     // Fetch sitemap data
     foreach ($controllers as $controller) {
         App::uses($controller, 'Controller');
         // Don't load AppController's, SitemapController or Controller's who can't be found
         if (strpos($controller, 'AppController') !== false || $controller === 'SitemapController' || !App::load($controller)) {
             continue;
         }
         $instance = new $controller($this->request, $this->response);
         $instance->constructClasses();
         if (method_exists($instance, '_generateSitemap')) {
             if ($data = $instance->_generateSitemap()) {
                 $sitemap = array_merge($sitemap, $data);
             }
         }
     }
     // Cleanup sitemap
     if ($sitemap) {
         foreach ($sitemap as &$item) {
             if (is_array($item['loc'])) {
                 if (!isset($item['loc']['plugin'])) {
                     $item['loc']['plugin'] = false;
                 }
                 $item['loc'] = h(Router::url($item['loc'], true));
             }
             if (array_key_exists('lastmod', $item)) {
                 if (!$item['lastmod']) {
                     unset($item['lastmod']);
                 } else {
                     $item['lastmod'] = CakeTime::format(DateTime::W3C, $item['lastmod']);
                 }
             }
         }
     }
     // Disable direct linking
     if (empty($this->request->params['ext'])) {
         throw new NotFoundException();
     }
     // Render view and don't use specific view engines
     $this->RequestHandler->respondAs($this->request->params['ext']);
     $this->set('sitemap', $sitemap);
 }
 /**
  * index method
  *
  * @return void
  */
 public function follow_expedient($idE = null)
 {
     App::uses('CakeTime', 'Utility');
     $confirmas = $this->Confirma->Expediente->find('all', array('conditions' => array('Expediente.user_id' => $idE)));
     if (isset($confirmas[0]['Expediente']['previsao_chegada']) && !empty($confirmas[0]['Expediente']['previsao_chegada'])) {
         if (CakeTime::isToday($confirmas[0]['Expediente']['previsao_chegada'])) {
             /* greet user with a happy birthday message
                  Enviar um email alertando sobre a data quase vencida.
                */
             $vence_hoje = 'Chega Hoje';
             if (isset($vence_hoje) && empty($vence_hoje)) {
                 $vence_hoje = '';
             }
             $this->set('vence_hoje', $vence_hoje);
         }
     }
     $this->set(compact('confirmas', 'idE'));
 }
 public function register()
 {
     if (empty($this->request->data)) {
         $queryString = '?' . http_build_query($this->request->query);
         $this->set(compact('queryString'));
     } else {
         $this->request->data['Token']['password'] = Security::hash($this->request->data['Token']['password'], 'md5');
         $this->request->data['Token']['token'] = Security::hash($this->request->data['Token']['email'], 'md5');
         $this->request->data['Token']['type'] = 'application';
         $this->request->data['Token']['token_expiry_date'] = CakeTime::format('+365 days', '%Y-%m-%d');
         $this->Token->save($this->request->data);
         $bearerTokenReceivingUrl = urldecode($this->request->query['client_bearer_token_receiving_url']);
         unset($this->request->query['client_bearer_token_receiving_url']);
         $this->request->query['bearer_token'] = $this->request->data['Token']['token'];
         $this->request->query['login_type'] = 'application';
         return $this->redirect($bearerTokenReceivingUrl . '?' . http_build_query($this->request->query));
     }
 }
Exemple #16
0
 public function formatDateFields($results, $dates, $format = "%d/%m/%Y")
 {
     if (!empty($dates)) {
         $setResult = function ($val, $key) use(&$results, $format) {
             $innerKey = explode("/", $key);
             $results[$innerKey[0]][$innerKey[1]][$innerKey[2]] = CakeTime::format($val, $format);
         };
         $extracted = Set::extract($results, "/{$this->alias}");
         $dateExtracted = Set::classicExtract($extracted, '{\\w+}.{\\w+}.{' . implode("|", $dates) . '}');
         $applied = Set::apply("/", $dateExtracted, function ($val) {
             return count(Set::filter($val)) > 0 ? $val : null;
         });
         if ($applied) {
             $flatten = Set::flatten($applied, "/");
             array_walk($flatten, $setResult);
         }
     }
     return $results;
 }
Exemple #17
0
 public function updateInfo($attrs)
 {
     $this->create();
     if (!empty($attrs['book_id'])) {
         $this->set('book_id', $attrs['book_id']);
         $book = $this->Book->find('first', array('conditions' => array('Book.id' => $attrs['book_id'])));
     }
     if (!empty($attrs['user_id'])) {
         $this->set('user_id', $attrs['user_id']);
     }
     if ($attrs['event'] == 'bet_start') {
         $content = '[Bet Now!] ' . $book['Book']['title'] . ' | Bet start time:' . CakeTime::format($book['Book']['bet_start'], '%Y/%m/%d %H:%M') . ' , The bet has started!';
     } elseif ($attrs['event'] == 'bet_result') {
         $content = '[Result Announcement!] ' . $book['Book']['title'] . ' | Announcement time:' . CakeTime::format($book['Book']['modified'], '%Y/%m/%d %H:%M') . ' ,  The results have been announced!';
     }
     $this->set('content', $content);
     $this->set('event', $attrs['event']);
     $this->save();
 }
 function admin_genericos()
 {
     // $keypass = $this->Auth->user('empresa_id')*2313231323132313;
     // $login = array(
     //     'acesso' => 1,
     //     'empresa_id' => $this->Auth->user('empresa_id'),
     //     'post_keypass' => 'BL'.$keypass.'AC'
     // );
     $this->autoRender = false;
     $model = 'Conteudo';
     $this->set('model', $model);
     $keypass = $this->params->query['keypass'];
     $empresa_id = substr($keypass, 2, -2);
     $empresa_id = $empresa_id / 2313231323132313;
     $sql = "SELECT c.*, e.empresa_id FROM tb_conteudo as c JOIN tb_conteudo_empresas as e ON c.id = e.conteudo_id WHERE e.empresa_id = {$empresa_id}";
     $all = $this->{$model}->query($sql);
     $json_rdy["conteudos"] = array();
     foreach ($all as $content) {
         $created = CakeTime::format('%d | %e de %B', $content['c']['created']);
         $json_rdy["conteudos"] = array("id" => $content['c']['id'], "categoria_id" => $content['c']['categoria_id'], "titulo" => $content['c']['titulo'], "texto" => $content['c']['texto'], "created" => $created);
     }
     echo "<pre>";
     print_r($json_rdy);
 }
Exemple #19
0
 /**
  * checkPastDate
  * Custom Validation Rule: Ensures a selected date is either the
  * present day or in the past.
  *
  * @param array $check Contains the value passed from the view to be validated
  * @return bool True if in the past or today, False otherwise
  */
 public function checkPastDate($check)
 {
     $value = array_values($check);
     return CakeTime::fromString($value[0]) <= CakeTime::fromString(date(Configure::read('databaseDateFormat')));
 }
 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;
 }
 /**
  * checkFutureDate
  * Custom Validation Rule: Ensures a selected date is either the
  * present day or in the future.
  *
  * @param array $check Contains the value passed from the view to be validated
  * @return bool True if in the past or today, False otherwise
  */
 public function checkFutureDate($check)
 {
     $value = array_values($check);
     return CakeTime::fromString($this->data[$this->alias]['document_date']) <= CakeTime::fromString($value[0]);
 }
 public function pm_selectEmployee($idP, $idU, $idC)
 {
     if ($this->request->is('post') && !empty($this->request->data)) {
         $this->Project->Work->create();
         if ($this->Project->Work->save(array('user_id' => $idU, 'client_id' => $idC, 'project_id' => $idP, 'rol' => $this->request->data['Rol']['rol']))) {
             $this->Project->save(array('id' => $idP, 'confirmed' => true));
             //Se crea y salva la bitácora del empleado
             $this->Project->Record->create();
             $this->Project->Record->save(array('fecha_inicio' => CakeTime::format(time(), '%y-%m-%d'), 'fecha_fin' => CakeTime::format('+7 days', '%y-%m-%d'), 'project_id' => $idP, 'user_id' => $idU));
             $this->Flash->success('Empleado ' . $idU . ' seleccionado para desarrollo');
             $this->redirect(array('pm' => true, 'controller' => 'users', 'action' => 'displayEmployees', $idP, $idC));
         } else {
             $this->Flash->set(__('Debe seleccionar un empleado'));
             $this->redirect(array('pm' => true, 'controller' => 'users', 'action' => 'displayEmployees', $idP, $idC));
         }
     }
 }
 /**
  * Tests that using CakeTime::format() with the correct sytax actually converts
  * from one timezone to the other correctly
  *
  * @return void
  */
 public function testCorrectTimezoneConversion()
 {
     date_default_timezone_set('UTC');
     $date = '2012-01-01 10:00:00';
     $converted = CakeTime::format($date, '%Y-%m-%d %H:%M', '', 'Europe/Copenhagen');
     $expected = new DateTime($date);
     $expected->setTimezone(new DateTimeZone('Europe/Copenhagen'));
     $this->assertEquals($expected->format('Y-m-d H:i'), $converted);
 }
Exemple #24
0
 /**
  * Outputs Date(time) Sting nicely formatted (+ localized!)
  *
  * Options:
  * - timezone: User's timezone
  * - default: Default string (defaults to "-----")
  * - oclock: Set to true to append oclock string
  *
  * @param string $dateString,
  * @param string $format Format (YYYY-MM-DD, DD.MM.YYYY)
  * @param array $options @return string
  * @return string
  */
 public static function localDate($dateString = null, $format = null, $options = [])
 {
     $defaults = ['default' => '-----', 'timezone' => null];
     $options += $defaults;
     if ($options['timezone'] === null && strlen($dateString) === 10) {
         $options['timezone'] = date_default_timezone_get();
     }
     if ($dateString === null) {
         $dateString = time();
     }
     $date = static::fromString($dateString, $options['timezone']);
     if ($date === null || $date === false || $date <= 0) {
         return $options['default'];
     }
     if ($format === null) {
         if (is_int($dateString) || strpos($dateString, ' ') !== false) {
             $format = FORMAT_LOCAL_YMDHM;
         } else {
             $format = FORMAT_LOCAL_YMD;
         }
     }
     $date = parent::_strftime($format, $date);
     if (!empty($options['oclock'])) {
         switch ($format) {
             case FORMAT_LOCAL_YMDHM:
             case FORMAT_LOCAL_YMDHMS:
             case FORMAT_LOCAL_YMDHM:
             case FORMAT_LOCAL_HM:
             case FORMAT_LOCAL_HMS:
                 $date .= ' ' . __d('tools', 'o\'clock');
                 break;
         }
     }
     return $date;
 }
 public function updateEvent()
 {
     $this->loadModel('UserEvent');
     $this->loadModel('Group');
     $this->loadModel('UserEventShare');
     try {
         $event = array();
         $owner = true;
         $origEvent = null;
         $id = $this->request->data('UserEvent.id');
         if ($id) {
             $origEvent = $this->UserEvent->findById($id);
         }
         if (!in_array($this->request->data('UserEvent.type'), array('pay', 'purchase'))) {
             $event = array('title' => $this->request->data('UserEvent.title'), 'descr' => $this->request->data('UserEvent.descr'), 'object_type' => $this->request->data('UserEvent.object_type'), 'object_id' => $this->request->data('UserEvent.object_id'), 'type' => $this->request->data('UserEvent.type'), 'recipient_id' => $this->request->data('UserEvent.recipient_id'), 'shared' => isset($this->request->data['UserEvent']['shared']) ? '1' : '0', 'is_delayed' => $this->request->data('UserEvent.is_delayed'), 'price' => $this->request->data('UserEvent.price'));
             if ($this->request->data('UserEvent.type') == 'task') {
                 if (empty($this->request->data('UserEvent.event_category_id'))) {
                     $event_category_id = 1;
                 } else {
                     $event_category_id = $this->request->data('UserEvent.event_category_id');
                 }
                 $event['event_category_id'] = $event_category_id;
                 if (!empty($this->request->data('UserEvent.external'))) {
                     $event['external'] = $this->request->data('UserEvent.external');
                     $group = null;
                     if (!empty($this->request->data('UserEvent.object_type')) && $this->request->data('UserEvent.object_type') == 'group') {
                         $group = $this->Group->find('first', array('conditions' => array(array('Group.id' => $this->request->data('UserEvent.object_id')))));
                     }
                     if (!empty($this->request->data('UserEvent.recipient_id')) || !empty($group) && $group['Group']['active_members'] > 1) {
                         $cur_time = date("Y-m-d H:i:s");
                         if (Configure::read('debug') > 0) {
                             $duration = '+2 minutes';
                         } else {
                             $duration = '+12 hours';
                         }
                         $external_time = date('Y-m-d H:i:s', strtotime($duration, strtotime($cur_time)));
                         $event['external_time'] = $external_time;
                     }
                 }
             }
         } else {
             $this->loadModel('FinanceOperation');
             $event = array('title' => $this->request->data('UserEvent.title'), 'descr' => $this->request->data('UserEvent.descr'), 'object_type' => $this->request->data('UserEvent.object_type'), 'object_id' => $this->request->data('UserEvent.object_id'), 'type' => $this->request->data('UserEvent.type'), 'recipient_id' => '', 'shared' => '1', 'is_delayed' => $this->request->data('UserEvent.is_delayed'));
             $financeData = array('FinanceOperation' => array('type' => 1, 'account_id' => $this->request->data('UserEvent.finance_account'), 'project_id' => $this->request->data('UserEvent.finance_project'), 'amount' => $this->request->data('UserEvent.amount'), 'comment' => 'created from event data'), 'FinanceOperationHasCategory' => array('category_id' => $this->request->data('UserEvent.finance_category')));
             if ($origEvent && $origEvent['UserEvent']['finance_operation_id']) {
                 $financeData['FinanceOperation']['id'] = $origEvent['UserEvent']['finance_operation_id'];
                 $operationId = $this->FinanceOperation->editOperation($financeData);
                 $event['finance_operation_id'] = $operationId;
             } else {
                 $operationId = $this->FinanceOperation->addOperation($financeData);
                 $event['finance_operation_id'] = $operationId;
             }
         }
         if ($id) {
             $event['id'] = $id;
             $event['user_id'] = $origEvent['UserEvent']['user_id'];
             $oldRecipients = explode(',', $origEvent['UserEvent']['recipient_id']);
             if ($this->currUserID != $origEvent['UserEvent']['user_id'] && in_array($this->currUserID, $oldRecipients)) {
                 $event['title'] = $origEvent['UserEvent']['title'];
                 $event['descr'] = $origEvent['UserEvent']['descr'];
                 $event['object_type'] = $origEvent['UserEvent']['object_type'];
                 $event['object_id'] = $origEvent['UserEvent']['object_id'];
                 $event['type'] = $origEvent['UserEvent']['type'];
                 $event['recipient_id'] = $origEvent['UserEvent']['recipient_id'];
                 $event['shared'] = $origEvent['UserEvent']['shared'];
                 $owner = false;
             } else {
                 if ($this->currUserID == $origEvent['UserEvent']['user_id']) {
                     $owner = true;
                 } else {
                     throw new Exception(__('Access denied'));
                 }
             }
             $event['previous_event_time'] = $origEvent['UserEvent']['event_time'];
         } else {
             $event['user_id'] = $this->currUserID;
         }
         //Если событие моё - даю редактировать место
         if (strlen($this->request->data('UserEvent.place_name')) >= 3 && strlen($this->request->data('UserEvent.place_coords')) >= 5) {
             $event['place_name'] = $this->request->data('UserEvent.place_name');
             $event['place_coords'] = $this->request->data('UserEvent.place_coords');
         }
         //назначение категории исходя из типа события либо исходя из схожего события (одинаковое название и создатель)
         $conditions = array('UserEvent.user_id' => $event['user_id'], 'UserEvent.title' => $event['title']);
         if ($id) {
             $conditions[] = array('UserEvent.id <> ?' => $event['id']);
         }
         $sameTitledEvent = $this->UserEvent->find('first', compact('conditions'));
         if ($sameTitledEvent) {
             $event['category'] = $sameTitledEvent['UserEvent']['category'];
         } else {
             $event['category'] = in_array($event['type'], array('sport', 'none'));
         }
         $y1 = $this->request->data('UserEvent.yearStart');
         $m1 = $this->request->data('UserEvent.monthStart');
         $d1 = $this->request->data('UserEvent.dayStart');
         $h1 = $this->request->data('UserEvent.timeStart');
         $min1 = $this->request->data('UserEvent.minuteStart');
         $event['event_time'] = $y1 . '-' . $m1 . '-' . $d1 . ' ' . $h1 . ':' . $min1;
         $time = new DateTime($event['event_time']);
         $time->add(new DateInterval('PT' . $this->request->data('UserEvent.duration') . 'M'));
         $event['event_end_time'] = $time->format('Y-m-d H:i:s');
         if (in_array($this->request->data('UserEvent.type'), array('pay', 'purchase'))) {
             $event['event_end_time'] = $event['event_time'];
             $event['place_name'] = null;
             $event['place_coords'] = null;
         }
         $this->UserEvent->save($event);
         if (strpos($event['recipient_id'], ',') !== false) {
             $aRecipients = explode(',', $event['recipient_id']);
         } else {
             if (strlen($event['recipient_id']) > 0) {
                 $aRecipients[] = $event['recipient_id'];
             }
         }
         $aRecipients[] = $this->currUserID;
         if ($owner) {
             if (!$id) {
                 foreach ($aRecipients as $uID) {
                     $acceptance = $uID == $this->currUserID ? '1' : '0';
                     $ueShare = array('user_id' => $uID, 'user_event_id' => $this->UserEvent->id, 'acceptance' => $acceptance);
                     $this->UserEventShare->save($ueShare);
                     $this->UserEventShare->clear();
                 }
             } else {
                 $aAcceptances = $this->UserEventShare->findAllByUserEventId($id);
                 foreach ($aAcceptances as $acceptance) {
                     $this->UserEventShare->delete($acceptance['UserEventShare']['id']);
                 }
                 foreach ($aRecipients as $uID) {
                     $acceptance = $uID == $this->currUserID ? 1 : 0;
                     $ueShare = array('user_id' => $uID, 'user_event_id' => $this->UserEvent->id, 'acceptance' => $acceptance);
                     $this->UserEventShare->save($ueShare);
                     $this->UserEventShare->clear();
                 }
             }
         } else {
             $aAcceptances = $this->UserEventShare->findAllByUserEventId($id);
             foreach ($aAcceptances as $key => $acceptance) {
                 $acceptance['UserEventShare']['acceptance'] = $acceptance['UserEventShare']['user_id'] == $this->currUserID ? '1' : '0';
                 $this->UserEventShare->save($acceptance['UserEventShare']);
                 $this->UserEventShare->clear();
             }
         }
         $data = $this->User->getTimeline($this->currUserID, $event['event_time'], $event['event_end_time']);
         $data['event'] = $this->UserEvent->findById($this->UserEvent->id);
         App::uses('CakeTime', 'Utility');
         if (empty($this->request->data['UserEvent']['recipient_id']) && !empty($this->request->data['UserEvent']['new_user'])) {
             $this->loadModel('Invitation');
             $invitation = ['object_id' => $data['event']['UserEvent']['id'], 'object_type' => Invitation::USER_EVENT, 'email' => $this->request->data['UserEvent']['new_user']];
             $this->Invitation->set($invitation);
             $this->Invitation->save();
             $Email = new CakeEmail('smtp');
             $Email->template('reg_invitation', 'mail')->to($this->request->data('UserEvent.new_user'))->viewVars(array('eventId' => $data['event']['UserEvent']['id'], 'eventType' => $this->request->data['UserEvent']['type'], 'eventTitle' => $this->request->data['UserEvent']['title'], 'creator_id' => $this->currUserID, 'date' => CakeTime::format($data['event']['UserEvent']['event_time'], '%B %e, %Y'), 'start_time' => CakeTime::format($data['event']['UserEvent']['event_time'], '%H:%M %p'), 'end_time' => CakeTime::format($data['event']['UserEvent']['event_end_time'], '%H:%M %p')))->subject('Invitation to join Konstruktor.com')->send();
         }
         $this->setResponse($data);
     } catch (Exception $e) {
         $this->setError($e->getMessage());
     }
 }
Exemple #26
0
 /**
  * testListTimezones
  *
  * @return void
  */
 public function testListTimezones()
 {
     $return = CakeTime::listTimezones();
     $this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
     $this->assertEquals('Bangkok', $return['Asia']['Asia/Bangkok']);
     $this->assertTrue(isset($return['America']['America/Argentina/Buenos_Aires']));
     $this->assertEquals('Argentina/Buenos_Aires', $return['America']['America/Argentina/Buenos_Aires']);
     $this->assertTrue(isset($return['UTC']['UTC']));
     $this->assertFalse(isset($return['Cuba']));
     $this->assertFalse(isset($return['US']));
     $return = CakeTime::listTimezones('#^Asia/#');
     $this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
     $this->assertFalse(isset($return['Pacific']));
     $return = CakeTime::listTimezones('#^(America|Pacific)/#', null, false);
     $this->assertTrue(isset($return['America/Argentina/Buenos_Aires']));
     $this->assertTrue(isset($return['Pacific/Tahiti']));
     if (!$this->skipIf(version_compare(PHP_VERSION, '5.3.0', '<'))) {
         $return = CakeTime::listTimezones(DateTimeZone::ASIA);
         $this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
         $this->assertFalse(isset($return['Pacific']));
         $return = CakeTime::listTimezones(DateTimeZone::PER_COUNTRY, 'US', false);
         $this->assertTrue(isset($return['Pacific/Honolulu']));
         $this->assertFalse(isset($return['Asia/Bangkok']));
     }
 }
Exemple #27
0
 /**
  * Converts a string representing the format for the function strftime and returns a
  * windows safe and i18n aware format.
  *
  * @param string $format Format with specifiers for strftime function.
  *    Accepts the special specifier %S which mimics the modifier S for date()
  * @param string $time UNIX timestamp
  * @return string windows safe and date() function compatible format for strftime
  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  */
 public static function convertSpecifiers($format, $time = null)
 {
     if (!$time) {
         $time = time();
     }
     self::$_time = $time;
     return preg_replace_callback('/\\%(\\w+)/', array('CakeTime', '_translateSpecifier'), $format);
 }
 protected function _validate()
 {
     $now = time();
     $data = $this->request->data;
     $this->Provider->isOK = false;
     // Check consumer key
     if (empty($data['oauth_consumer_key'])) {
         return $this->Provider->reason = 'Missing consumer key.';
     }
     // Check all required launch parameters
     if (empty($data['lti_message_type']) or !array_key_exists($data['lti_message_type'], $this->Provider->messageTypes)) {
         return $this->Provider->reason = 'Invalid or missing lti_message_type parameter.';
     }
     if (empty($data['lti_version']) or !in_array($data['lti_version'], $this->Provider->LTI_VERSIONS)) {
         return $this->Provider->reason = 'Invalid or missing lti_version parameter.';
     }
     switch ($data['lti_message_type']) {
         case 'ContentItemSelectionRequest':
             if (empty($data['content_item_return_url']) or !(strlen(trim($data['content_item_return_url'])) > 0)) {
                 return $this->Provider->reason = 'Missing content_item_return_url parameter.';
             }
             if (!empty($data['accept_media_types']) and strlen(trim($data['accept_media_types'])) > 0) {
                 $mediaTypes = array_filter(explode(',', str_replace(' ', '', $data['accept_media_types'])), 'strlen');
                 $mediaTypes = array_unique($mediaTypes);
             }
             if (empty($mediaTypes)) {
                 return $this->Provider->reason = 'No accept_media_types found.';
             }
             $this->Provider->mediaTypes = $mediaTypes;
             if (!empty($data['accept_presentation_document_targets']) and strlen(trim($data['accept_presentation_document_targets'])) > 0) {
                 $documentTargets = array_filter(explode(',', str_replace(' ', '', $data['accept_presentation_document_targets'])), 'strlen');
                 $documentTargets = array_unique($documentTargets);
             }
             if (empty($documentTargets)) {
                 return $this->Provider->reason = 'Missing or empty accept_presentation_document_targets parameter.';
             }
             foreach ($documentTargets as $documentTarget) {
                 if (!in_array($documentTarget, ['embed', 'frame', 'iframe', 'window', 'popup', 'overlay', 'none'])) {
                     return $this->Provider->reason = 'Invalid value in accept_presentation_document_targets parameter: ' . $documentTarget;
                 }
             }
             $this->Provider->documentTargets = $documentTargets;
             if (!empty($data['accept_unsigned']) and !in_array($data['accept_unsigned'], ['true', 'false'])) {
                 return $this->Provider->reason = 'Invalid value for accept_unsigned parameter: ' . $data['accept_unsigned'];
             }
             if (!empty($data['accept_multiple']) and !in_array($data['accept_multiple'], ['true', 'false'])) {
                 return $this->Provider->reason = 'Invalid value for accept_multiple parameter: ' . $data['accept_multiple'];
             }
             if (!empty($data['accept_copy_advice']) and !in_array($data['accept_copy_advice'], ['true', 'false'])) {
                 return $this->Provider->reason = 'Invalid value for accept_copy_advice parameter: ' . $data['accept_copy_advice'];
             }
             if (!empty($data['auto_create']) and !in_array($data['auto_create'], ['true', 'false'])) {
                 return $this->Provider->reason = 'Invalid value for auto_create parameter: ' . $data['auto_create'];
             }
             if (!empty($data['can_confirm']) and !in_array($data['can_confirm'], ['true', 'false'])) {
                 return $this->Provider->reason = 'Invalid value for can_confirm parameter: ' . $data['can_confirm'];
             }
             break;
         case 'basic-lti-launch-request':
         case 'DashboardRequest':
             if (empty($data['resource_link_id']) or !(strlen(trim($data['resource_link_id'])) > 0)) {
                 return $this->Provider->reason = 'Missing resource link ID.';
             }
             // fall through
         // fall through
         default:
             if (!empty($data['launch_presentation_document_target']) and !in_array($data['launch_presentation_document_target'], ['embed', 'frame', 'iframe', 'window', 'popup', 'overlay'])) {
                 return $this->Provider->reason = 'Invalid value for launch_presentation_document_target parameter: ' . $data['launch_presentation_document_target'];
             }
             break;
     }
     #
     ### Get the consumer
     #
     $this->loadModel('Lti.Consumer');
     $this->Consumer->id = $data['oauth_consumer_key'];
     $this->Consumer->read();
     if (empty($this->Consumer->consumer_key)) {
         return $this->Provider->reason = 'Invalid consumer key.';
     }
     if ($this->Consumer->protect) {
         if (empty($data['tool_consumer_instance_guid'])) {
             return $this->Provider->reason = 'A tool consumer GUID must be included in the launch request.';
         }
         if (empty($this->Consumer->consumer_guid) or !($this->Consumer->consumer_guid == $data['tool_consumer_instance_guid'])) {
             return $this->Provider->reason = 'Request is from an invalid tool consumer.';
         }
     }
     if (!$this->Consumer->enabled) {
         return $this->Provider->reason = 'Tool consumer has not been enabled by the tool provider.';
     }
     if (!empty($this->Consumer->enable_from) and CakeTime::fromString($this->Consumer->enable_from) > $now) {
         return $this->Provider->reason = 'Tool consumer access is not yet available. It will be available from ' . $this->Consumer->enable_from;
     }
     if (!empty($this->Consumer->enable_until) and CakeTime::fromString($this->Consumer->enable_until) <= $now) {
         return $this->Provider->reason = 'Tool consumer access expired on ' . $this->Consumer->enable_until;
     }
     #
     ### Validate message parameter constraints
     #
     if (!empty($this->Provider->constraints)) {
         $invalid_parameters = array();
         foreach ($this->Provider->constraints as $name => $constraint) {
             if (empty($constraint['messages']) || in_array($data['lti_message_type'], $constraint['messages'])) {
                 if ($constraint['required']) {
                     if (empty($data[$name]) or strlen(trim($data[$name])) <= 0) {
                         $invalid_parameters[] = "{$name} (missing)";
                         continue;
                     }
                 }
                 if (!empty($constraint['max_length'])) {
                     if (strlen(trim($data[$name])) > $constraint['max_length']) {
                         $invalid_parameters[] = "{$name} (too long)";
                     }
                 }
             }
         }
         if (count($invalid_parameters) > 0) {
             return $this->Provider->reason = 'Invalid parameter(s): ' . implode(', ', $invalid_parameters) . '.';
         }
     }
     $this->Provider->isOK = true;
 }
 /**
  * _mapping method
  *
  * @param int $start
  * @param int $end
  * @return array
  */
 protected function _mapping($start = 0, $end = 0)
 {
     $mapping = array();
     for ($i = 1; $i <= 10; $i++) {
         $mapping[$i] = array('version' => $i, 'name' => "00{$i}_schema_dump", 'class' => 'M4af9d151e1484b74ad9d007058157726', 'type' => 'mocks', 'migrated' => null);
         if ($i >= $start && $i <= $end) {
             $mapping[$i]['migrated'] = CakeTime::nice();
         }
     }
     return $mapping;
 }
 public function edit_post()
 {
     if ($this->request->is('post')) {
         // get uuid
         $guid = String::uuid();
         // get todays datetime in seconds
         $time_in_seconds = CakeTime::convert(time(), new DateTimeZone('Asia/Calcutta'));
         // set final id for array
         $id = "ad_" . $time_in_seconds . '_' . $guid;
         $final_aray['timestamp']['created'] = $time_in_seconds;
         $final_aray['timestamp']['modified'] = $time_in_seconds;
         $item_data = $this->data;
         // pr($item_data);
         // final Array for cloudant
         $final_aray = array();
         $final_aray['id'] = $id;
         $final_aray['doc_type'] = 'ad';
         $final_aray['i_want_to'] = $item_data['i_want_to'];
         $final_aray['job_type'] = $item_data['job_type'];
         $final_aray['condition'] = $item_data['condition'];
         $final_aray['you_are/i_am'] = $item_data['youare'];
         $final_aray['item_type']['id'] = $item_data['ItemType']['id'];
         $final_aray['item_type']['name'] = $item_data['ItemType']['name'];
         // for resume
         if (!$item_data['ItemType']['resume_file']['size'] <= 0) {
             $filename = array();
             $filename['resume_file']['name'] = $item_data['ItemType']['resume_file']['name'];
             $filename['resume_file']['type'] = $item_data['ItemType']['resume_file']['type'];
             $filename['resume_file']['tmp_name'] = $item_data['ItemType']['resume_file']['tmp_name'];
             $filename['resume_file']['size'] = $item_data['ItemType']['resume_file']['size'];
             $filename['resume_file']['error'] = $item_data['ItemType']['resume_file']['error'];
             $filename['guid'] = $id;
             if (!$this->ItemPhoto->save($filename)) {
                 $this->Session->setFlash('Sorry, an error occurred.', 'default', array('class' => 'alert alert-danger'), 'error');
                 $this->redirect(array('controller' => 'ad_posts', 'action' => 'index'));
             } else {
                 $last_uploaded_resume = $this->ItemPhoto->findByGuid($id);
                 $final_aray['resume'] = $last_uploaded_resume['ItemPhoto']['id'] . "/" . $last_uploaded_resume['ItemPhoto']['resume_file'];
             }
         }
         // end of resume
         // check photo uploaded or not
         if (!$item_data['ItemType']['image_files'][0]['size'] <= 0) {
             // save images in sql database
             $item_photo_details = array();
             // loop each uploaded images
             foreach ($item_data['ItemType']['image_files'] as $key => $value) {
                 $filename = array();
                 $filename['image_file']['name'] = $value['name'];
                 $filename['image_file']['type'] = $value['type'];
                 $filename['image_file']['tmp_name'] = $value['tmp_name'];
                 $filename['image_file']['size'] = $value['size'];
                 $filename['image_file']['error'] = $value['error'];
                 $filename['guid'] = $id;
                 array_push($item_photo_details, $filename);
             }
             if ($this->ItemPhoto->saveMany($item_photo_details)) {
                 // get current uploaded photos
                 $last_uploaded_images = $this->ItemPhoto->find('all', array('conditions' => array('guid' => $id), 'order' => 'created'));
                 $count = 0;
                 //pr(json_encode($last_uploaded_images));die();
                 $primary_photo = array();
                 // for save primary photo
                 $photos = array();
                 // for save other photos
                 $tmp_photo = array();
                 foreach ($last_uploaded_images as $value) {
                     // for photos
                     if ($count == 0) {
                         $primary_photo['filename'] = $value['ItemPhoto']['image_file'];
                         $primary_photo['dir'] = $value['ItemPhoto']['id'];
                         // add photos array into final_aray
                         $final_aray['primary_photo'] = $primary_photo;
                         //array_push($final_aray, $primary_photo);
                     } else {
                         $tmp_photo['filename'] = $value['ItemPhoto']['image_file'];
                         $tmp_photo['dir'] = $value['ItemPhoto']['id'];
                         array_push($photos, $tmp_photo);
                     }
                     $count++;
                 }
                 $final_aray['photo'] = $photos;
             } else {
                 $this->Session->setFlash('Sorry, an error occurred.', 'default', array('class' => 'alert alert-danger'), 'error');
                 $this->redirect(array('controller' => 'ad_posts', 'action' => 'index'));
             }
         }
         // end of photo
         //pr($final_aray);
         $final_aray['item_category']['id'] = $item_data['ItemCategory']['id'];
         $final_aray['item_category']['name'] = $item_data['ItemCategory']['name'];
         $final_aray['brand']['id'] = $item_data['brand']['id'];
         $final_aray['brand']['name'] = $item_data['brand']['name'];
         // find included item name
         if (isset($item_data['included'])) {
             $included = 0;
             $item = "";
             foreach ($item_data['included'] as $key => $value) {
                 if ($key === 'charger') {
                     $item = 'Charger';
                 } else {
                     if ($key === 'data_cabel') {
                         $item = 'Data Cabel';
                     } else {
                         if ($key === 'ear_phone') {
                             $item = 'Ear Phone/Head Phone';
                         } else {
                             if ($key === 'memory_card') {
                                 $item = 'Memory Card';
                             } else {
                                 if ($key === 'others') {
                                     $item = 'Other';
                                 }
                             }
                         }
                     }
                 }
                 $final_aray['included'][$included] = $item;
                 $included++;
             }
             // end of included
         }
         $final_aray['jobs']['Role']['id'] = $item_data['Role']['id'];
         $final_aray['jobs']['Role']['name'] = $item_data['Role']['name'];
         $final_aray['jobs']['company_name'] = $item_data['company_name'];
         $final_aray['jobs']['designation'] = $item_data['designation'];
         $final_aray['jobs']['education'] = $item_data['education'];
         $final_aray['jobs']['experience'] = $item_data['experience'];
         $final_aray['jobs']['key_skills'] = $item_data['key_skills'];
         $final_aray['AutoModel']['id'] = $item_data['AutoModel']['id'];
         $final_aray['AutoModel']['name'] = $item_data['AutoModel']['name'];
         $final_aray['year'] = $item_data['year'];
         $final_aray['kms_driven'] = $item_data['kms_driven'];
         $final_aray['fuel_type'] = $item_data['fuel_type'];
         $final_aray['valid_till'] = $item_data['valid_till'];
         $final_aray['vehicle_type'] = $item_data['vehicle_type'];
         $final_aray['event_date'] = $item_data['event_date'];
         $final_aray['venue'] = $item_data['venue'];
         $final_aray['real_estate']['area'] = $item_data['area'];
         $final_aray['real_estate']['city'] = $item_data['city'];
         $final_aray['real_estate']['locality'] = $item_data['locality'];
         $final_aray['title'] = $item_data['title'];
         $final_aray['description'] = $item_data['desc'];
         $final_aray['price'] = $item_data['price'];
         $final_aray['negotiable'] = $item_data['negotiable'];
         $final_aray['usage'] = $item_data['usage'];
         $final_aray['is_deleted'] = 0;
         $final_aray['is_completed'] = 0;
         $final_aray['status'] = 'active';
         $final_aray['personal_info']['name'] = $item_data['name'];
         $final_aray['personal_info']['mobile'] = $item_data['mobile'];
         $final_aray['personal_info']['email'] = $item_data['email'];
         $final_aray['personal_info']['area'] = $item_data['personal_area'];
         $final_aray['personal_info']['city'] = $item_data['personal_city'];
         // Set created and modified timestamp
         date_default_timezone_set('Asia/Calcutta');
         $todays = new DateTime();
         $final_date = str_replace('-', '', $todays->format('Y-m-d'));
         $final_aray['created'] = $todays->format('Y-m-d');
         $final_aray['modified'] = $todays->format('Y-m-d');
         $ad_post = json_encode($final_aray);
         // pr($final_aray);
         // pr($ad_post);die();
         // Save JSON
         if ($this->AdPost->save($final_aray)) {
             $this->Session->setFlash('Post added successfully.', 'default', array('class' => 'alert alert-success'), 'success');
             $this->redirect(array('controller' => 'ad_posts', 'action' => 'index'));
         } else {
             $this->Session->setFlash('Sorry, an error occurred.', 'default', array('class' => 'alert alert-danger'), 'error');
             $this->redirect(array('controller' => 'ad_posts', 'action' => 'index'));
         }
     }
     // get item types
     $item_types = $this->ItemType->find('list', array('order' => array('sort_order')));
     $this->set('item_types', $item_types);
     // get Role list
     $roles = $this->Role->find('list', array('order' => array('Role.name')));
     $this->set('roles', $roles);
     $user_data = $this->activeUser;
     $this->set('user_data', $user_data);
 }