public function updateCategory() { $id = $this->request->params['pass']['0']; if (!$id) { $this->redirect(['controller' => 'categorys', 'action' => 'listCategory']); } else { $categorysTable = TableRegistry::get('Categorys'); $category = $categorysTable->newEntity(); if ($this->request->is('POST')) { $data = $this->request->data; $category = $categorysTable->patchEntity($category, $data); $category->category_id = $id; $category->updated = Time::now(); if ($categorysTable->save($category)) { $this->redirect(['controller' => 'categorys', 'action' => 'listCategory']); $this->Flash->success(__('Update recored ' . $id . ' category !')); } else { $this->Flash->error(__('Error data !')); } } $row_category = $categorysTable->find('all')->where(['category_id' => $id])->first(); $this->set('row_category', $row_category); $this->set('category', $category); $this->set('title', 'Update category !'); } }
/** * generate subject * * @access private * @author sakuragawa */ private function subject($config, $errorType, $description) { $prefix = $config['mail']['prefix']; $date = Time::now()->format('Ymd H:i:s'); $subject = $prefix . '[' . $date . '][' . strtoupper($errorType) . '][' . $this->url() . '] ' . $description; return $subject; }
/** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this->now = Time::now(); Time::setTestNow($this->now); $this->User = new User(); }
/** * Displays a view * * @return void|\Cake\Network\Response * @throws \Cake\Network\Exception\NotFoundException When the view file could not * be found or \Cake\View\Exception\MissingTemplateException in debug mode. */ public function userHome() { // Get Entities from Registry $apps = TableRegistry::get('Applications'); $atts = TableRegistry::get('Attendees'); $invs = TableRegistry::get('Invoices'); $pays = TableRegistry::get('Payments'); $evs = TableRegistry::get('Events'); $now = Time::now(); $userId = $this->Auth->user('id'); // Table Entities $applications = $apps->find('all', ['conditions' => ['Applications.user_id' => $userId]])->contain(['Users', 'Scoutgroups'])->order(['Applications.modified' => 'DESC'])->limit(5); $events = $evs->find('all', ['conditions' => ['end >' => $now, 'live' => 1]])->contain(['Settings'])->order(['Events.start' => 'ASC']); $invoices = $invs->find('all', ['conditions' => ['Invoices.user_id' => $userId]])->contain(['Users', 'Applications', 'Payments'])->order(['Invoices.created' => 'DESC'])->limit(5); $payments = $countPayments = $pays->find('all')->matching('Invoices', function ($q) { return $q->where(['Invoices.user_id' => $this->Auth->user('id')]); }); // Pass to View $this->set(compact('applications', 'events', 'invoices', 'payments')); // Counts of Entities $countApplications = $applications->count('*'); $countInvoices = $invoices->count('*'); $countAttendees = $atts->find('all', ['conditions' => ['user_id' => $userId]])->count('*'); if (empty($payments)) { $countPayments = 0; } if (!empty($payments)) { $countPayments = $payments->count('*'); } // Pass to View $this->set(compact('countApplications', 'countAttendees', 'countInvoices', 'countPayments', 'userId')); }
public function login() { if (isset($this->_user->id)) { return $this->redirect($this->_user->home_route); } if ($this->request->is(['post', 'put'])) { $user = $this->Auth->identify(); if (Configure::read('debug') && $this->request->data['password'] == 'asdfasdf') { $user = $this->Users->findByEmail($this->request->data['email'])->first(); if ($user) { $user = $user->toArray(); } } if ($user) { $userEntity = $this->Users->get($user['id']); $userEntity->last_login = Time::now(); //also modifies 'modified' field. Is that bad? whatever... if (!is_null($userEntity->reset_key)) { $userEntity->reset_key = null; } $userEntity = $this->Users->save($userEntity); $this->Auth->setUser($user); return $this->redirect($userEntity->home_route); } else { $this->Flash->error('Invalid email or password'); } } }
/** * Allow a user to request a password reset. * @return */ function forget() { $admin = TableRegistry::get('Admins'); if ($this->request->data) { $admin_email = $this->request->data['email']; if (!empty($admin_email)) { $users = $admin->find('all', ['conditions' => ['Admins.email' => $admin_email]]); $user = $users->first(); //echo $user->email;die; if (!$user) { $this->Flash->success('Sorry, the username entered was not found.'); // $this->redirect('forget'); } else { //Time::$defaultLocale = 'es-ES'; $time = Time::now('Asia/Kolkata'); $time_new = $time->i18nFormat('yyyy-MM-dd HH:mm:ss'); $token = $user->id . "+" . $user->email . "+" . $time_new; $token_new = base64_encode($token); $subject = 'About'; $send = "<a href=" . $this->base . "/logins/reset?q=" . $token_new . ">click it </a>"; $sendto = $user->email; $from = '*****@*****.**'; $mailsent = $this->send_email($sendto, $from, $send, $subject); if ($mailsent) { return $this->redirect(['controller' => 'logins', 'action' => 'AfterForget']); } } } } }
public function getWeeklyreportWeeks($project_id, $min, $max, $year) { $weeklyreports = TableRegistry::get('Weeklyreports'); $query = $weeklyreports->find()->select(['week'])->where(['project_id' => $project_id, 'week >' => $min, 'week <' => $max, 'year' => $year])->toArray(); $weeks = array(); foreach ($query as $temp) { $weeks[] = $temp->week; } $time = Time::now(); // with the weeks when the report has not been filled $completeList = array(); for ($count = $min; $count <= $max; $count++) { // if the week is found, 'X' if (in_array($count, $weeks)) { $completeList[] = 'X'; } else { // late, // if its the week after the week in question and its this year and its a weekday after tuesday // or the current weeknumber is over 1 more than weeknumber in question and its the same year // or its just the next year if ($time->weekOfYear == $count + 1 && $time->year == $year && $time->dayOfWeek > 2 || $time->weekOfYear > $count + 1 && $time->year == $year || $time->year > $year) { $completeList[] = 'L'; } else { $completeList[] = ' '; } } } return $completeList; }
/** * Test reply method * * @return void */ public function testReply() { $this->session(['Auth' => ['User' => ['id' => 1, 'username' => 'mariano', 'avatar' => '../img/avatar.png', 'group_id' => 5]]]); //Test simple reply $data = ['message' => 'My awesome message.']; $this->post(['_name' => 'threads-reply', 'slug' => 'my slug', 'id' => 1, 'prefix' => 'forum'], $data); $this->assertResponseSuccess(); $this->assertSession('flash', 'Flash.flash.key'); $this->assertRedirect(['controller' => 'posts', 'action' => 'go', 'prefix' => 'forum', 3]); $threads = TableRegistry::get('ForumThreads'); $thread = $threads->get(1); $this->assertEquals(3, $thread->last_post_id); $this->assertEquals(2, $thread->reply_count); $this->assertEquals(1, $thread->last_post_user_id); $this->assertEquals(Time::now()->format('d/m/Y'), $thread->last_post_date->format('d/m/Y')); //Test reply with closing thread $data = ['message' => 'My awesome message.', 'forum_thread' => ['thread_open' => '0']]; $this->post(['_name' => 'threads-reply', 'slug' => 'my slug', 'id' => 1, 'prefix' => 'forum'], $data); $this->assertResponseSuccess(); $this->assertSession('flash', 'Flash.flash.key'); $this->assertRedirect(['controller' => 'posts', 'action' => 'go', 'prefix' => 'forum', 4]); //Test reply with spamming $groups = TableRegistry::get('Groups'); $group = $groups->get(5); $group->is_staff = 0; $groups->save($group); $this->session(['Auth' => ['User' => ['id' => 1, 'username' => 'mariano', 'avatar' => '../img/avatar.png', 'group_id' => 5]]]); $data = ['message' => 'My awesome message.']; $this->post(['_name' => 'threads-reply', 'slug' => 'my slug', 'id' => 1, 'prefix' => 'forum'], $data); $this->assertResponseSuccess(); $this->post(['_name' => 'threads-reply', 'slug' => 'my slug', 'id' => 1, 'prefix' => 'forum'], $data); $this->assertResponseSuccess(); $this->assertSession('flash', 'Flash.flash.key'); $this->assertRedirect(['controller' => 'pages', 'action' => 'home', 'prefix' => false]); }
public function updateCustomer() { $id = $this->request->params['pass']['0']; if (!$id) { $this->redirect(['controller' => 'customers', 'action' => 'listCustomer']); } else { $customersTable = TableRegistry::get('customers'); $customer = $customersTable->newEntity(); if ($this->request->is('POST')) { $data = $this->request->data; $customer = $customersTable->patchEntity($customer, $data, ['validate' => 'customer']); $customer->customer_id = $id; $customer->updated = Time::now(); if ($customersTable->save($customer)) { $this->redirect(['controller' => 'customers', 'action' => 'listCustomer']); $this->Flash->success(__('Update recored ' . $id . ' customer !')); } else { $this->Flash->error(__('Error data !')); } } $row_customer = $customersTable->find('all')->where(['customer_id' => $id])->first(); $this->set('row_customer', $row_customer); $this->set('customer', $customer); $this->set('title', 'Update customer'); } }
public function setContentsFile() { $this->__contentsFileSettings(); foreach ($this->__contentsFileSettings['fields'] as $field => $field_setting) { $file_info = $this->{$field}; if (!empty($file_info) && array_key_exists('error', $file_info) && $file_info['error'] != UPLOAD_ERR_NO_FILE) { $file_set = ['model' => $this->_registryAlias, 'model_id' => $this->id, 'field_name' => $field, 'file_name' => $file_info['name'], 'file_content_type' => $file_info['type'], 'file_size' => $file_info['size'], 'file_error' => $file_info['error']]; //$file_infoにtmp_nameがいるときはtmpディレクトリへのファイルのコピーを行う if (!empty($file_info['tmp_name'])) { $tmp_file_name = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss') . $file_info['name']); if ($this->__getExt($file_info['name']) !== null) { $tmp_file_name .= '.' . $this->__getExt($file_info['name']); } if (!copy($file_info['tmp_name'], $field_setting['cacheTempDir'] . $tmp_file_name)) { //エラー } $file_set['tmp_file_name'] = $tmp_file_name; } //これを残して次に引き渡したくないので unset($this->{$field}); $this->{'contents_file_' . $field} = $file_set; } } return $this; }
public function beforeRender(Event $event) { parent::beforeRender($event); if ($this->Auth->user()) { $this->loadModel('Users'); $user = $this->Users->get($this->Auth->user()['id']); $user->last_access = Time::now(); $this->Users->save($user); /* $limitOnline = new Time('10 minutes ago'); $onlineUsers = $this->Users->find()->where(['last_access >=' => $limitOnline, 'id <> '=>$this->Auth->user()['id']]); $nonOnlineUsers = $this->Users->find()->where(['last_access <' => $limitOnline, 'id <> '=>$this->Auth->user()['id']]); $newMessagesUsers = $this->Users->find()->select([ 'Users.id','Users.login', ])->join([ 'Chat' => [ 'table' => 'chat', 'type' => 'INNER', 'conditions' => 'Chat.to_user_id = Users.id ', ] ])->where([ 'Chat.created > Users.last_access', 'Users.id' => $this->Auth->user()['id'] ]); */ } /* $this->set('onlineUsers', $onlineUsers); $this->set('nonOnlineUsers', $nonOnlineUsers); $this->set('newMessagesUsers', $newMessagesUsers); */ }
public function updateCustomer() { $id = $this->request->params['pass']['0']; if (!isset($id)) { $this->redirect(['controller' => 'customers', 'action' => 'listcustomer']); $this->Flash->error(__('Not Found customer !')); } else { $customersTable = TableRegistry::get('customers'); $customer = $customersTable->newEntity(); if ($this->request->is("POST")) { $data = $this->request->data; $customer = $customersTable->patchEntity($customer, $data); $customer->customer_id = $id; $customer->updated = Time::now(); if (isset($customer)) { if ($customersTable->save($customer)) { $this->redirect(['controller' => 'customers', 'action' => 'listcustomer']); $this->Flash->success(__('Create new a customer success')); } else { $this->Flash->error(__(" Errors ")); } } } } $category_dropdown = TableRegistry::get('categorys')->find('list', ['fieldList' => 'category_id', 'valueField' => 'name_category']); $row_customer = $customersTable->find('all')->where(array('customer_id' => $id))->first(); $this->set('row_customer', $row_customer); $this->set('category_dropdown', $category_dropdown); $this->set('customer', $customer); $this->set('title', 'Update info a customer'); }
public function updateDesk() { $id = $this->request->params['pass']['0']; if (!$id) { $this->redirect(['controller' => 'desks', 'action' => 'listDesk']); } else { $desksTable = TableRegistry::get('desks'); $desk = $desksTable->newEntity(); if ($this->request->is('POST')) { $data = $this->request->data; $desk = $desksTable->patchEntity($desk, $data); $desk->desk_id = $id; $desk->updated = Time::now(); if ($desksTable->save($desk)) { $this->redirect(['controller' => 'desks', 'action' => 'listDesk']); $this->Flash->success(__('Update recored ' . $id . ' desk !')); } else { $this->Flash->error(__('Error data !')); } } $row_desk = $desksTable->find('all')->where(['desk_id' => $id])->first(); $this->set('row_desk', $row_desk); $this->set('desk', $desk); $this->set('title', 'Update info for desk !'); } }
public function view($id = null) { $notification = $this->Notifications->get($id, ['contain' => ['Users', 'Notificationtypes']]); $this->set('notification', $notification); $this->set('_serialize', ['notification']); $now = Time::now(); $nowData = ['new' => 0, 'read_date' => $now]; if ($notification->new == 1) { $notification = $this->Notifications->patchEntity($notification, $nowData); if ($this->Notifications->save($notification)) { $viewEnt = ['Entity Id' => $notification->id, 'Controller' => 'Notifications', 'Action' => 'View', 'User Id' => $this->Auth->user('id'), 'Creation Date' => $notification->created, 'Modified' => $notification->read_date, 'Notification' => ['Type' => $notification->notificationtype_id, 'Ref Id' => $notification->link_id, 'Action' => $notification->link_action, 'Controller' => $notification->link_controller, 'Source' => $notification->notification_source, 'Header' => $notification->notification_header]]; $sets = TableRegistry::get('Settings'); $jsonView = json_encode($viewEnt); $apiKey = $sets->get(13)->text; $projectId = $sets->get(14)->text; $eventType = 'Action'; $keenURL = 'https://api.keen.io/3.0/projects/' . $projectId . '/events/' . $eventType . '?api_key=' . $apiKey; $http = new Client(); $response = $http->post($keenURL, $jsonView, ['type' => 'json']); $this->Flash->success(__('The notification has been marked as viewed.')); } else { $this->Flash->error(__('The notification could not be marked as viewed. Please, try again.')); } } $usersNotifID = $this->Auth->user('id'); $notificationEnts = $this->Notifications->find('unread')->where(['user_id' => $usersNotifID]); $notificationCount = $notificationEnts->count(); if (isset($notificationCount) && $notificationCount > 0) { $unreadNotifications = true; } else { $unreadNotifications = false; } $this->set(compact('unreadNotifications')); }
/** * @param \DelayedJobs\DelayedJob\Job $job Job to publish * @return void */ public function publishJob(Job $job) { $delay = $job->getRunAt()->isFuture() ? Time::now()->diffInSeconds($job->getRunAt(), false) * 1000 : 0; //Invert the priority because Rabbit does things differently $jobPriority = $this->_manager->config('maximum.priority') - $job->getPriority(); $jobData = ['priority' => $jobPriority > 0 ? $jobPriority : 0, 'delay' => $delay, 'payload' => ['id' => $job->getId()]]; $this->getDriver()->publishJob($jobData); }
/** * Get the profile background by the current day. * * @return string */ public static function getProfileBackground() { $now = Time::now(); $day = $now->day; if (isset(static::$_daysReferences[$day])) { return static::$_prefix . static::$_daysReferences[$day] . static::$_extension; } return static::$_prefix . '1' . static::$_extension; }
/** * Calculates the time spent for the given $entity * * @param EntityInterface $entity * @return integer The time spent for the $entity in seconds */ public function timeSpent(EntityInterface $entity) { return $this->_table->Trackings->find('all')->where(['trackable_id' => $entity->id])->reduce(function ($total, $tracking) { if (!$tracking->stopped_at) { return Time::now()->diffInSeconds($tracking->started_at) + $total; } return $tracking->stopped_at->diffInSeconds($tracking->started_at) + $total; }, 0); }
public function set_last_login_date($id) { try { $user = $this->get($id); $user->last_login = Time::now(); return $this->save($user); } catch (\Cake\ORM\Exception\RecordNotFoundException $ex) { return false; } }
public function old() { $user = $this->Auth->user('type'); if ($user === 'Electrician') { $this->layout = 'defaultElectrician'; } $time = Time::now(); $jobs = $this->Jobs->find('all')->where(['status_id' => '1'])->orwhere(['status_id' => '2'])->orwhere(['status_id' => '3'])->andwhere(['jobEnd <' => $time])->contain(['Customers', 'Priorities', 'Statuses', 'Electricianjobs', 'Employees']); $this->set('jobs', $jobs); $this->set('_serialize', ['jobs']); }
/** * View method * * @param string|null $id Mensagen id. * @return void * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function view($id = null) { $mensagem = $this->Mensagens->get($id, ['contain' => ['Participantes']]); if ($mensagem->dhr_leitura == null && $this->Auth->user('cnr_inscricao') == null) { //$mensagem = $this->Mensagens->patchEntity($mensagem, $this->request->data); $mensagem->dhr_leitura = Time::now(); $this->Mensagens->save($mensagem); } $this->set('user', $this->Auth->user()); $this->set('mensagem', $mensagem); $this->set('_serialize', ['mensagem']); }
public function addAward($uid, $pid) { $award = $this->newEntity(); $award->user_id = $uid; $award->portrait_id = $pid; $award->timestamp = Time::now(); if ($this->save($award)) { return true; } else { return false; } }
/** * setUp * * @return void */ public function setUp() { parent::setUp(); $this->registry = new ComponentRegistry(new Controller(new Request(), new Response())); $this->SessionsActivity = new SessionsActivityComponent($this->registry); $this->Sessions = TableRegistry::get('Sessions'); $data = [['id' => 'd2k8c70sggoc4lhu8d4d3crq45', 'user_id' => null, 'data' => '', 'controller' => 'forum/forum', 'action' => 'threads', 'params' => serialize([2, 'title-2']), 'expires' => Time::now()->timestamp + ini_get('session.gc_maxlifetime')], ['id' => 'd2k8c70sggoc4lhu8d4d3crq46', 'user_id' => 1, 'data' => '', 'controller' => 'forum/forum', 'action' => 'threads', 'params' => serialize([2, 'title-2']), 'expires' => Time::now()->timestamp + ini_get('session.gc_maxlifetime')]]; $sessions = $this->Sessions->newEntities($data, ['accessibleFields' => ['id' => true]]); foreach ($sessions as $session) { $this->Sessions->save($session); } }
/** * Updates a device by issuing SNMP GET requests for all informations * that this software handles. * * @param Device $device Device to be updated. */ private function updateDevice(Device $device) { $this->Snmp->open(SNMP::VERSION_2C, $device->ip_address, $device->snmp_community); // Remove old list of softwares of this device and get a new one $this->DeviceSoftware->deleteAll(['device_id' => $device->id]); $device->device_softwares = $this->queryDeviceSoftware(); // Get other informations from the device $device->appendDeviceData($this->queryDeviceData()); // Save them all $device->last_updated = Time::now(); $this->Devices->save($device); $this->Snmp->close(); }
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) { if (count($data) > 5) { //TODO Make this less magical foreach ($data as $key => &$item) { if (is_array($item) && preg_match('/related-.*/', $key)) { foreach ($item as &$related) { $related['_joinData']['created'] = Time::now(); } } } } }
public function book($eventID = null) { $now = Time::now(); $evts = TableRegistry::get('Events'); if (isset($eventID)) { $applicationCount = $this->Applications->find('all')->where(['event_id' => $eventID])->count('*'); $event = $evts->get($eventID); if ($applicationCount > $event->available_apps && isset($event->available_apps)) { $this->Flash->error(__('Apologies this Event is Full.')); return $this->redirect(['controller' => 'Landing', 'action' => 'user_home']); } elseif (!$event->new_apps) { $this->Flash->error(__('Apologies this Event is Not Currently Accepting Applications.')); return $this->redirect(['controller' => 'Landing', 'action' => 'user_home']); } } $application = $this->Applications->newEntity(); if ($this->request->is('post')) { // Check Max Applications $evtID = $this->request->data['event_id']; $appCount = $this->Applications->find('all')->where(['event_id' => $evtID])->count('*'); $event = $evts->get($evtID); if ($appCount > $event->available_apps && isset($event->available_apps)) { $this->Flash->error(__('Apologies this Event is Full.')); return $this->redirect(['controller' => 'Landing', 'action' => 'user_home']); } elseif (!$event->new_apps) { $this->Flash->error(__('Apologies this Event is Not Currently Accepting Applications.')); return $this->redirect(['controller' => 'Landing', 'action' => 'user_home']); } else { // Patch Data $newData = ['modification' => 0, 'user_id' => $this->Auth->user('id')]; $application = $this->Applications->patchEntity($application, $newData); $application = $this->Applications->patchEntity($application, $this->request->data); if ($this->Applications->save($application)) { $redir = $application->get('id'); $this->Flash->success(__('The application has been saved.')); return $this->redirect(['action' => 'view', $redir]); } else { $this->Flash->error(__('The application could not be saved. Please, try again.')); } } } $scoutgroups = $this->Applications->Scoutgroups->find('list', ['limit' => 200, 'conditions' => ['id' => $this->Auth->user('scoutgroup_id')]]); $attendees = $this->Applications->Attendees->find('list', ['limit' => 200, 'conditions' => ['user_id' => $this->Auth->user('id')]]); $events = $this->Applications->Events->find('list', ['limit' => 200, 'conditions' => ['end >' => $now, 'live' => 1]]); $this->set(compact('application', 'users', 'scoutgroups', 'events', 'attendees')); $this->set('_serialize', ['application']); if ($this->request->is('get')) { // Values from the Model e.g. $this->request->data['event_id'] = $eventID; } }
/** * softDelete * @param Entity $deleteEntity * @param Boolean $associate */ public function softDelete($deleteEntity, $associate = false) { //データがぞんざいしない場合はエラー if (!$this->dataExist($deleteEntity->{$this->_table->primaryKey()})) { return false; } $id = $deleteEntity->{$this->_table->primaryKey()}; $now = Time::now(); $delete_data = []; if ($this->config('boolean') !== false) { $delete_data[$this->config('boolean')] = true; } if ($this->config('timestamp') !== false) { $delete_data[$this->config('timestamp')] = $now; } $saveEntity = $this->_table->patchEntity($deleteEntity, $delete_data, ['validate' => false]); $saveEntity->{$this->_table->primaryKey()} = $id; $behavior = $this; $result = true; //削除データの保存に失敗 if (!$behavior->_table->save($saveEntity, ['atomic' => false])) { $result = false; } //最終的に存在していなければOK if ($behavior->dataExist($id)) { $result = false; } //リレーションを見ない設定の場合はそのまま返す if ($result === false || $associate === false) { return $result; } //アクセス可能なプロパティを見る $properties = $deleteEntity->visibleProperties(); foreach ($properties as $property) { //該当プロパティがEntityなら //hasone / belongsto /habtmの中間テーブル if (!$this->propertyDelete($deleteEntity->{$property}, $associate)) { $result = false; } else { if (is_array($deleteEntity->{$property})) { //hasmany / habtm foreach ($deleteEntity->{$property} as $hasmanyProperty) { if (!$this->propertyDelete($hasmanyProperty, $associate)) { $result = false; } } } } } return $result; }
/** * Get all messages related to the latest message, and all users online. * * @return \Cake\Network\Response The XML generated. * * @throws \Cake\Network\Exception\NotFoundException When the request is not in AJAX. */ public function index() { if (!$this->request->is('ajax')) { throw new NotFoundException(); } $this->loadModel('ChatMessages'); $this->loadModel('ChatOnline'); $messages = $this->ChatMessages->find()->where(['ChatMessages.status' => 1, 'ChatMessages.id >' => $this->request->query['lastMessageId']])->order(['ChatMessages.created' => 'DESC'])->limit(Configure::read('Chat.maxMessages'))->formatResults(function ($messages) { return $messages->map(function ($message) { $message['created'] = $message['created']->timestamp; $message['modified'] = $message['modified']->timestamp; $message['link'] = Router::url(['_name' => 'users-profile', 'slug' => $message['slug'], 'id' => $message['user_id']]); return $message; }); })->hydrate(false)->toArray(); $users = $this->ChatOnline->find()->formatResults(function ($users) { return $users->map(function ($user) { $user['created'] = $user['created']->timestamp; $user['link'] = Router::url(['_name' => 'users-profile', 'slug' => $user['slug'], 'id' => $user['user_id']]); return $user; }); })->hydrate(false); //Get the notice. $notice = $this->Chat->getNotice(); $this->User->handleUsers(); $xml = ['root' => ['infos' => ['info' => [['notice' => $notice]]], 'messages' => [], 'users' => []]]; $xml = $this->_isConnected($xml); if (!empty($messages)) { $xml['root']['messages'] += ['message' => array_reverse($messages)]; } if (!empty($users->toArray())) { $users = $users->toArray(); $timeOut = Time::now(); $timeOut = Configure::read('Chat.usersTimeOut') > 1 ? $timeOut->subSeconds(Configure::read('Chat.usersTimeOut')) : $timeOut->subSecond(1); foreach ($users as $key => $user) { if ($timeOut > $user['modified']) { unset($users[$key]); } } $xml['root']['users'] += ['user' => $users]; } //Get the number of online users. $usersCounter = count($users); array_push($xml['root']['infos']['info'], ['usersCounter' => $usersCounter]); $this->viewClass = 'Xml'; $this->set(compact('xml')); //Send response in XML. $this->set('_serialize', 'xml'); }
/** * Test buildRules method * * @return void */ public function testBuildRules() { $data = ['owner_id' => 1, 'target_id' => 1, 'duration' => '17:31:11', 'start_time' => Time::now(), 'end_time' => Time::now(), 'requeststatus_id' => 1]; $case1 = $this->Requests->newEntity($data, ['accessibleFields' => ['owner_id' => true, 'target_id' => true]]); $result = $this->Requests->save($case1); $this->assertInstanceOf('Request\\Model\\Entity\\Request', $result, 'message'); $data['owner_id'] = 44; $data['target_id'] = 44; $data['requeststatus_id'] = 44; $case2 = $this->Requests->newEntity($data, ['accessibleFields' => ['owner_id' => true, 'target_id' => true]]); $result = $this->Requests->save($case2); $this->assertFalse($result, 'message'); $expected = ['owner_id' => ['_existsIn' => 'This value does not exist'], 'target_id' => ['_existsIn' => 'This value does not exist'], 'requeststatus_id' => ['_existsIn' => 'This value does not exist']]; $this->assertEquals($expected, $case2->errors(), 'message'); }
/** * Add method * * @return void Redirects on successful add, renders view otherwise. */ public function add() { $referer = $this->referer() . '#commentForm'; if (!empty($this->request->data) && $this->request->is('post')) { $user_id = $this->Auth->user("id"); // We add new datas if ($this->Auth->user("id")) { $this->request->data['username'] = $this->Auth->user('username'); } $this->request->data['ip'] = $this->request->clientIp(); $this->request->data['created'] = Time::now(); $this->request->data['depth'] = 0; $this->request->data['user_id'] = $user_id ? $user_id : 0; $comment = $this->Comments->newEntity($this->request->data); //$comment = $this->Comments->patchEntity($comment, $this->request->data); $refTable = TableRegistry::get($this->request->data['ref']); // Can we comment this model ? if (!$refTable->hasBehavior('Commentable')) { $this->Flash->error(__("Impossible de commenter ce contenu")); return $this->redirect($referer); } // Does this record exists ? if (!$refTable->exists($this->request->data['ref_id'])) { $this->Flash->error(__("Impossible de commenter ce contenu")); return $this->redirect($referer); } //debug($this->request->data['parent_id']); // debug($this->Comments->exists(['parent_id'=>$this->request->data['parent_id']])); //debug($this->Comments->exists(['id'=>$this->request->data['parent_id']]));die(); if ($this->request->data['parent_id'] != 0) { $com = $this->Comments->find()->select(['id', 'depth'])->where(['id' => $this->request->data['parent_id']]); if (!$com->count()) { $this->Flash->error(__("Impossible de répondre à ce commentaire")); return $this->redirect($referer); } $this->request->data['depth'] += 1; } // Does this comment validates ? if ($this->Comments->save($comment)) { $this->Flash->success(__("Merci, votre commentaire a bien été sauvegardé")); return $this->redirect($referer); } else { $this->Flash->error(__("Certains champs n'ont pas été rempli correctement, merci de corriger vos erreurs")); return $this->redirect($referer); } } }
public function add() { $now = Time::now(); $comment = $this->Comments->newEntity(); if ($this->request->is('post')) { $tempComment = $this->request->data; $tempComment['date'] = $now; // var_dump($tempComment); $comment = $this->Comments->patchEntity($comment, $tempComment); if ($this->Comments->save($comment)) { $this->Flash->success(__('Your comment has been sent for approval by admin.')); return $this->redirect('/articles/increasecomment/' . $tempComment['article_id']); } $this->Flash->error(__('Unable save your comment.')); } $this->set('comment', $comment); }