Beispiel #1
0
 public static function render($app, $ref_id, $title = 'Comments')
 {
     if (!isset($app)) {
         throw new \FuelException('Petro_Comment : Invalid $app = ' . $app);
     }
     $query = \DB::query('SELECT ' . static::$_table . '.*, users.username FROM ' . static::$_table . ', users' . ' WHERE ' . static::$_table . '.user_id = users.id' . ' AND ' . static::$_table . '.app = "' . $app . '"' . ' AND ' . static::$_table . '.ref_id = ' . $ref_id . ' ORDER BY ' . static::$_table . '.created_at asc')->execute();
     $data['title'] = $title;
     $data['app'] = $app;
     $data['ref_id'] = $ref_id;
     $data['total_comments'] = count($query);
     if ($data['total_comments'] <= 0) {
         $data['comments'] = str_replace('{text}', 'No comments yet.', \Config::get('petro.template.comment.empty'));
     } else {
         $t = \Config::get('petro.template.comment.item');
         $out = '';
         foreach ($query as $item) {
             $author = isset($item['username']) ? $item['username'] : '******';
             $date = empty($item['created_at']) ? '' : \Date::forge($item['created_at'])->format(\Config::get('petro.date_format', '%Y-%m-%d %H:%M'));
             $cost = empty($item['cost']) ? '' : number_format($item['cost']);
             $out .= str_replace(array('{comment_id}', '{comment_author}', '{comment_date}', '{comment_text}', '{comment_cost}'), array($item['id'], $author, $date, nl2br($item['text']), $cost), $t);
         }
         $data['comments'] = $out;
     }
     $data['last_url'] = \Uri::current();
     return \View::forge('petro/comments/_form', $data, false)->render();
 }
Beispiel #2
0
 public function action_edit($id = null)
 {
     $client = Model_Client::find($id);
     $form = $this->setup_form();
     if (Input::method() == 'POST') {
         if ($form->validation()->run() === true) {
             $fields = $form->validated();
             $client->code = $fields['code'];
             $client->name = $fields['name'];
             $client->name_en = $fields['name_en'];
             $client->status = $fields['status'];
             $client->updated_at = Date::forge()->get_timestamp();
             if ($client->save()) {
                 Session::set_flash('success', 'Updated client #' . $id);
                 Response::redirect('clients');
             } else {
                 Session::set_flash('error', 'Could not update client #' . $id);
             }
         } else {
             $this->template->set_global('errors', $form->error(), false);
         }
     }
     $this->template->page_title = "Edit Client";
     $this->template->set('content', $form->build($client), false);
 }
 /**
  * 対象のフリマを取得
  *
  * @access private
  * @return Model_Fleamarket array
  */
 private function getFleamarkets()
 {
     $target_event_statuses = array(\Model_Fleamarket::EVENT_STATUS_SCHEDULE, \Model_Fleamarket::EVENT_STATUS_RESERVATION_RECEIPT, \Model_Fleamarket::EVENT_STATUS_RECEIPT_END);
     $date = \Date::forge(strtotime('- 1 day'));
     $fleamarkets = \Model_Fleamarket::find('all', array('select' => array('fleamarket_id', 'event_status'), 'where' => array(array('event_date', '<=', $date->format('mysql')), array('register_type', '=', \Model_Fleamarket::REGISTER_TYPE_ADMIN), array('event_time_end', '<=', $date::time()->format('mysql')), array('event_status', 'IN', $target_event_statuses))));
     return $fleamarkets;
 }
Beispiel #4
0
 public function action_review($pid)
 {
     $this->template->title = "旅ログ";
     $ret = Model_Members_General::getPostHeader($pid);
     $first = array_shift($ret);
     // ********************************
     if (Input::method() == 'POST') {
         /*--------
           ユーザが入力した値とその時の時刻を保持
           ------*/
         $first['input_title'] = Input::post('title');
         $first['input_comment'] = Input::post('comment');
         $first['input_rating'] = Input::post('rating');
         $time = Date::forge()->get_timestamp();
     }
     /*-----------
       Validationの準備
       -----------*/
     //Validationオブジェクトを呼び出す
     $val = Validation::forge();
     //フォームのルール設定
     $val->add('title', 'タイトル')->add_rule('required')->add_rule('max_length', 30);
     $val->add('comment', 'コメント')->add_rule('required');
     //コメントの長さ制限いる?
     $val->add('rating', '評価')->add_rule('required');
     //Validationチェック
     if ($val->run()) {
         /*------------
           postされた各データをDBに保存
           ----------------*/
         $props = array('uid' => $this->viewer_info['uid'], 'pid' => $pid, 'title' => $first['input_title'], 'comment' => $first['input_comment'], 'rating' => $first['input_rating'], 'datetime' => $time);
         //モデルオブジェクト作成
         $new = Model_Review::forge();
         $new->set($props);
         //データを保存する
         if (!$new->save()) {
             //保存失敗
             $data['save'] = '正しく投稿できませんでした。';
         } else {
             //保存成功
             //$input_title, $input_comment, $input_rating を初期化
             $first['input_title'] = '';
             $first['input_comment'] = '';
             $first['input_rating'] = 5.0;
         }
     }
     //$val->run()ここまで
     //Validationオブジェクトをビューに渡す
     $first['val'] = $val;
     // ********************************
     $first['itta'] = Model_Members_General::countItta($pid);
     $first['ikitai'] = Model_Members_General::countIkitai($pid);
     $first['reviews'] = Model_Members_General::getReviews($pid);
     $first['revnum'] = Model_Members_General::countReview($pid);
     $first['msg'] = $this->msg;
     $this->template->content = View::forge('members/postlookuprev', $first);
 }
 /**
  * 新規会員数
  *
  * @access private
  * @param
  * @return int
  * @author ida
  */
 private function getNewMemberCount()
 {
     $date = \Date::forge(strtotime('- 1 day'));
     $field = \DB::expr("DATE_FORMAT(created_at, '%Y-%m-%d')");
     $query = \Model_User::query();
     $query->where($field, $date->format('%Y-%m-%d'));
     $count = $query->count();
     return $count;
 }
Beispiel #6
0
 /**
  * Demonstrates reading data through an ORM model
  */
 public function action_index()
 {
     $event_model = Model_Orm_Event::find("all", array("where" => array(array('start', '>=', Date::forge()->format("%Y-%m-%d"))), "order_by" => array("start" => "asc"), "related" => array("agendas", "location")));
     $main_content = View::forge("event/index");
     $main_content->set("event_model", $event_model);
     $this->template->libs_js = array("http://code.jquery.com/jquery-1.8.2.js");
     $this->template->page_title = __("ACTION_INDEX_TITLE");
     $this->template->page_content = $main_content;
 }
Beispiel #7
0
 public function action_index()
 {
     echo '<pre>';
     echo 'FuelPHP version: ' . Fuel::VERSION . "\n";
     echo '			local: ' . setlocale(LC_ALL, '0') . "\n";
     echo '			 date: ' . Date::forge()->format('mysql') . "\n";
     echo 'default_charset: ' . ini_get('default_charset') . "\n";
     echo '<pre>';
 }
 /**
  * メールマガジン送信
  *
  * @access public
  * @param int $mail_magazine_id メルマガID
  * @param int $administrator_id 管理者ID
  * @param int $limit 1回で処理する件数
  * @return void
  * @author ida
  */
 public function run($mail_magazine_id, $administrator_id = 0, $limit = 1000)
 {
     $this->openLog($mail_magazine_id);
     $this->log('メルマガID: ' . $mail_magazine_id . ' の送信を開始します' . "\n");
     if (\Model_Mail_Magazine::isProcess()) {
         $this->log('メルマガ送信中のため送信できません' . "\n");
         exit;
     }
     $mail_magazine = \Model_Mail_Magazine::startProcess($mail_magazine_id);
     $offset = 0;
     if (!is_numeric($limit) || $limit <= 0) {
         $limit = 1000;
     }
     $total_count = 0;
     $success_count = 0;
     $fail_count = 0;
     while ($limit > 0) {
         $mail_magazine_users = \Model_Mail_Magazine_User::findByMailMagazineId($mail_magazine_id, $offset, $limit);
         if (count($mail_magazine_users) == 0) {
             break;
         }
         $is_stop = false;
         $replace_data = $this->makeReplaceData($mail_magazine);
         foreach ($mail_magazine_users as $mail_magazine_user) {
             try {
                 usleep(300000);
                 if (!\Model_Mail_Magazine::isProcess($mail_magazine_id)) {
                     $is_stop = true;
                     $this->log($mail_magazine_user->user_id . ": cancel.\n");
                     break;
                 }
                 $send_result = $this->send($mail_magazine_user, $mail_magazine, $replace_data);
                 \Model_Mail_Magazine_User::updateStatus(array('send_status' => $send_result, 'error' => null, 'updated_user' => $administrator_id), array('mail_magazine_user_id' => $mail_magazine_user->mail_magazine_user_id));
                 $this->log($mail_magazine_user->user_id . " : success\n");
                 $success_count++;
             } catch (\Exception $e) {
                 $message = $e->getMessage();
                 $this->log($mail_magazine_user->user_id . ' : fail ' . $message . "\n");
                 \Model_Mail_Magazine_User::updateStatus(array('send_status' => \Model_Mail_Magazine_User::SEND_STATUS_ERROR_END, 'error' => $message, 'updated_user' => $administrator_id), array('mail_magazine_user_id' => $mail_magazine_user->mail_magazine_user_id));
                 $fail_count++;
             }
             $total_count++;
         }
         $offset += $limit;
     }
     $this->log('[total] ' . $total_count . ' [success] ' . $success_count . ' [fail] ' . $fail_count . "\n");
     $this->log('送信を終了しました');
     $this->closeLog();
     $mail_magazine->send_datetime = \Date::forge()->format('mysql');
     if ($is_stop) {
         $mail_magazine->send_status = \Model_Mail_Magazine::SEND_STATUS_CANCEL;
     } else {
         $mail_magazine->send_status = \Model_Mail_Magazine::SEND_STATUS_NORMAL_END;
     }
     $mail_magazine->save();
 }
Beispiel #9
0
 protected static function _columns()
 {
     $columns = array('id' => array('label' => 'ID', 'grid' => array('visible' => true, 'sortable' => true)), 'name' => array('label' => 'Name', 'grid' => array('process' => function ($data, $value) {
         $prof = unserialize($data->profile_fields);
         return $prof['first_name'] . ' ' . $prof['last_name'];
     })), 'username' => array('label' => 'Username', 'grid' => array('visible' => true, 'sortable' => true)), 'group' => array('label' => 'Group', 'grid' => array('visible' => true, 'sortable' => true, 'process' => function ($data, $value) {
         return static::$groups[$data->group];
     })), 'email' => array('label' => 'Email', 'grid' => array('visible' => true, 'sortable' => false)), 'last_login' => array('label' => 'Last Login', 'grid' => array('visible' => true, 'sortable' => false, 'process' => function ($data, $value) {
         return empty($data->last_login) ? '<span class="label warning">Never</span>' : '<span class="label">' . \Date::forge($data->last_login)->format('%Y-%m-%d %H:%M') . '</span>';
     })), '_action_' => Petro_Grid::default_actions());
     return $columns;
 }
Beispiel #10
0
 public function action_index()
 {
     $pid = 1;
     /* 仮 */
     $uid = 1;
     /* 仮 */
     /* 本当はレビュー投稿したヒトのuid */
     //ビューに渡すデータの配列を初期化
     $data = array();
     if (Input::method() == 'POST') {
         /*--------
           ユーザが入力した値とその時の時刻を保持
           ------*/
         $data['input_title'] = Input::post('title');
         $data['input_comment'] = Input::post('comment');
         $data['input_rating'] = Input::post('rating');
         $time = Date::forge()->get_timestamp();
     }
     /*-----------
       Validationの準備
       -----------*/
     //Validationオブジェクトを呼び出す
     $val = Validation::forge();
     //フォームのルール設定
     $val->add('title', 'タイトル')->add_rule('required')->add_rule('max_length', 30);
     $val->add('comment', 'コメント')->add_rule('required');
     //コメントの長さ制限いる?
     $val->add('rating', '評価')->add_rule('required');
     //Validationチェック
     if ($val->run()) {
         /*------------
            postされた各データをDBに保存
           ----------------*/
         $props = array('uid' => $uid, 'pid' => $pid, 'title' => $data['input_title'], 'comment' => $data['input_comment'], 'rating' => $data['input_rating'], 'datetime' => $time);
         //モデルオブジェクト作成
         $new = Model_Review::forge($props);
         //データを保存する
         if (!$new->save()) {
             //保存失敗
             $data['save'] = '正しく投稿できませんでした。';
         } else {
             //保存成功
             /* 本当はルックアップページのレビュー画面に飛びたい */
             Response::redirect('members/top');
         }
     }
     //$val->run()ここまで
     //Validationオブジェクトをビューに渡す
     $data['val'] = $val;
     return View::forge('members/review', $data, false);
 }
Beispiel #11
0
 public function action_index()
 {
     echo '<pre>';
     echo Fuel::VERSION . "\n";
     echo setlocale(LC_ALL, '') . "\n";
     echo Date::forge()->format('mysql') . "\n";
     echo ini_get('default_charset') . "\n";
     echo '</pre>';
     $cd = '10001';
     $result = Model_Employee::find_by_cd($cd);
     foreach ($result->as_array() as $row) {
         echo $row['lname'] . "\n";
         echo $row['fname'] . "\n";
     }
     echo count($result);
 }
Beispiel #12
0
 public static function check_and_create($foreign_table, $foreign_id, $type)
 {
     $since_datetime = \Date::forge(strtotime('-' . \Config::get('notice.periode_to_update.default')))->format('mysql');
     if (!($obj = self::get_last4foreign_data($foreign_table, $foreign_id, $type, $since_datetime))) {
         $obj = self::forge(array('foreign_table' => $foreign_table, 'foreign_id' => $foreign_id, 'type' => $type, 'body' => Site_Util::get_notice_body($foreign_table, $type)));
         if (!in_array($foreign_table, Site_Util::get_accept_parent_tables()) && ($parent_table = \Site_Model::get_parent_table($foreign_table))) {
             $obj->parent_table = $parent_table;
             $foreign_obj_name = \Site_Model::get_model_name($foreign_table);
             $foreign_obj = $foreign_obj_name::find($foreign_id);
             $parent_id_prop = $parent_table . '_id';
             $obj->parent_id = $foreign_obj->{$parent_id_prop};
         }
         $obj->save();
     }
     return $obj;
 }
Beispiel #13
0
 /**
  * Create tables: users, options, posts, tags, posts_tags
  */
 public function up()
 {
     \DBUtil::create_table('users', array('id' => array('type' => 'int', 'constraint' => 11, 'auto_increment' => true), 'username' => array('type' => 'varchar', 'constraint' => 50), 'password' => array('type' => 'varchar', 'constraint' => 256), 'group' => array('type' => 'int', 'constraint' => 11, 'default' => 1), 'email' => array('type' => 'varchar', 'constraint' => 256), 'last_login' => array('type' => 'varchar', 'constraint' => 25), 'login_hash' => array('type' => 'varchar', 'constraint' => 256), 'profile_fields' => array('type' => 'text')), array('id'));
     // Coming soon
     // \DBUtil::create_index('users', 'username', 'unique');
     // \DBUtil::create_index('users', 'email', 'unique');
     \DBUtil::create_table('options', array('id' => array('type' => 'int', 'constraint' => 11, 'auto_increment' => true), 'option' => array('type' => 'varchar', 'constraint' => 128), 'value' => array('type' => 'text')), array('id'));
     // Coming soon
     // \DBUtil::create_index('options', 'option', 'unique');
     \DBUtil::create_table('posts', array('id' => array('type' => 'int', 'constraint' => 11, 'auto_increment' => true), 'user_id' => array('type' => 'int', 'constraint' => 11), 'title' => array('type' => 'varchar', 'constraint' => 128), 'slug' => array('type' => 'varchar', 'constraint' => 128), 'body' => array('type' => 'text'), 'created_at' => array('type' => 'datetime'), 'updated_at' => array('type' => 'datetime')), array('id'));
     // Coming soon
     // \DBUtil::create_index('posts', 'slug', 'unique');
     \DBUtil::create_table('tags', array('id' => array('type' => 'int', 'constraint' => 11, 'auto_increment' => true), 'tag' => array('type' => 'varchar', 'constraint' => 128), 'slug' => array('type' => 'varchar', 'constraint' => 128)), array('id'));
     // Coming soon
     // \DBUtil::create_index('tags', 'tag', 'unique');
     // \DBUtil::create_index('tags', 'slug', 'unique');
     \DBUtil::create_table('posts_tags', array('post_id' => array('type' => 'int', 'constraint' => 11), 'tag_id' => array('type' => 'int', 'constraint' => 11)));
     \Auth::create_user('admin', 'admin', '*****@*****.**', 100);
     \Option::reset();
     \DB::insert('posts')->columns(array('user_id', 'title', 'slug', 'body', 'created_at', 'updated_at'))->values(array(1, 'My first post', 'my-first-post', 'This is my first post. Yiharr!', \Date::forge()->format('mysql'), \Date::forge()->format('mysql')))->execute();
     \DB::insert('tags')->columns(array('tag', 'slug'))->values(array('My first tag', 'my-first-tag'))->execute();
     \DB::insert('posts_tags')->columns(array('post_id', 'tag_id'))->values(array(1, 1))->execute();
 }
Beispiel #14
0
 /**
  * Takes a DB timestamp and converts it into a Date object
  *
  * @param   string  value
  * @param   array  any options to be passed
  *
  * @return  \Fuel\Core\Date
  */
 public static function type_time_decode($var, array $settings)
 {
     if ($settings['data_type'] == 'time_mysql') {
         // deal with a 'nulled' date, which according to MySQL is a valid enough to store?
         if ($var == '0000-00-00 00:00:00') {
             if (array_key_exists('null', $settings) and $settings['null'] === false) {
                 throw new InvalidContentType('Value ' . $var . ' is not a valid date and can not be converted to a Date object.');
             }
             return null;
         }
         return \Date::create_from_string($var, 'mysql');
     }
     return \Date::forge($var);
 }
 /**
  * Update a user's properties
  * Note: Username cannot be updated, to update password the old password must be passed as old_password
  *
  * @param   Array  properties to be updated including profile fields
  * @param   string
  * @return  bool
  */
 public function update_user($values, $username = null)
 {
     $username = $username ?: $this->user['username'];
     $current_values = \DB::select_array(\Config::get('simpleauth.table_columns', array('*')))->where('username', '=', $username)->from(\Config::get('simpleauth.table_name'))->execute(\Config::get('simpleauth.db_connection'));
     if (empty($current_values)) {
         throw new \SimpleUserUpdateException('Username not found', 4);
     }
     $update = array();
     if (array_key_exists('username', $values)) {
         throw new \SimpleUserUpdateException('Username cannot be changed.', 5);
     }
     if (array_key_exists('password', $values)) {
         if (empty($values['old_password']) or $current_values->get('password') != $this->hash_password(trim($values['old_password']))) {
             throw new \SimpleUserWrongPassword('Old password is invalid');
         }
         $password = trim(strval($values['password']));
         if ($password === '') {
             throw new \SimpleUserUpdateException('Password can\'t be empty.', 6);
         }
         $update['password'] = $this->hash_password($password);
         unset($values['password']);
     }
     if (array_key_exists('old_password', $values)) {
         unset($values['old_password']);
     }
     if (array_key_exists('email', $values)) {
         $email = filter_var(trim($values['email']), FILTER_VALIDATE_EMAIL);
         if (!$email) {
             throw new \SimpleUserUpdateException('Email address is not valid', 7);
         }
         $update['email'] = $email;
         unset($values['email']);
     }
     if (array_key_exists('group', $values)) {
         if (is_numeric($values['group'])) {
             $update['group'] = (int) $values['group'];
         }
         unset($values['group']);
     }
     if (!empty($values)) {
         $profile_fields = @unserialize($current_values->get('profile_fields')) ?: array();
         foreach ($values as $key => $val) {
             if ($val === null) {
                 unset($profile_fields[$key]);
             } else {
                 $profile_fields[$key] = $val;
             }
         }
         $update['profile_fields'] = serialize($profile_fields);
     }
     $update['updated_at'] = \Date::forge()->get_timestamp();
     $affected_rows = \DB::update(\Config::get('simpleauth.table_name'))->set($update)->where('username', '=', $username)->execute(\Config::get('simpleauth.db_connection'));
     // Refresh user
     if ($this->user['username'] == $username) {
         $this->user = \DB::select_array(\Config::get('simpleauth.table_columns', array('*')))->where('username', '=', $username)->from(\Config::get('simpleauth.table_name'))->execute(\Config::get('simpleauth.db_connection'))->current();
     }
     return $affected_rows > 0;
 }
Beispiel #16
0
	<fieldset>
		<div class="form-group">
			<?php 
echo Form::label('Имя (фамилия, имя)', 'staff_name', array('class' => 'control-label'));
?>
                        <?php 
echo Form::input('staff_name', Input::post('staff_name', isset($staff) ? $staff->staff_name : ''), array('class' => 'col-md-4 form-control', 'placeholder' => 'Имя (фамилия, имя)'));
?>
		</div>
            
		<div class="form-group">
			<?php 
echo Form::label('Дата рождения', 'birthdate', array('class' => 'control-label'));
?>
                        <?php 
echo Form::input('birthdate', Input::post('birthdate', isset($staff) ? Date::forge($staff->birthdate)->format("%d.%m.%Y") : ''), array('class' => 'col-md-4 form-control datepicker', 'placeholder' => 'Дата рождения'));
?>
		</div>
            
		<div class="form-group">
			<?php 
echo Form::label('Данные', 'data', array('class' => 'control-label'));
?>
                        <?php 
echo Form::textarea('data', Input::post('data', isset($staff) ? $staff->data : ''), array('class' => 'col-md-8 form-control textarea_tinymce', 'rows' => 8, 'placeholder' => 'Данные об игроке'));
?>

		</div>
            
		<div class="form-group">
			<?php 
 /**
  * Creates a temporary hash that will validate the current login
  *
  * @return  string
  */
 public function create_login_hash()
 {
     if (empty($this->user)) {
         throw new \SimpleUserUpdateException('User not logged in, can\'t create login hash.');
     }
     $last_login = \Date::forge()->get_timestamp();
     $login_hash = sha1(\Config::get('simpleauth.login_hash_salt') . $this->user['username'] . $last_login);
     \DB::update(\Config::get('simpleauth.table_name'))->set(array('last_login' => $last_login, 'login_hash' => $login_hash))->where('username', '=', $this->user['username'])->execute(\Config::get('simpleauth.db_connection'));
     $this->user['login_hash'] = $login_hash;
     return $login_hash;
 }
Beispiel #18
0
 /**
  * Creates a temporary hash that will validate the current login
  *
  * @return  string
  */
 public function create_login_hash()
 {
     // we need a logged-in user to generate a login hash
     if (empty($this->user)) {
         throw new \SimpleUserUpdateException('User not logged in, can\'t create login hash.', 10);
     }
     // set the previous and current last login
     $this->user->previous_login = $this->user->last_login;
     $this->user->last_login = \Date::forge()->get_timestamp();
     // generate the new hash
     $this->user->login_hash = sha1(\Config::get('ormauth.login_hash_salt') . $this->user->username . $this->user->last_login);
     // store it
     $this->user->save();
     // and return it
     return $this->user->login_hash;
 }
Beispiel #19
0
	<?php 
echo $activity->isWholeday ? 'Yes' : 'No';
?>
</p>

<h5><strong>Date of Activity:</strong></h5>
</p>
	<?php 
echo Date::forge($activity->date)->format("%b %d, %Y %H:%M %p", true);
?>
</p>

<h5><strong>Activity Until:</strong></h5>
</p>
	<?php 
echo Date::forge($activity->end_date)->format("%b %d, %Y %H:%M %p", true);
?>
</p>

<h5><strong>Subject:</strong></h5>
<p>
	<?php 
echo Model_Subject::getSubjectName($activity->subject_id) ?: Config::get('no_subject')[$activity->subject_id];
?>
</p>

<h5><strong>Activity:</strong></h5>
<p>
	<?php 
echo $activity->activity_content;
?>
Beispiel #20
0
 public function delete($cascade = null, $use_transaction = false)
 {
     // If we are using a transcation then make sure it's started
     if ($use_transaction) {
         $db = \Database_Connection::instance(static::connection(true));
         $db->start_transaction();
     }
     // Call the observers
     $this->observe('before_delete');
     // Load temporal properties.
     $timestamp_end_name = static::temporal_property('end_column');
     $mysql_timestamp = static::temporal_property('mysql_timestamp');
     // Generate the correct timestamp and save it
     $current_timestamp = $mysql_timestamp ? \Date::forge()->format('mysql') : \Date::forge()->get_timestamp();
     static::disable_primary_key_check();
     $this->{$timestamp_end_name} = $current_timestamp;
     static::enable_primary_key_check();
     // Loop through all relations and delete if we are cascading.
     $this->freeze();
     foreach ($this->relations() as $rel_name => $rel) {
         // get the cascade delete status
         $relCascade = is_null($cascade) ? $rel->cascade_delete : (bool) $cascade;
         if ($relCascade) {
             if (get_class($rel) != 'Orm\\ManyMany') {
                 // Loop through and call delete on all the models
                 foreach ($rel->get($this) as $model) {
                     $model->delete($cascade);
                 }
             }
         }
     }
     $this->unfreeze();
     parent::save();
     $this->observe('after_delete');
     // Make sure the transaction is committed if needed
     $use_transaction and $db->commit_transaction();
     return $this;
 }
Beispiel #21
0
        <h4><?php 
echo Html::anchor(Uri::create('news'), 'Новости');
?>
</h4>

        <?php 
foreach ($news as $value) {
    ?>
            <div class="article">                    
                <h3><?php 
    echo Html::anchor(Uri::create('news/shahter/view/' . $value->id), $value->title);
    ?>
</h3>

                <div class="details">Когда: <span class="date"><?php 
    echo Date::forge($value->created_at)->format("%d.%m.%Y");
    ?>
</span> / Комментариев: <span class="comments"><?php 
    echo $value->vk_comments_count;
    ?>
</span></div>

                <?php 
    echo $value->preview;
    ?>
             
                <p><?php 
    echo Html::anchor(Uri::create('news/shahter/view/' . $value->id), 'Читать далее', array('class' => 'btn btn-success'));
    ?>
</p>
            </div>
Beispiel #22
0
 protected function delete_self()
 {
     // If soft deleting has been disabled then just call the parent's delete
     if ($this->_disable_soft_delete) {
         return parent::delete_self();
     }
     $deleted_column = static::soft_delete_property('deleted_field', static::$_default_field_name);
     $mysql_timestamp = static::soft_delete_property('mysql_timestamp', static::$_default_mysql_timestamp);
     // Generate the correct timestamp and save it
     $this->{$deleted_column} = $mysql_timestamp ? \Date::forge()->format('mysql') : \Date::forge()->get_timestamp();
     $result = $this->save(false);
     return $result;
 }
Beispiel #23
0
 /**
  * Updates the defined deleted_field with a current timestamp rather than
  * deleting.
  *
  * TODO: This method needs a major cleanup but can't be done really until the refactoring starts. This is currently
  * not maintainable at all,
  *
  * @param $cascade         boolean
  * @param $use_transaction boolean
  *
  * @return boolean
  */
 public function delete($cascade = null, $use_transaction = false)
 {
     // New objects can't be deleted, neither can frozen
     if ($this->is_new() or $this->frozen()) {
         return false;
     }
     if ($use_transaction) {
         $db = \Database_Connection::instance(static::connection(true));
         $db->start_transaction();
     }
     try {
         $this->observe('before_delete');
         $deleted_column = static::soft_delete_property('deleted_field', static::$_default_field_name);
         $mysql_timestamp = static::soft_delete_property('mysql_timestamp', static::$_default_mysql_timestamp);
         //Call the observers
         $this->observe('before_delete');
         //Generate the correct timestamp and save it
         $this->{$deleted_column} = $mysql_timestamp ? \Date::forge()->format('mysql') : \Date::forge()->get_timestamp();
         $this->freeze();
         foreach ($this->relations() as $rel_name => $rel) {
             $rel->delete($this, $this->{$rel_name}, false, is_array($cascade) ? in_array($rel_name, $cascade) : $cascade);
         }
         $this->unfreeze();
         // Return success of update operation
         if (!$this->save()) {
             return false;
         }
         $this->freeze();
         foreach ($this->relations() as $rel_name => $rel) {
             //Give model subclasses a chance to chip in.
             if (!$this->should_cascade_delete($rel)) {
                 //The function returned false so something does not want this relation to be cascade deleted
                 $should_cascade = false;
             } else {
                 $should_cascade = is_array($cascade) ? in_array($rel_name, $cascade) : $cascade;
             }
             $rel->delete($this, $this->{$rel_name}, true, $should_cascade);
         }
         $this->unfreeze();
         // Perform cleanup:
         // remove from internal object cache, remove PK's, set to non saved object, remove db original values
         if (array_key_exists(get_called_class(), static::$_cached_objects) and array_key_exists(static::implode_pk($this), static::$_cached_objects[get_called_class()])) {
             unset(static::$_cached_objects[get_called_class()][static::implode_pk($this)]);
         }
         foreach ($this->primary_key() as $pk) {
             unset($this->_data[$pk]);
         }
         // remove original relations too
         foreach ($this->relations() as $rel_name => $rel) {
             $this->_original_relations[$rel_name] = $rel->singular ? null : array();
         }
         $this->_is_new = true;
         $this->_original = array();
         $this->observe('after_delete');
         $use_transaction and $db->commit_transaction();
     } catch (\Exception $e) {
         $use_transaction and $db->rollback_transaction();
         throw $e;
     }
     return $this;
 }
Beispiel #24
0
 public function action_update($id = false)
 {
     if (!is_numeric($id)) {
         \Response::redirect('admin/team/list');
     }
     // Get news item to edit
     if (!($item = Model_Team::find_one_by_id($id))) {
         \Response::redirect('admin/team/list');
     }
     \View::set_global('title', 'Edit Member');
     if (\Input::post()) {
         $val = Model_Team::validate('update');
         // Upload image and display errors if there are any
         $image = $this->upload_image();
         if (!$image['exists'] && \Config::get('details.image.required', false) && empty($item->images)) {
             // No previous images and image is not selected and it is required
             \Messages::error('<strong>There was an error while trying to upload content image</strong>');
             \Messages::error('You have to select image');
         } elseif ($image['errors']) {
             \Messages::error('<strong>There was an error while trying to upload content image</strong>');
             foreach ($image['errors'] as $error) {
                 \Messages::error($error);
             }
         }
         if ($val->run() && $image['is_valid'] && !(!$image['exists'] && \Config::get('details.image.required', false) && empty($item->images))) {
             /** IMAGES **/
             // Get all alt texts to update if there is no image change
             foreach (\Arr::filter_prefixed(\Input::post(), 'alt_text_') as $image_id => $alt_text) {
                 if (strpos($image_id, 'new_') === false) {
                     $item_images[$image_id] = array('id' => $image_id, 'data' => array('alt_text' => \Input::post('alt_text_' . $image_id, '')));
                 }
             }
             // Save images if new files are submitted
             if (isset($this->_image_data)) {
                 foreach ($this->_image_data as $image_data) {
                     $cover_count = count($item->images);
                     if (strpos($image_data['field'], 'new_') === false) {
                         // Update existing image
                         if (str_replace('image_', '', $image_data['field']) != 0) {
                             $image_id = (int) str_replace('image_', '', $image_data['field']);
                             $cover_count--;
                             $item_images[$image_id] = array('id' => $image_id, 'data' => array('content_id' => $item->id, 'image' => $image_data['saved_as'], 'alt_text' => \Input::post('alt_text_' . $image_id, '')));
                             $this->delete_image(\Input::post('image_db_' . $image_id, ''));
                         }
                     } else {
                         // Save new image
                         $image_tmp = str_replace('image_new_', '', $image_data['field']);
                         $item_images[0] = array('id' => 0, 'data' => array('content_id' => $item->id, 'image' => $image_data['saved_as'], 'alt_text' => \Input::post('alt_text_new_' . $image_tmp, ''), 'cover' => $cover_count == 0 ? 1 : 0, 'sort' => $cover_count + 1));
                     }
                 }
             }
             Model_Team::bind_images($item_images);
             /** END OF IMAGES **/
             // Get POST values
             $insert = \Input::post();
             // Prepare some values
             $insert['published_at'] = !empty($insert['published_at']) ? strtotime($insert['published_at']) : \Date::forge()->get_timestamp();
             $insert['active_from'] = !empty($insert['active_from']) ? strtotime($insert['active_from']) : NULL;
             $insert['active_to'] = !empty($insert['active_to']) ? strtotime($insert['active_to']) : NULL;
             if ($insert['status'] != 2) {
                 unset($insert['active_from']);
                 unset($insert['active_to']);
             }
             $item->set($insert);
             try {
                 $item->save();
                 \Messages::success('Member successfully updated.');
                 \Response::redirect(\Input::post('exit', false) ? \Uri::create('admin/team/list/') : \Uri::admin('current'));
             } catch (\Database_Exception $e) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to update member</strong>');
                 // Uncomment lines below to show database errors
                 //$errors = $e->getMessage();
                 //\Messages::error($errors);
             }
         } else {
             // Delete uploaded images if there is news saving error
             if (isset($this->_image_data)) {
                 foreach ($this->_image_data as $image_data) {
                     $this->delete_image($image_data['saved_as']);
                 }
             }
             if ($val->error() != array()) {
                 // show validation errors
                 \Messages::error('<strong>There was an error while trying to update member</strong>');
                 foreach ($val->error() as $e) {
                     \Messages::error($e->get_message());
                 }
             }
         }
     }
     $team = Model_Team::find_one_by_id($id);
     \Theme::instance()->set_partial('content', $this->view_dir . 'update')->set('team', $team);
 }
            }
            $max_booth = mt_rand(20, 100);
            $reservation_booth_limit = mt_rand(1, 10);
            $entry_style_line = array('fleamarket_id' => $fleamarket_id, 'entry_style_id' => $entry_style_id, 'booth_fee' => $booth_fee, 'max_booth' => $max_booth, 'reservation_booth_limit' => $reservation_booth_limit, 'created_user' => 0, 'updated_user' => null, 'created_at' => \Date::forge()->format('mysql'));
            \Model_Fleamarket_Entry_Style::forge($entry_style_line)->save();
        }
    }
    // フリマ説明情報
    $about_rand = mt_rand(0, 7);
    if ($about_rand > 0) {
        $about_list = array_rand($about_titles, $about_rand);
        if (!is_array($about_list)) {
            $about_list = (array) $about_list;
        }
        foreach ($about_list as $about_id) {
            $about_line = array('fleamarket_id' => $fleamarket_id, 'about_id' => $about_id, 'title' => $about_titles[$about_id], 'description' => $abouts[$about_id], 'created_user' => 0, 'updated_user' => null, 'created_at' => \Date::forge()->format('mysql'));
            \Model_Fleamarket_About::forge($about_line)->save();
        }
    }
}
/**
 * 住所から都道府県を省く
 *
 * @access private
 * @param string $address 住所
 * @return string
 * @author ida
 */
function getAddress($address)
{
    $address_pattern = '/(東京都|北海道|(?:京都|大阪)府|.{6,9}県)' . '((?:四日市|廿日市|野々市|かすみがうら|つくばみらい|いちき串木野)市|' . '(?:杵島郡大町|余市郡余市|高市郡高取)町|' . '.{3,12}市.{3,12}区|.{3,9}区|.{3,15}市(?=.*市)|' . '.{3,15}市|.{6,27}町(?=.*町)|.{6,27}町|' . '.{9,24}村(?=.*村)|.{9,24}村)(.*)/';
Beispiel #26
0
 /**
  * Test for Date::set_timezone()
  *
  * @test
  */
 public function test_set_timezone()
 {
     $output = Date::forge(1294176140)->set_timezone("America/Chicago")->get_timezone();
     $expected = "America/Chicago";
     $this->assertEquals($expected, $output);
 }
Beispiel #27
0
 /**
  * Saves the object to the database by either creating a new record
  * or updating an existing record. Sets the default values if set.
  *
  * @param   bool   $validate  wether to validate the input
  * @return  mixed  Rows affected and or insert ID
  */
 public function save($validate = true)
 {
     if ($this->frozen()) {
         throw new \Exception('Cannot modify a frozen row.');
     }
     $vars = $this->to_array();
     // Set default if there are any
     isset(static::$_defaults) and $vars = $vars + static::$_defaults;
     if ($validate and isset(static::$_rules) and !empty(static::$_rules)) {
         $vars = $this->pre_validate($vars);
         $validated = $this->post_validate($this->run_validation($vars));
         if ($validated) {
             $validated = array_filter($this->validation()->validated(), function ($val) {
                 return $val !== null;
             });
             $vars = $validated + $vars;
         } else {
             return false;
         }
     }
     $vars = $this->prep_values($vars);
     if (isset(static::$_properties)) {
         $vars = \Arr::filter_keys($vars, static::$_properties);
     }
     if (isset(static::$_updated_at)) {
         if (isset(static::$_mysql_timestamp) and static::$_mysql_timestamp === true) {
             $vars[static::$_updated_at] = \Date::forge()->format('mysql');
         } else {
             $vars[static::$_updated_at] = \Date::forge()->get_timestamp();
         }
     }
     if ($this->is_new()) {
         if (isset(static::$_created_at)) {
             if (isset(static::$_mysql_timestamp) and static::$_mysql_timestamp === true) {
                 $vars[static::$_created_at] = \Date::forge()->format('mysql');
             } else {
                 $vars[static::$_created_at] = \Date::forge()->get_timestamp();
             }
         }
         $query = \DB::insert(static::$_table_name)->set($vars);
         $this->pre_save($query);
         $result = $query->execute(static::get_connection(true));
         if ($result[1] > 0) {
             // workaround for PDO connections not returning the insert_id
             if ($result[0] === false and isset($vars[static::primary_key()])) {
                 $result[0] = $vars[static::primary_key()];
             }
             $this->set($vars);
             empty($result[0]) or $this->{static::primary_key()} = $result[0];
             $this->is_new(false);
         }
         return $this->post_save($result);
     }
     $query = \DB::update(static::$_table_name)->set($vars)->where(static::primary_key(), '=', $this->{static::primary_key()});
     $this->pre_update($query);
     $result = $query->execute(static::get_connection(true));
     $result > 0 and $this->set($vars);
     return $this->post_update($result);
 }
Beispiel #28
0
echo Html::img('assets/img/teams/' . $match->team_2->logo_uri) . ' <b>' . $match->team_2->value . '</b>';
?>
        </center>
        
        <br>
        <small><i>                
            <?php 
echo $match->name;
?>
<br>
            <?php 
echo $match->season->value;
?>
<br>
            <?php 
echo Date::forge($match->date)->format('%d.%m.%Y');
?>
</i>
        </small>
        
        <?php 
$goals = '';
?>
        <?php 
$f = TRUE;
?>
        <?php 
$exist_1 = FALSE;
?>
        <?php 
foreach ($match->matches_events as $item) {
Beispiel #29
0
 public static function get_datetime_list($base_datatime, $second = 1, $type = 'both')
 {
     if (!in_array($type, array('both', 'past', 'future'))) {
         throw new InvalidArgumentException('Third parameter is invalid.');
     }
     $base_time = strtotime($base_datatime);
     $return = array();
     switch ($type) {
         case 'future':
             $min = 0;
             $max = $second;
             break;
         case 'past':
             $min = 0 - $second;
             $max = 0;
             break;
         case 'both':
         default:
             $min = 0 - $second;
             $max = $second;
             break;
     }
     for ($i = $min; $i <= $max; $i++) {
         $return[] = \Date::forge($base_time + $i)->format('mysql');
     }
     return $return;
 }
Beispiel #30
0
<?php 
    foreach ($сategories as $item) {
        ?>
		<tr>

			<td><?php 
        echo $item->title;
        ?>
</td>
			<td><?php 
        $count = count($item->photos);
        echo $count != 0 ? Html::anchor('admin/media/photos/list/index/' . $item->id, count($item->photos)) : 0;
        ?>
</td>
			<td><?php 
        echo Date::forge($item->created_at)->format("%d.%m.%Y %H:%M");
        ?>
</td>
			<td>
                            <div class="btn-toolbar">
                                <div class="btn-group">
                                        <?php 
        echo Html::anchor('admin/media/photos/list/index/' . $item->id, '<i class="glyphicon glyphicon-eye-open"></i> Просмотр фото', array('class' => 'btn btn-sm btn-success'));
        ?>
						
                                        <?php 
        echo Html::anchor('admin/media/photos/categories/edit/' . $item->id, '<i class="glyphicon glyphicon-edit"></i> Редактировать', array('class' => 'btn btn-sm btn-primary'));
        ?>
						
                                        <?php 
        echo Html::anchor('admin/media/photos/categories/delete/' . $item->id, '<i class="glyphicon glyphicon-trash"></i> Удалить', array('class' => 'btn btn-sm btn-danger', 'onclick' => "return confirm('Вы уверены?')"));