Beispiel #1
1
 /**
  * Custom finder method, returns recent to-do's based on status
  *
  * @param Query $query  cakephp query object
  * @param array $options list of options
  * @return query $query cakephp query object
  */
 public function findRecent(Query $query, array $options = ['status' => 0])
 {
     return $query->where(['is_done' => $options['status']])->order(['updated' => 'DESC'])->formatResults(function ($results, $query) {
         return $results->map(function ($row) {
             $timeCreated = new Time($row->created);
             $timeUpdated = new Time($row->updated);
             $row->created = $timeCreated->timeAgoInWords();
             $row->updated = $timeUpdated->timeAgoInWords();
             $row->todo = htmlspecialchars($row->todo);
             return $row;
         });
     });
 }
Beispiel #2
0
 /**
  * @param string $format
  * @param int|string|DateTime $date
  * @return mixed|string
  */
 public function persianDate($date, $format = 'Y-m-d H:i:s')
 {
     $time = new Time($date);
     //        $unix = $time->i18nFormat(\IntlDateFormatter::FULL, 'Asia/Tehran', 'en_US')->toUnixString();
     //        debug($unix);die;
     return Persian::date($format, (int) $time->toUnixString(), '', 'Asia/Tehran', 'en');
 }
 /**
  * testEnqueue method.
  */
 public function testEnqueue()
 {
     $count = $this->EmailQueue->find()->count();
     $this->EmailQueue->enqueue('*****@*****.**', array('a' => 'variable', 'some' => 'thing'), array('subject' => 'Hey!', 'headers' => ['X-FOO' => 'bar', 'X-BAZ' => 'thing']));
     $this->assertEquals(++$count, $this->EmailQueue->find()->count());
     $result = $this->EmailQueue->find()->last()->toArray();
     $expected = array('email' => '*****@*****.**', 'subject' => 'Hey!', 'template' => 'default', 'layout' => 'default', 'format' => 'both', 'template_vars' => array('a' => 'variable', 'some' => 'thing'), 'sent' => false, 'locked' => false, 'send_tries' => 0, 'config' => 'default', 'headers' => array('X-FOO' => 'bar', 'X-BAZ' => 'thing'), 'from_name' => null, 'from_email' => null);
     $sendAt = new Time($result['send_at']);
     unset($result['id'], $result['created'], $result['modified'], $result['send_at']);
     $this->assertEquals($expected, $result);
     $this->assertEquals(gmdate('Y-m-d H'), $sendAt->format('Y-m-d H'));
     $date = new Time();
     $this->EmailQueue->enqueue(array('*****@*****.**', '*****@*****.**'), array('a' => 'b'), array('send_at' => $date, 'subject' => 'Hey!'));
     $this->assertEquals($count + 2, $this->EmailQueue->find()->count());
     $email = $this->EmailQueue->find()->where(array('email' => '*****@*****.**'))->first();
     $this->assertEquals(array('a' => 'b'), $email['template_vars']);
     $this->assertEquals($date, $email['send_at']);
     $email = $this->EmailQueue->find()->where(array('email' => '*****@*****.**'))->first();
     $this->assertEquals(array('a' => 'b'), $email['template_vars']);
     $this->assertEquals($date, $email['send_at']);
     $this->EmailQueue->enqueue('*****@*****.**', array('a' => 'c'), array('subject' => 'Hey', 'send_at' => $date, 'config' => 'other', 'template' => 'custom', 'layout' => 'email'));
     $email = $this->EmailQueue->find()->last();
     $this->assertEquals(array('a' => 'c'), $email['template_vars']);
     $this->assertEquals($date, $email['send_at']);
     $this->assertEquals('other', $email['config']);
     $this->assertEquals('custom', $email['template']);
     $this->assertEquals('email', $email['layout']);
 }
Beispiel #4
0
 public function post($body, $type, $id)
 {
     if (!$this->config('enabled')) {
         return false;
     }
     // Find out when the last time an announce was sent for this entity
     $result = $this->Slack->findAllByEntityAndEntityId($type, $id)->first();
     if ($result) {
         $last_update = $result->modified;
     } else {
         $result = $this->Slack->newEntity();
         $result->entity = $type;
         $result->entity_id = $id;
         $last_update = new Time('1 year ago');
     }
     // Prevent sending out an update too soon
     if ($last_update->wasWithinLast($this->config('debounce'))) {
         return false;
     }
     $http = new Client();
     $data = (object) ['text' => $body];
     $response = $http->post($this->config('webhook_url'), ['payload' => json_encode($data, JSON_PRETTY_PRINT)]);
     $result->messages++;
     $this->Slack->save($result);
 }
 /**
  * {@inheritDoc}
  */
 public function display($fieldname, $dateValue, $model = null)
 {
     if (!is_object($dateValue)) {
         $dateValue = new Time($dateValue);
     }
     $dateValue->setTimezone('Europe/Berlin');
     return $dateValue->nice();
 }
 public function jobsPerSecond($conditions = [], $field = 'created', $time_range = '-1 hour')
 {
     $start_time = new Time($time_range);
     $current_time = new Time();
     $second_count = $current_time->diffInSeconds($start_time);
     $conditions[$this->aliasField($field) . ' > '] = $start_time;
     $count = $this->find()->where($conditions)->count();
     return $count / $second_count;
 }
Beispiel #7
0
 public static function jalaliAsiaTehranToGregorianUTC($date, $format = 'Y-m-d H:i:s')
 {
     $defaultTimezone = date_default_timezone_get();
     date_default_timezone_set('Asia/Tehran');
     $gregorianDate = formated_to_gregorian($date);
     $time = new Time($gregorianDate);
     date_default_timezone_set($defaultTimezone);
     return $time->setTimezone('UTC')->format($format);
 }
 /**
  * __construct to set up all properties and call parent
  *
  * @param string $fileName to initialize Environment file
  */
 public function __construct($fileName)
 {
     parent::__construct(Configure::read('CakePostman.environments.path') . $fileName);
     $environmentData = json_decode($this->read(), true);
     $this->environmentName = $environmentData['name'];
     $this->url = $environmentData['values'][0]['value'];
     $time = new Time($this->lastChange());
     $this->created = $time->nice();
 }
 /**
  * Test index method unauthorized
  *
  * @return void
  */
 public function testIndexAuthorizedWithPremium()
 {
     $Users = TableRegistry::get('Users');
     $user = $Users->get(1);
     $time = new Time('+5 days');
     $user->end_subscription = $time;
     $Users->save($user);
     $this->session(['Auth' => ['User' => ['id' => 1, 'username' => 'mariano', 'avatar' => '../img/avatar.png', 'group_id' => 5]]]);
     $this->get(['controller' => 'premium', 'action' => 'index']);
     $this->assertResponseOk();
     //We can't test the flash test due to the translation system.
     $this->assertResponseContains('infobox-primary');
     $this->assertResponseContains($time->format('H:i:s d-m-Y'));
 }
Beispiel #10
0
 public function beforeFilter(Event $event)
 {
     parent::beforeFilter($event);
     $session = $this->request->session();
     $lang = 'en';
     if (isset($this->request->params['lang'])) {
         $lang = $this->request->params['lang'];
     } else {
         if ($session->check('Config.language')) {
             $lang = $session->read('Config.language');
         }
     }
     $session->write('Config.language', $lang);
     // Change current language by post request
     if ($this->request->is('post') && isset($this->request->data['language'])) {
         $newLang = $this->request->data['language'];
         $transUrl = $this->translateUrl($newLang);
         $this->redirect($transUrl);
     }
     $this->set('lang', $lang);
     $this->set('controller', $this->name);
     I18n::locale($lang);
     Time::setToStringFormat('YYYY-MM-dd HH:mm:ss');
     Type::build('datetime')->useLocaleParser();
     $this->Auth->config(['unauthorizedRedirect' => false]);
     $this->Auth->allow(['login', 'init']);
     $user = $this->Auth->user();
     if (isset($user)) {
         $username = $user['username'];
         $this->set(['is_authorized' => true, 'username' => $username]);
     } else {
         $this->set('is_authorized', false);
     }
 }
Beispiel #11
0
 /**
  * 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;
 }
Beispiel #12
0
 /**
  * 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 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');
     }
 }
    /**
     * Renders a date time widget.
     *
     * @param array $data Data to render with.
     * @param \Cake\View\Form\ContextInterface $context The current form context.
     * @return string A generated select box.
     * @throws \RuntimeException When option data is invalid.
     */
    public function render(array $data, ContextInterface $context)
    {
        $id = $data['id'];
        $name = $data['name'];
        $val = $data['val'];
        $type = $data['type'];
        $required = $data['required'] ? 'required' : '';
        $disabled = isset($data['disabled']) && $data['disabled'] ? 'disabled' : '';
        $role = isset($data['role']) ? $data['role'] : 'datetime-picker';
        $format = null;
        $locale = isset($data['locale']) ? $data['locale'] : I18n::locale();
        $timezoneAware = Configure::read('CrudView.timezoneAwareDateTimeWidget');
        $timestamp = null;
        $timezoneOffset = null;
        if (isset($data['data-format'])) {
            $format = $this->_convertPHPToMomentFormat($data['data-format']);
        }
        if (!$val instanceof DateTimeInterface && !empty($val)) {
            $val = $type === 'date' ? Time::parseDate($val) : Time::parseDateTime($val);
        }
        if ($val) {
            if ($timezoneAware) {
                $timestamp = $val->format('U');
                $dateTimeZone = new DateTimeZone(date_default_timezone_get());
                $timezoneOffset = $dateTimeZone->getOffset($val) / 60;
            }
            $val = $val->format($type === 'date' ? 'Y-m-d' : 'Y-m-d H:i:s');
        }
        if (!$format) {
            $format = $type === 'date' ? 'L' : 'L LT';
        }
        $widget = <<<html
            <div class="input-group {$type}">
                <input
                    type="text"
                    class="form-control"
                    name="{$name}"
                    value="{$val}"
                    id="{$id}"
                    role="{$role}"
                    data-locale="{$locale}"
                    data-format="{$format}"
html;
        if ($timezoneAware && isset($timestamp, $timezoneOffset)) {
            $widget .= <<<html
                    data-timestamp="{$timestamp}"
                    data-timezone-offset="{$timezoneOffset}"
html;
        }
        $widget .= <<<html
                    {$required}
                    {$disabled}
                />
                <label for="{$id}" class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </label>
            </div>
html;
        return $widget;
    }
 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 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');
         }
     }
 }
 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'));
 }
 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 !');
     }
 }
 /**
  * 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 signup()
 {
     if ($this->request->is('post')) {
         $table = TableRegistry::get('Users');
         $salt = uniqid(mt_rand(), true);
         $user = $table->newEntity(['name' => $this->request->data('name'), 'email' => $this->request->data('email'), 'password' => pbkdf2("sha256", $this->request->data('password'), $salt), 'salt' => $salt, 'date_created' => Time::createFromTimestamp(time())]);
         if ($user->isValid() && $this->request->data('password') == $this->request->data('confirm_password') && $table->save($user)) {
             $key = $user->makeKey();
             $this->Cookie->write('ta_login_id', $user->id);
             $this->Cookie->write('ta_login_email', $user->email);
             $this->Cookie->write('ta_login_key', $key);
             return $this->redirect("/");
         } else {
             if ($user->isValid()) {
                 if ($this->request->data('password') == $this->request->data('confirm_password')) {
                     $this->Flash->set('The email you entered is already in use.', ['element' => 'error']);
                 } else {
                     $this->Flash->set('The password and confirmation you entered did not match.', ['element' => 'error']);
                 }
             } else {
                 $this->Flash->set('Please make sure your email is valid and name is longer than three characters.', ['element' => 'error']);
             }
         }
     }
     $this->viewBuilder()->layout("auth");
 }
 public function beforeFilter(Event $event)
 {
     parent::beforeFilter($event);
     Time::$defaultLocale = 'en-CA';
     Time::setToStringFormat('YYYY-MM-dd');
     $this->Session = $this->request->session();
     $this->set('Session', $this->Session);
     $this->_icons = $this->Utilities->setIcons();
     $this->set('icons', $this->_icons);
     $title = $this->Utilities->setDefaultTitle();
     $breadcrumbs = $this->Utilities->setDefaultBreadcrumbs();
     $this->set(compact('title', 'breadcrumbs'));
     if (empty($this->request->params['prefix'])) {
         $this->Auth->allow();
         $this->viewBuilder()->layout('public');
     }
     // Set the user logged in
     if (!is_null($this->Auth->user('id'))) {
         $Users = TableRegistry::get('Users');
         $this->_user = $Users->get($this->Auth->user('id'));
         $this->set('authUser', $this->_user);
     } else {
         $this->set('authUser', false);
     }
     // $this->set(compact($authUser));
     $nav = $this->_setNav();
     $this->set(compact('nav'));
 }
Beispiel #22
0
 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 !');
     }
 }
Beispiel #23
0
 /**
  * Render a LilDate field.
  *
  * This method accepts a number of keys:
  *
  * - `text` The text of the button. Unlike all other form controls, buttons
  *   do not escape their contents by default.
  * - `escape` Set to true to enable escaping on all attributes.
  * - `type` The button type defaults to 'submit'.
  *
  * Any other keys provided in $data will be converted into HTML attributes.
  *
  * @param array            $data    The data to build a button with.
  * @param ContextInterface $context The form context.
  * 
  * @return string
  */
 public function render(array $data, ContextInterface $context)
 {
     $data += ['val' => '', 'name' => ''];
     if (is_a($data['val'], 'Cake\\I18n\\Time') || is_a($data['val'], 'Cake\\I18n\\Date') || is_a($data['val'], 'Cake\\I18n\\FrozenTime') || is_a($data['val'], 'Cake\\I18n\\FrozenDate')) {
         $data['value'] = $data['val']->toDateString();
     } else {
         if ($theDate = Time::parseDate($data['val'], 'yyyy-MM-dd')) {
             $data['value'] = $theDate->toDateString();
         }
     }
     // default field type is HTML5 date
     $fieldType = 'date';
     // localized date input with jquery date picker
     if (Configure::read('Lil.legacyDateFields')) {
         $fieldType = 'text';
         if ($theDate = Time::parseDate($data['value'], 'yyyy-MM-dd')) {
             $parts = str_split(Configure::read('Lil.dateFormat'));
             for ($i = 0; $i < sizeof($parts); $i++) {
                 $parts[$i] = strtr($parts[$i], ['D' => str_pad($theDate->day, 2, '0', STR_PAD_LEFT), 'M' => str_pad($theDate->month, 2, '0', STR_PAD_LEFT), 'Y' => $theDate->year]);
             }
             $data['value'] = implode(Configure::read('Lil.dateSeparator'), $parts);
         }
         $this->view->Lil->jsReady(sprintf('$("#%1$s").datepicker(%2$s);', $data['id'], $this->_jsOptions()));
     }
     return $this->templates->format('input', ['type' => $fieldType, 'name' => $data['name'], 'attrs' => $this->templates->formatAttributes($data, ['name', 'val'])]);
 }
 /**
  * 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'));
 }
Beispiel #25
0
 /**
  * setUp method
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $this->View = new View();
     $this->Time = new TimeHelper($this->View);
     Time::$defaultLocale = 'en_US';
 }
Beispiel #26
0
 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);
     */
 }
Beispiel #27
0
 public function setUp()
 {
     Time::setToStringFormat('yyyy-MM-dd HH:mm:ss');
     $this->request = new Request();
     $this->response = new Response();
     $this->view = new CsvView($this->request, $this->response);
 }
 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');
 }
Beispiel #29
0
 public function render(array $data, ContextInterface $context)
 {
     //         debug($data);
     //         debug($this->_templates);
     $date_data = ['type' => 'text', 'name' => $data['name'] . '__date__', 'id' => $this->get_dom_id($data['name'] . '-date'), 'language' => $data['language'], 'datepicker_format' => $data['datepicker_format'], 'upper_datepicker_id' => isset($data['upper_datepicker_name']) ? $this->get_dom_id($data['upper_datepicker_name'] . '-date') : null, 'upper_datepicker_name' => isset($data['upper_datepicker_name']) ? $data['upper_datepicker_name'] : null, 'format_on_blur' => $data['format_on_blur'], 'alaxos_js_format' => $data['alaxos_js_format'], 'class' => 'form-control inputDate'];
     //         debug($date_data);
     $time_data = ['type' => 'text', 'name' => $data['name'] . '__time__', 'id' => $this->get_dom_id($data['name'] . '-time'), 'class' => 'form-control inputTime'];
     $hidden_data = ['type' => 'hidden', 'name' => $data['name'], 'id' => $this->get_dom_id($data['name'] . '-hidden')];
     $display_timezone = null;
     if (Configure::check('display_timezone')) {
         $display_timezone = Configure::read('display_timezone');
     } elseif (Configure::check('default_display_timezone')) {
         $display_timezone = Configure::read('default_display_timezone');
     }
     /*
      * Case of posted data
      */
     if (isset($data['val']) && !empty($data['val']) && is_string($data['val'])) {
         $data['val'] = Time::parse($data['val'], $display_timezone);
     }
     if (isset($data['val']) && (is_a($data['val'], 'Cake\\I18n\\Time') || is_a($data['val'], 'Cake\\I18n\\FrozenTime'))) {
         if (isset($display_timezone)) {
             $data['val']->setTimezone($display_timezone);
             //it doesn't change the timezone internally, but it changes the tz used for display
         }
         $datetime = $data['val'];
         $date_data['value'] = $datetime->format($data['php_date_format']);
         $time_data['value'] = $datetime->format('H:i');
         $hidden_data['value'] = $date_data['value'] . ' ' . $time_data['value'];
     }
     $input = $this->get_html_code($date_data, $time_data, $hidden_data);
     $input .= $this->get_js_code($date_data, $time_data, $hidden_data);
     return $input;
 }
 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;
 }