/** * 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); }
/** * 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; }
/** * 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); }
/** * 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); }
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)); } }
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(); }
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; }
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); }
/** * index method * @param boolean $post * @return void */ public function index($post = null) { $user_id = $this->Session->read('user_id'); $this->Round->recursive = -1; $this->paginate = array('fields' => array('Round.id', 'Round.title', 'Round.description', 'Round.ends_in_date', 'Project.title', 'Project.id'), 'contain' => array('Project')); $rounds = $this->Round->UsersRound->find('list', array('recursive' => -1, 'fields' => 'UsersRound.round_id', 'group' => 'UsersRound.round_id', 'conditions' => array('UsersRound.user_id' => $user_id))); $this->Round->contain(false, array('Project')); App::uses('CakeTime', 'Utility'); $date = CakeTime::format('+1 days', '%Y-%m-%d'); $conditions = array('conditions' => array('AND' => array('Round.id' => $rounds, 'ends_in_date IS NOT NULL', "ends_in_date >= {$date}"))); $data = $this->Session->read('data'); $busqueda = $this->Session->read('search'); if ($post == null) { $this->Session->delete('data'); $this->Session->delete('search'); $this->set('search', ''); } else { $conditions['conditions']['OR'] = $data; $this->set('search', $busqueda); } $this->paginate = $conditions; $name = strtolower($this->name); $this->set($name, $this->paginate()); }
public function analysis() { $this->Cookie = $this->Components->load('Cookie'); $this->Cookie->type('rijndael'); $projects = array(); // $this->Cookie->time = '999 hours'; if ($this->request->is(array('post', 'put'))) { // debug($this->request->data); if (isset($this->request->data['Participant']['email'])) { $email = $this->request->data['Participant']['email']; } if (isset($this->request->data['Participant']['code'])) { $code = $this->request->data['Participant']['code']; } $project_id = -1; if (isset($this->request->data['Project']['Project'])) { $project_id = $this->request->data['Project']['Project']; } if ($this->data['Participant']['remember_me'] && isset($code) && isset($email)) { $cookie = array(); $cookie['email'] = $email; $cookie['code'] = $code; if (isset($project_id)) { $cookie['project_id'] = $project_id; } $this->Cookie->write('participantData', $cookie, true, '+2 weeks'); } else { if ($this->Cookie->check('participantData')) { $this->Cookie->destroy('participantData'); } } $projects = $this->getParticipantProjects($email, $code); App::uses('Folder', 'Utility'); App::uses('File', 'Utility'); if (isset($this->request->data['Participant']['analyze_File']) && $this->request->data['Participant']['analyze_File']['size'] > 0 && !empty($projects)) { /* ============================================= */ /* ==============Load analysis=================== */ /* ============================================= */ if ($this->request->data['Participant']['analyze_File']['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']['analyze_File']['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']['analyze_File']['tmp_name']); if ($file->readable()) { $content = $file->read(); $file->close(); $lines = explode("\n", $content); $incorrectFormat = empty($lines); $count = 0; $size = count($lines); 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) != 5; $count++; } else { break; } } } // $correctFormat = $this->correctTsvFormat($file, 5); if ($incorrectFormat) { // $count=$this->incorrecLineTsvFormat($file); $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')); } $participantID = $this->Participant->find('first', array("recursive" => -1, "fields" => array("id"), "conditions" => array('Participant.email' => $email, 'Participant.code' => $code))); $participantID = $participantID["Participant"]["id"]; $this->request->data['Participant']['id'] = $participantID; $this->participantSaveConnection($this->request->data['Participant'], "uploadAnalysis"); // $this->Participant->UploadedAnnotation->deleteAll(array( // "participant_id" => $participantID)); // // $this->Participant->PredictionDocument->deleteAll(array( // "participant_id" => $participantID, // "project_id" => $project_id // )); $javaJarPath = Configure::read('javaJarPath'); $analyze_program = Configure::read('analyze_program'); $runJava = Configure::read('runJava'); $program = $javaJarPath . DS . $analyze_program; $path = $this->request->data['Participant']['analyze_File']['tmp_name']; $file = new File($path); if ($file->readable()) { $newPath = $file->Folder->path . DS . md5(date('Y-m-d H:i:s:u')) . $file->name() . "mtmp"; $file->copy($newPath); $path = $newPath; } else { throw new Exception("Ops! file could not be readed"); } $arguments = "{$project_id}\t{$participantID}\t{$email}\t{$path}"; // exec("nohup java -jar $program $arguments", $output); $javaLog = ".." . DS . 'java_jars' . DS . "java.log"; $date = date('Y-m-d H:i:s'); exec("echo \"{$date}:{$runJava} {$program} {$arguments}\" >> {$javaLog} 2>&1 &"); exec("{$runJava} {$program} {$arguments} >> {$javaLog} 2>&1 &"); $this->Session->setFlash("Your predictions are being processed, we will send you an email when the analysis finish", 'success'); return $this->redirect(array('controller' => 'Participants', 'action' => 'analysis')); } } else { if (isset($this->request->data['Participant']['results_File']['size']) && $this->request->data['Participant']['results_File']['size'] > 0) { if ($this->request->data['Participant']['results_File']['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')); } /* ============================================= */ /* =====================Results================= */ /* ============================================= */ $file = new File($this->request->data['Participant']['results_File']['tmp_name']); if ($file->readable()) { $content = $file->read(); $file->close(); $content = $this->decrypt($content); $results = json_decode(trim($content), true); // debug($results); if (!empty($results)) { $projects = $this->getParticipantProjects($email, $code, $results['project_id']); if (!empty($projects)) { $goldenSet = $this->Participant->GoldenProject->find('first', array('recursive' => -1, 'fields' => array('user_id', 'round_id'), 'conditions' => array('project_id' => $results['project_id']))); if (!empty($goldenSet)) { $isModified = !$this->Participant->PredictionFile->hasAny(array('participant_id' => $results['Participant']['id'], 'modified' => $results['date'])); $results['Participant']['isModified'] = $isModified; $results['Golden']['user_id'] = $goldenSet['GoldenProject']['user_id']; $results['Golden']['round_id'] = $goldenSet['GoldenProject']['round_id']; $this->Session->write("analysisResults", $results); $this->redirect(array('action' => 'results')); } else { $this->Session->setFlash("This golden set have been deleted"); } } else { $this->Session->setFlash("This file does not correspond to your credentials"); } } else { $this->Session->setFlash("This file is corrupted"); } } else { $this->Session->setFlash("This file is corrupted"); } } else { if (empty($projects)) { $this->Session->setFlash("You are not in any project"); } else { $this->Session->setFlash("One team prediction file or one result file is needed"); } } } } else { $cookie = $this->Cookie->read('participantData'); if (isset($cookie)) { if (isset($cookie['email']) && $cookie['code']) { $this->request->data['Participant']['email'] = $cookie['email']; $this->request->data['Participant']['code'] = $cookie['code']; $this->request->data['Participant']['remember_me'] = true; if (isset($cookie['project_id'])) { $this->request->data['Project']['Project'] = $cookie['project_id']; } $projects = $this->getParticipantProjects($cookie['email'], $cookie['code']); if (empty($projects)) { $this->Cookie->destroy('participantData'); } } else { $this->Cookie->destroy('participantData'); } } $this->loadModel('Post'); $this->Post->recursive = -1; $this->Post->contain(false, array('User' => array('username', 'surname', 'full_name', 'image', 'image_type', 'id'))); $this->Post->paginate = array('limit' => 5, 'order' => array('modified' => 'DESC')); $this->set("posts", $this->paginate($this->Post)); } $this->set('projects', $projects); App::uses('CakeTime', 'Utility'); $finalDate = Configure::read('final_date_to_upload_tasks'); $startDate = Configure::read('initial_date_to_upload_tasks'); $isEnd = CakeTime::isPast($finalDate); $isFuture = CakeTime::isFuture($startDate); $isThisWeek = CakeTime::isThisWeek($finalDate); $isToday = CakeTime::isTomorrow(CakeTime::fromString($finalDate)); $finalDate = CakeTime::format($finalDate, "%B %e, %Y"); $startDate = CakeTime::format($startDate, "%B %e, %Y"); $this->set('isEnd', $isEnd); $this->set('isFuture', $isFuture); $this->set('isThisWeek', $isThisWeek); $this->set('isToday', $isToday); $this->set('finalDate', $finalDate); $this->set('startDate', $startDate); //// $key = "xVO5JLSLOTpKX4YRyFpJXNYb1STQK26mHAzgNK6bwS697XzK8ZE5kEA8R7gajaI9fE6HfemeLhg28nqbGTmh5Dv5uKydSOoM4BHlQ43mvH4h0Jl3xFDcv95fRnY9wYAluS1WFi9QOLc2JDUOsN3ggNzypHuZcPaAjBklfsNH98qkX5brqEnfMUubPOUCtpTEUmtvVNq2oTGKSArEuSuuKRnMHtlbKvl4XbaAUvSfajF4DtHwLa2qaWU6pNXLHf16"; //// $key = "FFF3454D1E9CCDE00101010101010101"; // $value = "63612bb6b56ef964bc2a6add5e0697deadde735fd4ca966d7b762f61b2b4cb14a14500"; //// $value = base64_decode($value); //// debug($value); //// $result = Security::rijndael($value, $key, 'decrypt'); // $result = $this->decrypt($value); //// $resultE = Security::rijndael($value, $key, 'encrypt'); // $this->set(compact('result', 'resultE')); }
/** * Hurad configuration step */ public function finalize() { $this->set('title_for_layout', __d('hurad', 'Hurad Configuration')); $dataSource = ConnectionManager::getDataSource('default'); if ($this->request->is('post')) { $this->Installer->set($this->request->data); if ($this->Installer->validates()) { $search = []; $search['$[prefix]'] = $dataSource->config['prefix']; App::uses('CakeTime', 'Utility'); $search['$[created]'] = CakeTime::format('Y-m-d H:i:s', strtotime('now')); $search['$[modified]'] = CakeTime::format('Y-m-d H:i:s', strtotime('now')); $request = new CakeRequest(); $search['$[client_ip]'] = $request->clientIp(); $search['$[user_agent]'] = $request::header('USER_AGENT'); $search['$[username]'] = $this->request->data['Installer']['site_username']; $search['$[email]'] = $this->request->data['Installer']['email']; $search['$[password]'] = Security::hash($this->request->data['Installer']['site_password'], null, true); $search['$[title]'] = $this->request->data['Installer']['site_title']; $serverName = env("SERVER_NAME"); $url = Router::url('/'); $search['$[site_url]'] = rtrim("http://" . $serverName . $url, '/'); if ($dataSource->connected) { if ($this->__executeSQL("hurad_defaults.sql", $dataSource, $search)) { $this->Session->setFlash(__d('hurad', 'Hurad successfully installed.'), 'flash_message', array('class' => 'success')); $this->redirect(array('action' => 'welcome')); } } else { $this->Session->setFlash(__d('hurad', 'Not connected to database.'), 'flash_message', array('class' => 'danger')); } } } }
public function feed() { $this->Event->contain(array('Artist' => array('fields' => array('id', 'title')), 'Type' => array('fields' => array('id', 'title')), 'Place' => array('fields' => array('id', 'title')))); $start = $this->request->query['start']; $end = $this->request->query['end']; $this->Event->recursive = 1; $events = $this->Event->find('all', array('conditions' => array('AND' => array('start >=' => $start, 'start <=' => $end)), 'fields' => array('Event.start', 'Event.end', 'Event.title', 'Event.id', 'Event.regular_ticket_price', 'Event.discounted_ticket_price'))); foreach ($events as $key => $event) { $events[$key]['start'] = CakeTime::toAtom($event['Event']['start']); $events[$key]['start_day'] = CakeTime::format($event['Event']['start'], '%e %B %Y'); $events[$key]['start_time'] = CakeTime::format($event['Event']['start'], '%Hh%M'); $events[$key]['end'] = CakeTime::toAtom($event['Event']['end']); $events[$key]['title'] = $event['Event']['title']; $events[$key]['regular_ticket_price'] = $event['Event']['regular_ticket_price']; $events[$key]['discounted_ticket_price'] = $event['Event']['discounted_ticket_price']; unset($events[$key]['Event']); } $this->set('data', $events); $this->layout = 'ajax'; $this->render('../Shared/json/data'); return; }
public function oldCopyRound($projectId = null) { if ($this->request->is('post') || $this->request->is('put')) { //$this -> autoRender = false; if (!empty($this->request->data['Round']['Round'])) { $oldRoundId = $this->request->data['Round']['Round']; $round = $this->Round->find('first', array('recursive' => -1, 'conditions' => array('Round.id' => $oldRoundId))); if (trim($this->request->data['Round']['title']) == '' || !isset($this->request->data['Round']['title'])) { $this->Session->setFlash('Please select one Title'); $this->redirect(array('controller' => 'rounds', 'action' => 'copyRound', $projectId)); } App::uses('CakeTime', 'Utility'); if (CakeTime::isFuture($round['Round']['ends_in_date'])) { $this->Round->id = $round['Round']['id']; $date = CakeTime::format('-1 days', '%Y-%m-%d'); $this->Round->saveField('ends_in_date', $date); } if (empty($this->request->data['Round']['User'])) { $this->Session->setFlash('You must choose at least one user'); $this->redirect(array('controller' => 'rounds', 'action' => 'copyRound', $projectId)); } else { $oldRoundId = $this->request->data['Round']['Round']; $this->Round->create(); $this->request->data['Round']['ends_in_date'] = NULL; $users = $this->request->data['Round']['User']; $conditions_userRounds = array('UsersRound.round_id' => $oldRoundId, 'UsersRound.user_id' => $users); //guardamos los usuarios en condiciones unset($this->request->data['Round']['User']); $title = $this->request->data['Round']['title']; $this->request->data['Round']['title'] = $title . '-[0%]'; $errors = ""; //$db = $this->Round->getDataSource(); //$db->begin(); if ($this->Round->save($this->request->data, false)) { //se deshabilita el save para poder guardar rounds con ends_in_date = NULL //esta bandera marcara que un round esta en estado de copia $this->Session->setFlash('We are creating a new version of the round. Please be patient', 'information'); //cortamos la ejecucion parab el usuario pero el script sigue en ejecucion //de esta forma el usuario puedeseguir navegando $this->backGround(array('controller' => 'projects', 'action' => 'view', $round['Round']['project_id'])); $round_id = $this->Round->id; $newRoundId = $this->Round->id; $size_userRounds = $this->Round->UsersRound->find('count', array('recursive' => -1, 'conditions' => $conditions_userRounds)); /** * tamaño de particiones * Haremos una particion de los rounds para no sobrecargar la memoria * ** */ if ($size_userRounds > 0) { //hacemos partioces de user_rounds de 100 $particiones_userRounds = 100; $size_userRounds_total = $size_userRounds; //si el tamaño es mayor que la particion calculamos cuantas veces vamos a tener que hacer if ($size_userRounds > $particiones_userRounds) { $fin_userRounds = $size_userRounds / $particiones_userRounds; //calculamos el numero de beces a la baja // por ejemplo 2.5 se haces dos veces $fin_userRounds = floor($fin_userRounds); //si existe resto se hace una vez mas if ($size_userRounds % $particiones_userRounds != 0) { $fin_userRounds++; } } else { // si no la particion es = al tamaño $particiones_userRounds = $size_userRounds; $fin_userRounds = 1; } $contador_userRounds = 0; $procces_userRounds = 0; $time = date('Y-m-d H:i:s'); //variables para monotorizar la copia $worked = 0; $procces = 0; while ($contador_userRounds < $fin_userRounds) { $usersRounds = $this->Round->UsersRound->find('all', array('offset' => $procces_userRounds, 'limit' => $particiones_userRounds, 'recursive' => -1, 'fields' => array('UsersRound.id', 'UsersRound.user_id', 'UsersRound.document_id', 'UsersRound.text_marked'), 'conditions' => $conditions_userRounds)); //se eligen bucles for en vez de bucles foreach dado que son mas rapidos si se van a modificar datos //http://www.phpbench.com/ $usersRoundTam = sizeof($usersRounds); for ($i = 0; $i < $usersRoundTam; $i++) { $procces++; $worked = $procces / $size_userRounds_total * 100; if (round($worked) % 10 == 0) { $data = array('Round' => array('title' => $title . '-[' . round($worked) . '%]')); $this->Round->save($data); } $usersRounds[$i]['UsersRound']['created'] = $time; $conditions = array('Annotation.round_id' => $oldRoundId, 'Annotation.document_id' => $usersRounds[$i]['UsersRound']['document_id'], 'Annotation.user_id' => $usersRounds[$i]['UsersRound']['user_id'], 'Annotation.users_round_id' => $usersRounds[$i]['UsersRound']['id']); $textoForMatches = $usersRounds[$i]['UsersRound']['text_marked']; $usersRounds[$i]['UsersRound']['round_id'] = $newRoundId; unset($usersRounds[$i]['UsersRound']['id']); unset($usersRounds[$i]['UsersRound']['text_marked']); $this->Round->UsersRound->create(); if ($this->Round->UsersRound->save($usersRounds[$i])) { $size_annotations = $this->Round->UsersRound->Annotation->find('count', array('recursive' => -1, 'conditions' => $conditions)); if ($size_annotations > 0) { $parseKey = Configure::read('parseKey'); $parseIdAttr = Configure::read('parseIdAttr'); /** * Particiones de anotaciones */ $particiones_annotations = 400; if ($size_annotations > $particiones_annotations) { $fin_annotations = $size_annotations / $particiones_annotations; $fin_annotations = floor($fin_annotations); if ($size_annotations % $particiones_annotations != 0) { $fin_annotations++; } } else { $particiones_annotations = $size_annotations; $fin_annotations = 1; } $contador_annotations = 0; $procces_annotations = 0; $annotations_id = array(); while ($contador_annotations < $fin_annotations) { $annotations = $this->Round->UsersRound->Annotation->find('all', array('offset' => $procces_annotations, 'limit' => $particiones_annotations, 'recursive' => -1, 'conditions' => $conditions)); $annotationTam = sizeof($annotations); for ($j = 0; $j < $annotationTam; $j++) { $oldId = $annotations[$j]['Annotation']['id']; unset($annotations[$j]['Annotation']['id']); //insertamos nuevo user round $annotations[$j]['Annotation']['users_round_id'] = $this->Round->UsersRound->id; //insertamos nuevo round $annotations[$j]['Annotation']['round_id'] = $newRoundId; if (empty($annotations[$j]['Annotation']['annotated_text'])) { $annotations[$j]['Annotation']['annotated_text'] = 'empty?'; } $this->Round->UsersRound->Annotation->create(); if ($this->Round->UsersRound->Annotation->save($annotations[$j])) { $newId = $this->Round->UsersRound->Annotation->id; array_push($annotations_id, $newId); $this->Round->UsersRound->Annotation->query("insert into annotations_questions ( annotation_id,question_id,answer)\n SELECT " . $newId . ",question_id,answer FROM annotations_questions where annotation_id = {$oldId}"); } } //$i = 0; $i < $annotationTam; $i++ if ($procces_annotations + $particiones_annotations * 2 > $size_annotations) { $procces_annotations += $particiones_annotations; $particiones_annotations = $size_annotations - $procces_annotations; } else { $procces_annotations += $particiones_annotations; } $contador_annotations++; } /* * A partir de este punto machearemos las anotaciones en el documento actualizando su ID * */ preg_match_all("/<mark[^>]*" . $parseKey . "[^>]*[^>]*>/", $textoForMatches, $matches); $numberOfMaches = sizeof($matches[0]); // el sistema es flexible frente a contratiempos imprevistos como que el umero de anotaciones parseadas sean distintos a la base de datos $pos = -1; $k = 0; $ultimoId = -1; while ($k < $numberOfMaches) { preg_match('/[^>]*' . $parseIdAttr . '=.?(\\d+).?[^>]/', $matches[0][$k], $id); if ($ultimoId != $id) { $ultimoId = $id; $pos++; } // debug($annotations_id[$pos]); $search = $matches[0][$k]; // if(!isset($annotations_id[$pos])) { // debug($id); // } $replace = preg_replace('/' . $parseIdAttr . '=.(\\d+)./', $parseIdAttr . '="' . $annotations_id[$pos] . '"', $search); $textoForMatches = str_replace($search, $replace, $textoForMatches); $k++; } if ($pos + 1 != sizeof($annotations_id)) { // debug(sizeof($annotations_id)); // debug($numberOfMaches); // debug($pos); // debug($usersRounds[$i]['UsersRound']['document_id']); $errors = "This round is courrupted. Unexpected error has occurred. Do not worry this is not a fatal error. But please contact the administrator. Error: 'other number annotations database VS parse'"; } } //guardamos el documento con el texto anotado actualizado $usersRounds[$i]['UsersRound']['text_marked'] = $textoForMatches; unset($usersRounds[$i]['UsersRound']['id']); $this->Round->UsersRound->save($usersRounds[$i]); } //$this->Round->UsersRound->save($usersRounds[$i]) } //$i = 0; $i < $usersRoundTam; $i++ if ($procces_userRounds + $particiones_userRounds * 2 >= $size_userRounds) { $procces_userRounds += $particiones_userRounds; $particiones_userRounds = $size_userRounds - $procces_userRounds; } else { $procces_userRounds += $particiones_userRounds; } $contador_userRounds++; } } //finalmente actualizamos los datos del round con los datos que metio el usuario e introducimos los tipos de anotacion //del round origen $date = CakeTime::format('+30 days', '%Y-%m-%d'); $data = array('Round' => array('description' => $errors, 'ends_in_date' => $date, 'title' => $title), 'User' => array('User' => $users)); if ($this->Round->save($data)) { //$this->Round->commit(); $round_id = $this->Round->id; $this->Round->query("insert into types_rounds ( round_id,type_id) select {$round_id},type_id\n from types_rounds \n where round_id = {$oldRoundId}"); //$db->commit(); //$db->close(); } else { //$db->rollback(); //$db->close(); } } else { //$db->rollback(); //$db->close(); $this->Session->setFlash('Unexpected error ocurs, error Id: roundCopySave'); $this->redirect(array('controller' => 'rounds', 'action' => 'copyRound', $projectId)); } } } else { $this->Session->setFlash('There are no data to be copied!'); $this->redirect(array('controller' => 'rounds', 'action' => 'copyRound', $projectId)); } } else { $this->Round->Project->id = $projectId; if (!$this->Round->Project->exists()) { throw new NotFoundException(__('Invalid round')); } //!$this->Round->exists() $deleteCascade = Configure::read('deleteCascade'); $conditions = array('project_id' => $projectId, 'ends_in_date IS NOT NULL'); if ($deleteCascade) { $conditions = array('project_id' => $projectId, 'ends_in_date IS NOT NULL', 'title!=\'Removing...\''); } $rounds = $this->Round->find('list', array('conditions' => $conditions)); if (empty($rounds)) { $this->Session->setFlash('Insufficient data for this operation'); $this->redirect(array('controller' => 'projects', 'action' => 'view', $projectId)); } else { $cond = array('project_id' => $projectId); $users = $this->Round->Project->ProjectsUser->find('all', array('fields' => 'user_id', 'conditions' => $cond, 'recursive' => -1)); $users = $this->flatten($users); $userConditions = array('id' => $users); if ($deleteCascade) { $userConditions = array('username !=' => 'Removing...', 'id' => $users); } $users = $this->Round->User->find('list', array('conditions' => $userConditions)); } $this->set('rounds', $rounds); $this->set('users', $users); $this->set('projectId', $projectId); } }
private function admin_createDta($dtaRequests) { $dtaFile = new DTA(DTA_DEBIT); $dtaFile->setAccountFileSender(array('name' => 'Ringelsoeckchen e.V.', 'bank_code' => 37050299, 'account_number' => 138274368)); $this->Fee->Member->recursive = -1; foreach ($dtaRequests as $dtaRequest) { //Get member information $member = $this->Fee->Member->find('first', array('conditions' => array('id' => $dtaRequest['member_id']))); //Get yearly fee information $yearly_fee = $this->Fee->YearlyFee->find('first', array('conditions' => array('year' => $dtaRequest['year']))); $dtaFile->addExchange(array('name' => $member['Member']['account_holder'], 'bank_code' => $member['Member']['bank_code'], 'account_number' => $member['Member']['account_number']), $yearly_fee['YearlyFee']['fee'], array('Ringelsoeckche Beitrag ' . $dtaRequest['year'], $member['Member']['full_name'])); } $dtaFile->saveFile(TMP . 'dta.dta'); $this->viewClass = 'Media'; $params = array('id' => 'dta.dta', 'name' => 'Mitgliedsbeitraege' . CakeTime::format('Y-m-d', time()), 'download' => true, 'extension' => 'dta', 'path' => TMP); $this->set($params); }
public function admin_importXml() { if ($this->request->is('post')) { $xml = Xml::build($this->request->data['Booking']['Filename']['tmp_name']); $bookingsAlreadyPresent = 0; $bookingsAdded = 0; foreach ($xml->xpath('/UmsatzListe/Umsatz') as $payment) { //Transfer XML Data to application format $newBooking['date'] = CakeTime::format('Y-m-d', $payment->Datum); $newBooking['giro_payment_name'] = $payment->Name; $newBooking['giro_payment_reason'] = $payment->Verwendungszweck; $newBooking['description'] = $payment->Geschaeftsvorfall; $newBooking['account'] = 'Giro'; if (floatval(str_replace(',', '.', $payment->Betrag)) >= 0) { $newBooking['credit'] = floatval(str_replace(',', '.', $payment->Betrag)); $newBooking['debit'] = 0; } else { $newBooking['debit'] = abs(floatval(str_replace(',', '.', $payment->Betrag))); $newBooking['credit'] = 0; } if (!$this->Booking->find('first', array('conditions' => array('date' => $newBooking['date'], 'giro_payment_name' => $newBooking['giro_payment_name'], 'giro_payment_reason' => $newBooking['giro_payment_reason'], 'credit' => $newBooking['credit'], 'debit' => $newBooking['debit']))) && in_array($payment->Geschaeftsvorfall, $this->supportedPayments)) { $this->Booking->create(); $this->Booking->save($newBooking); $bookingsAdded++; } else { $bookingsAlreadyPresent++; } } $this->Session->setFlash($bookingsAdded . ' ' . __('bookings imported from xml') . ', ' . $bookingsAlreadyPresent . ' ' . __('bookings already present or not supported')); $this->redirect(array('action' => 'index')); } }
function admin_genericosandroid() { ini_set('display_errors', 'Off'); $this->autoRender = false; $this->response->type('json'); $meses = array('January' => 'Janeiro', 'February' => 'Fevereiro', 'March' => 'Março', 'April' => 'Abril', 'May' => 'Maio', 'June' => 'Junho', 'July' => 'Julho', 'August' => 'Agosto', 'September' => 'Setembro', 'October' => 'Outubro', 'November' => 'Novembro', 'December' => 'Dezembro'); $dia_semana = array('Monday' => 'Segunda-feira', 'Tuesday' => 'Terça-feira', 'Wednesday' => 'Quarta-feira', 'Thursday' => 'Quinta-feira', 'Friday' => 'Sexta-feira', 'Saturday' => 'Sábado', 'Sunday' => 'Domingo'); $model = 'Conteudo'; $keypass = $this->params->query['k']; $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} AND c.publicar = 1 ORDER BY c.id DESC"; //print_r($sql); //die(); $all = $this->{$model}->query($sql); $json_rdy["conteudos"] = array(); foreach ($all as $content) { $created = CakeTime::format('l d F', $content['c']['created']); $created = explode(' ', $created); $created = "{$dia_semana[$created[0]]} | {$created[1]} de {$meses[$created[2]]}"; //$texto = htmlentities($content['c']['texto']); //$texto = json_encode($content['c']['texto']); $texto = $content['c']['texto']; $conteudo = array("id" => $content['c']['id'], "categoria_id" => $content['c']['categoria_id'], "titulo" => $content['c']['titulo'], "texto" => $texto, "created" => $created); array_push($json_rdy["conteudos"], $conteudo); } // echo "<pre>"; // print_r($json_rdy); //echo json_encode($json_rdy); $json = json_encode($json_rdy); $this->response->body($json); }
/** * Callback used to display what migration is being runned * * Additionally, shows the generation date of the migration, * if the version is greater than '2000-01-01'. * * @param CakeMigration &$Migration Migration being performed * @param string $direction Direction being runned * @return void */ public function beforeMigration(&$Migration, $direction) { $version = $Migration->info['version']; $generationDate = ''; if ($version > 946684800) { $generationDate = ' (' . CakeTime::format($version, '%Y-%m-%d %H:%M:%S') . ')'; } $this->out(' [' . sprintf("%'.03d", $version) . '] ' . $Migration->info['name'] . $generationDate); }
public function formatTimeResult($time) { return CakeTime::format($time, '%d.%m.%Y %H:%M %p'); }
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)); } } }
/** * edit method * * @throws NotFoundException * @param string $id * @return void */ public function edit($id = null) { $this->set('title_for_layout', "Editar Paciente"); $patient = $this->Patient->findById($id); if (!$id) { $this->Session->setFlash(__('Por favor, forneça a identificação do Usuário!'), 'alert-box', array('class' => 'error', 'title' => 'Error!')); $this->redirect(array('action' => 'index')); } if (!$patient) { $this->Session->setFlash(__('Por favor, forneça a identificação do Usuário!'), 'alert-box', array('class' => 'error', 'title' => 'Error!')); $this->redirect(array('action' => 'index')); } if ($this->request->is('post') || $this->request->is('put')) { $this->Patient->id = $id; $this->request->data['Patient']['born'] = CakeTime::format($this->request->data['Patient']['date'], "%Y-%m-%d"); if ($this->Patient->save($this->request->data)) { $this->Session->setFlash(__('Os dados foram salvos'), 'alert-box', array('class' => 'success', 'title' => 'Sucesso!')); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('Não foi possível concluir a solicitação...'), 'alert-box', array('class' => 'error', 'title' => 'Error!')); } } if (!$this->request->data) { $this->request->data = $patient; $born = CakeTime::format($patient['Patient']['born'], "%d-%m-%Y"); $this->set(compact('born')); $agents = $this->Patient->Agent->find('list'); $this->set(compact('agents')); } }
/** * Retrieve full permalink for current content. * * @param int $contentId Post or Page id * * @return string */ public function getPermalink($contentId) { $this->getContentData($contentId); $year = CakeTime::format('Y', $this->content[$this->contentModel]['created']); $month = CakeTime::format('m', $this->content[$this->contentModel]['created']); $day = CakeTime::format('d', $this->content[$this->contentModel]['created']); if ($this->contentType == 'post') { switch (Configure::read('Permalink.common')) { case 'default': $permalink = Router::url("/p/" . $this->content[$this->contentModel]['id'], true); break; case 'day_name': $permalink = Router::url('/' . $year . "/" . $month . "/" . $day . "/" . $this->content[$this->contentModel]['slug'], true); break; case 'month_name': $permalink = Router::url('/' . $year . "/" . $month . "/" . $this->content[$this->contentModel]['slug'], true); break; default: break; } } elseif ($this->contentType == 'page') { if (Configure::read('Permalink.common') == 'default') { $permalink = Router::url("/page/" . $this->content[$this->contentModel]['id'], true); } else { $permalink = Router::url("/page/" . $this->content[$this->contentModel]['slug'], true); } } return $permalink; }
private function admin_createSepa($sepaRequests) { //F�r Sparkasse muss der Request kompatibel zu pain 008.002.02 (Sammellastschriften) sein // Erzeugen einer neuen Instanz $creatorSequenceFirst = new SepaXmlCreator(); /* * Mit den Account-Werten wird das eigene Konto beschrieben * erster Parameter = Name * zweiter Parameter = IBAN * dritter Paramenter = BIC */ $creatorSequenceFirst->setAccountValues('Ringelsoeckchen e.V.', 'DE34370502990138274368', 'COKSDE33XXX'); /* * Setzen Sie von der Bundesbank �bermittelte Gl�ubiger-ID */ $creatorSequenceFirst->setGlaeubigerId("DE90BEI00001201537"); /* * Mit Hilfe eines Ausf�hrungs-Offsets k�nnen Sie definieren, wann die Lastchrift gezogen wird. Die Anzahl * der �bergebenen Tage wird auf den aktuellen Kalendertag addiert * * Beispiel 1 * heute = 1. Juni 2013 * Offset nicht �bergeben * Ausf�hrung -> Heute bzw. n�chst m�glich * * Beispiel 1 * heute = 1. Juni 2013 * Offset 3 * Ausf�hrung -> 4. Juni 2013 */ $creatorSequenceFirst->setAusfuehrungOffset(8); $creatorSequenceRecurring = clone $creatorSequenceFirst; $creatorSequenceFirst->setSequenz(SepaXmlCreator::SEQUENZ_FIRST); $creatorSequenceRecurring->setSequenz(SepaXmlCreator::SEQUENZ_RECURRING); $this->Fee->Member->recursive = -3; if (!$sepaRequests) { throw new NotFoundException("Request empty"); } foreach ($sepaRequests as $sepaRequest) { //Get member information $member = $this->Fee->Member->find('first', array('conditions' => array('id' => $sepaRequest['member_id']))); //Get yearly fee information $yearly_fee = $this->Fee->YearlyFee->find('first', array('conditions' => array('year' => $sepaRequest['year']))); $sepamandate = $this->Fee->Member->Sepamandate->find('first', array('conditions' => array('member_id' => $sepaRequest['member_id'], 'valid' => 1))); if (!$sepamandate) { throw new NotFoundException('Could not find Sepamandate for ' . $member['Member']['full_name']); } // Erzeugung einer neuen Buchungssatz $buchung = new SepaBuchung(); // gew�nschter Einzugsbetrag $buchung->setBetrag($yearly_fee['YearlyFee']['fee']); // gew�nschte End2End Referenz (OPTIONAL) $buchung->setEnd2End('BEI' . $sepaRequest['year'] . '-' . $member['Member']['id']); // BIC des Zahlungspflichtigen Institutes $buchung->setBic($sepamandate['Sepamandate']['bic']); // Name des Zahlungspflichtigen $buchung->setName(htmlspecialchars($sepamandate['Sepamandate']['account_holder'])); // IBAN des Zahlungspflichtigen $buchung->setIban($sepamandate['Sepamandate']['iban']); // gew�nschter Verwendungszweck (OPTIONAL) $buchung->setVerwendungszweck('Ringelsoeckche Beitrag ' . $sepaRequest['year'] . ' ' . $member['Member']['full_name']); // Referenz auf das vom Kunden erteilte Lastschriftmandat // ID = MANDAT0001 // Erteilung durch Kunden am 20. Mai 2013 // False = seit letzter Lastschrift wurde am Mandat nichts ge�ndert $buchung->setMandat($sepamandate['Sepamandate']['mandate_reference'], $sepamandate['Sepamandate']['mandate_date'], false); // Buchung zur entsprechenden Liste hinzufügen if ($sepamandate['Sepamandate']['sequence'] == "first") { $creatorSequenceFirst->addBuchung($buchung); } else { $creatorSequenceRecurring->addBuchung($buchung); } } $zip = new ZipArchive(); $zip->open(TMP . 'sepa.zip', ZIPARCHIVE::OVERWRITE); if ($creatorSequenceFirst->hasBuchungen()) { $file = new File(TMP . 'sepa_erstlastschriften.xml', true); // Nun kann die XML-Datei über den Aufruf der entsprechenden Methode generiert werden $sepaOutput = $creatorSequenceFirst->generateBasislastschriftXml(); $file->write($sepaOutput); $file->close(); $zip->addFile(TMP . 'sepa_erstlastschriften.xml', 'sepa_erstlastschriften.xml'); } if ($creatorSequenceRecurring->hasBuchungen()) { $file = new File(TMP . 'sepa_folgelastschriften.xml', true); // Nun kann die XML-Datei über den Aufruf der entsprechenden Methode generiert werden $sepaOutput = $creatorSequenceRecurring->generateBasislastschriftXml(); $file->write($sepaOutput); $file->close(); $zip->addFile(TMP . 'sepa_folgelastschriften.xml', 'sepa_folgelastschriften.xml'); } $zip->close(); $this->viewClass = 'Media'; $params = array('id' => 'sepa.zip', 'name' => 'Sepa-Lastschrift-Mitgliedsbeitraege' . CakeTime::format('Y-m-d', time()), 'download' => true, 'extension' => 'zip', 'path' => TMP); $this->set($params); }
/** * login method * * @return void */ public function logout($isLogin = false) { $user_id = $this->Session->read('user_id'); if (isset($user_id) && !$isLogin) { $this->User->id = $user_id; App::uses('CakeTime', 'Utility'); $date = CakeTime::format("-3 seconds", '%Y-%m-%d %H:%M:%S'); $this->User->saveField('logged_until', $date); } $this->Session->destroy(); // $this->Cookie->destroy(); if ($isLogin) { $this->Session->setFlash('This user is already logged into the system. Please try again in a minute or contact with administrator'); } // $this->redirect(array('controller' => 'Posts', 'action' => 'publicIndex')); $this->redirect('/'); }
/** * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string. * This function also accepts a time string and a format string as first and second parameters. * In that case this function behaves as a wrapper for TimeHelper::i18nFormat() * * ## Examples * * Create localized & formatted time: * * ``` * $this->Time->format('2012-02-15', '%m-%d-%Y'); // returns 02-15-2012 * $this->Time->format('2012-02-15 23:01:01', '%c'); // returns preferred date and time based on configured * locale * $this->Time->format('0000-00-00', '%d-%m-%Y', 'N/A'); // return N/A because an invalid date was passed * $this->Time->format('2012-02-15 23:01:01', '%c', 'N/A', 'America/New_York'); // converts passed date to * timezone * ``` * * @param int|string|DateTime $format date format string (or a UNIX timestamp, strtotime() valid string or * DateTime object) * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object (or a date * format string) * @param bool $invalid flag to ignore results of fromString == false * @param string|DateTimeZone $timezone User's timezone string or DateTimeZone object * * @return string Formatted date string * @see CakeTime::format() * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function format($format, $date = NULL, $invalid = FALSE, $timezone = NULL) { return $this->_engine->format($format, $date, $invalid, $timezone); }
/** *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.')); } } } }
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()); } }
/** * Método responsável por converter a data do formato Cake para o da Cielo * para ser usada na construção dos XML's * * @param string $data Exemplo formato: 1990-05-05 15:00:00 * @return string Data no formato: 1990-05-05T150:00:00 */ public function converterData($data = null) { if (is_null($data)) { return false; } return CakeTime::format('Y-m-d', $data) . 'T' . CakeTime::format('H:i:s', $data); }
/** * 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); }
/** * delete create * * @throws NotFoundException * @throws MethodNotAllowedException * @param string $id * @return void */ public function create() { $this->Note->Budget->contain(array('Note', 'BudgetStatus', 'FiscalYear', 'BudgetType', 'SharePeriodicity', 'ShareDistribution')); $budget = $this->Note->Budget->find('first', array('conditions' => array('Budget.id' => $this->getPhkRequestVar('budget_id'), 'Budget.budget_status_id' => '2'))); if (empty($budget)) { $this->Flash->error(__('Invalid Budget')); $this->redirect(array('controller' => 'budgets', 'action' => 'index', '?' => array('condo_id' => $this->phkRequestData['condo_id']))); } if (isset($budget['Note']) && count($budget['Note']) > 0) { $this->Flash->error(__('Invalid Budget')); $this->redirect(array('controller' => 'budgets', 'action' => 'index', '?' => array('condo_id' => $this->phkRequestData['condo_id']))); } if ($this->request->is('post')) { $notes = $this->request->data['Note']; unset($notes['Budget']); App::uses('CakeTime', 'Utility'); foreach ($notes as $key => $note) { // check fraction please $this->request->data['Note'] = $note; $this->request->data['Note']['budget_id'] = $budget['Budget']['id']; $this->request->data['Note']['note_type_id'] = '2'; $this->request->data['Note']['pending_amount'] = $note['amount']; $shares = 1; $tmpDate = $budget['Budget']['begin_date']; while ($shares <= $note['shares']) { $month = CakeTime::format('F', $tmpDate); $this->request->data['Note']['title'] = __n('Share', 'Shares', 1) . ' ' . $shares . ' ' . __($month) . ' ' . $budget['Budget']['title']; $this->request->data['Note']['document_date'] = $tmpDate; $this->request->data['Note']['due_date'] = date(Configure::read('dateFormatSimple'), strtotime($tmpDate . ' +' . $budget['Budget']['due_days'] . ' days')); $this->request->data['Note']['note_status_id'] = '1'; switch ($budget['Budget']['share_periodicity_id']) { case 1: $tmpDate = $tmpDate; break; case 2: $tmpDate = date(Configure::read('dateFormatSimple'), strtotime($tmpDate . ' +1 year')); break; case 3: $tmpDate = date(Configure::read('dateFormatSimple'), strtotime($tmpDate . ' +6 months')); break; case 4: $tmpDate = date(Configure::read('dateFormatSimple'), strtotime($tmpDate . ' +3 months')); break; case 5: $tmpDate = date(Configure::read('dateFormatSimple'), strtotime($tmpDate . ' +1 month')); break; case 6: $tmpDate = date(Configure::read('dateFormatSimple'), strtotime($tmpDate . ' +1 week')); break; default: break; } $this->_addNote(); if ($note['common_reserve_fund'] > 0) { $this->request->data['Note']['pending_amount'] = $note['common_reserve_fund']; $this->request->data['Note']['amount'] = $note['common_reserve_fund']; $this->request->data['Note']['title'] = __('Common Reserve Fund') . ' ' . $shares . ' ' . __($month) . ' ' . $budget['Budget']['title']; $this->_addNote(); } $this->request->data['Note']['amount'] = $note['amount']; $this->request->data['Note']['pending_amount'] = $note['amount']; $shares++; } } $this->Flash->success(__('The notes has been created')); $this->redirect(array('controller' => 'budgets', 'action' => 'view', $this->getPhkRequestVar('budget_id'), '?' => array('condo_id' => $this->getPhkRequestVar('condo_id')))); } $this->Note->Fraction->contain(array('Entity')); $fractions = $this->Note->Fraction->find('all', array('order' => array('Fraction.length' => 'asc', 'Fraction.fraction' => 'asc'), 'conditions' => array('condo_id' => $this->getPhkRequestVar('condo_id')))); $this->set(compact('fractions', 'budget')); }