Example #1
0
File: module.php Project: anqh/core
 /**
  * Wrap requested view inside module and render
  *
  * @return  string
  */
 public function render($file = null)
 {
     // Start benchmark
     if (Kohana::$profiling === true and class_exists('Profiler', false)) {
         $benchmark = Profiler::start('View', __METHOD__ . '(' . $this->_name . ')');
     }
     $module = (string) View::factory('generic/mod', array('class' => 'mod ' . Arr::get_once($this->_data, 'mod_class', strtr(basename($this->_file, '.php'), '_', '-')), 'id' => Arr::get_once($this->_data, 'mod_id'), 'actions' => isset($this->_data['mod_actions']) ? (string) View::factory('generic/actions', array('actions' => Arr::get_once($this->_data, 'mod_actions'))) : null, 'actions2' => isset($this->_data['mod_actions2']) ? (string) View::factory('generic/actions', array('actions' => Arr::get_once($this->_data, 'mod_actions2'))) : null, 'title' => Arr::get_once($this->_data, 'mod_title'), 'subtitle' => Arr::get_once($this->_data, 'mod_subtitle'), 'pagination' => Arr::get_once($this->_data, 'pagination'), 'content' => parent::render($file)));
     // Stop benchmark
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     return $module;
 }
Example #2
0
File: api.php Project: anqh/venues
 /**
  * Action: foursquare proxy
  */
 public function action_foursquare()
 {
     $foursquare = Arr::get_once($_REQUEST, 'method');
     $url = 'https://api.foursquare.com/v2';
     $method = 'GET';
     $required = $optional = array();
     switch ($foursquare) {
         // Venue info
         case 'venue':
             $url .= '/venue.json';
             $required = array('vid');
             break;
             // Venue search
         // Venue search
         case 'venues':
             $url .= '/venues/search';
             $required = array('ll', 'query');
             $optional = array('limit', 'intent');
             break;
         default:
             return;
     }
     $params = array_filter(Arr::intersect($_REQUEST, $required));
     if (!empty($params)) {
         $params += array_filter(Arr::intersect($_REQUEST, $optional));
         try {
             if ($method == 'GET') {
                 // Send GET request
                 if (!empty($params)) {
                     $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params, '', '&');
                 }
                 $options = array();
             } else {
                 // Send POST request
                 $options = array(CURLOPT_POST => true, CURLOPT_FOLLOWLOCATION => true);
                 if (!empty($params)) {
                     $options[CURLOPT_POSTFIELDS] = http_build_query($params);
                 }
             }
             /** @var  Request  $request */
             $request = Request::factory($url);
             $request->get_client()->options($options);
             $response = $request->execute();
             var_dump($response);
             if ($response->status() == 200) {
                 $this->data[$foursquare] = json_decode($response->body());
             }
         } catch (Kohana_Exception $e) {
         }
     }
 }
Example #3
0
File: api.php Project: anqh/anqh
 /**
  * Action: foursquare proxy
  */
 public function action_foursquare()
 {
     $foursquare = Arr::get_once($_REQUEST, 'method');
     $url = 'https://api.foursquare.com/v2';
     $required = $optional = array();
     switch ($foursquare) {
         // Venue info
         case 'venue':
             $url .= '/venue.json';
             $required = array('vid');
             break;
             // Venue search
         // Venue search
         case 'venues':
             $url .= '/venues/search';
             $required = array('ll', 'query');
             $optional = array('limit', 'intent');
             break;
         default:
             return;
     }
     $params = array_filter(Arr::intersect($_REQUEST, $required));
     if (!empty($params)) {
         $params += array_filter(Arr::intersect($_REQUEST, $optional));
         // Client keys
         $client_id = Kohana::$config->load('site.foursquare_client_id');
         $client_secret = Kohana::$config->load('site.foursquare_client_secret');
         if (!$client_id || !$client_secret) {
             throw new Anqh_Controller_API_Exception('Client id or secret missing');
         }
         $params['client_id'] = $client_id;
         $params['client_secret'] = $client_secret;
         $params['v'] = '20130815';
         try {
             if (!empty($params)) {
                 $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params, '', '&');
             }
             /** @var  Request  $request */
             $request = Request::factory($url);
             Kohana::$log->add(Log::DEBUG, 'Foursquare API call: :url ', array(':url' => $url));
             $response = $request->execute();
             switch ($response->status()) {
                 // Success
                 case 200:
                     $result = json_decode($response->body(), true);
                     $this->data[$foursquare] = self::_prepare_foursquare($foursquare, $result['response']);
                     Kohana::$log->add(Log::DEBUG, 'Foursquare API response: :response ', array(':response' => $response->body()));
                     break;
                     // Error in request
                 // Error in request
                 case 400:
                     $this->data['error'] = json_decode($response->body(), true);
                     throw new Controller_API_Exception('Error in request: :response', array(':response' => $response->body()));
                     break;
                 default:
                     $this->data['error'] = json_decode($response->body(), true);
                     throw new Controller_API_Exception('Unknown response: :response', array(':response' => $response->body()));
             }
         } catch (Controller_API_Exception $e) {
             Kohana::$log->add(Log::DEBUG, 'Foursquare API error: :error ', array(':error' => $e->getMessage()));
         } catch (Kohana_Exception $e) {
         }
     }
 }
Example #4
0
File: html.php Project: anqh/anqh
 /**
  * Return formatted <time> tag
  *
  * @param   string        $str
  * @param   array|string  $attributes  handled as time if not an array
  * @param   boolean       $short       use only date
  * @return  string
  */
 public static function time($str, $attributes = null, $short = false)
 {
     // Extract datetime
     $datetime = is_array($attributes) ? Arr::get_once($attributes, 'datetime') : $attributes;
     if ($datetime) {
         $time = is_numeric($datetime) ? $datetime : strtotime($datetime);
         $datetime = Date::format($short ? Date::DATE_8601 : Date::TIME_8601, $time);
         if (is_array($attributes)) {
             $attributes['datetime'] = $datetime;
         } else {
             $attributes = array('datetime' => $datetime);
         }
         // Set title if not the same as content
         if (!isset($attributes['title'])) {
             $title = Date::format($short ? 'DMYYYY' : 'DMYYYY_HM', $time);
             if ($title != $str) {
                 $attributes['title'] = $title;
             }
         }
     }
     return '<time' . HTML::attributes($attributes) . '>' . $str . '</time>';
 }
Example #5
0
File: topic.php Project: anqh/forum
 /**
  * Edit forum topic
  *
  * @param  integer  $area_id
  * @param  integer  $topic_id
  *
  * @throws  Model_Exception           invalid area, invalid topic
  * @throws  InvalidArgumentException  missing area and topic
  */
 protected function _edit_topic($area_id = null, $topic_id = null)
 {
     $this->history = false;
     $this->view = new View_Page();
     if ($area_id && !$topic_id) {
         // Start new topic
         $mode = View_Forum_PostEdit::NEW_TOPIC;
         /** @var  Model_Forum_Private_Area|Model_Forum_Area  $area */
         $area = $this->private ? Model_Forum_Private_Area::factory($area_id) : Model_Forum_Area::factory($area_id);
         if (!$area->loaded()) {
             throw new Model_Exception($area, $area_id);
         }
         Permission::required($area, Model_Forum_Area::PERMISSION_POST, self::$user);
         $this->view->title = HTML::chars($area->name);
         if ($this->private) {
             $topic = new Model_Forum_Private_Topic();
             $post = new Model_Forum_Private_Post();
             $cancel = Route::url('forum_area', array('id' => 'private', 'action' => ''));
             $recipients = array();
         } else {
             $topic = new Model_Forum_Topic();
             $post = new Model_Forum_Post();
             $cancel = Route::model($area);
         }
     } else {
         if ($topic_id) {
             // Edit old topic
             $mode = View_Forum_PostEdit::EDIT_TOPIC;
             /** @var  Model_Forum_Private_Topic|Model_Forum_Topic  $topic */
             $topic = $this->private ? Model_Forum_Private_Topic::factory($topic_id) : Model_Forum_Topic::factory($topic_id);
             if (!$topic->loaded()) {
                 throw new Model_Exception($topic, $topic_id);
             }
             Permission::required($topic, Model_Forum_Topic::PERMISSION_UPDATE, self::$user);
             // Build recipients list
             if ($this->private) {
                 $recipients = $topic->find_recipient_names();
             }
             $this->view->title_html = Forum::topic($topic);
             $cancel = Route::model($topic);
             // Set actions
             if (Permission::has($topic, Model_Forum_Topic::PERMISSION_DELETE, self::$user)) {
                 $this->view->actions[] = array('link' => Route::model($topic, 'delete') . '?' . Security::csrf_query(), 'text' => '<i class="icon-trash icon-white"></i> ' . __('Delete topic'), 'class' => 'btn btn-danger topic-delete');
             }
         } else {
             throw new InvalidArgumentException('Topic and area missing');
         }
     }
     $errors = array();
     if ($_POST && Security::csrf_valid()) {
         // Get recipients
         if ($this->private) {
             $post_recipients = array();
             foreach (explode(',', Arr::get_once($_POST, 'recipients')) as $recipient) {
                 if ($user = Model_User::find_user_light(trim($recipient))) {
                     $post_recipients[$user['id']] = $user['username'];
                 }
             }
             // Make sure author is included
             $post_recipients[self::$user->id] = self::$user->username;
         }
         if (isset($post)) {
             // New topic
             $post->post = $_POST['post'];
             $post->forum_area_id = $area->id;
             $post->author_id = self::$user->id;
             $post->author_name = self::$user->username;
             $post->author_ip = Request::$client_ip;
             $post->author_host = Request::host_name();
             $post->created = time();
             try {
                 $post->is_valid();
             } catch (Validation_Exception $e) {
                 $errors += $e->array->errors('validate');
             }
             $topic->author_id = self::$user->id;
             $topic->author_name = self::$user->username;
             $topic->name = $_POST['name'];
             $topic->forum_area_id = $area->id;
             $topic->created = time();
             try {
                 $topic->is_valid();
             } catch (Validation_Exception $e) {
                 $errors += $e->array->errors('validate');
             }
             // If no errors found, save models
             if (empty($errors)) {
                 $topic->save();
                 // Recipients
                 if ($this->private) {
                     $topic->set_recipients($post_recipients);
                 }
                 // Post
                 $post->forum_topic_id = $topic->id;
                 $post->save();
                 // Topic
                 $topic->first_post_id = $topic->last_post_id = $post->id;
                 $topic->last_poster = self::$user->username;
                 $topic->last_posted = time();
                 $topic->post_count = 1;
                 $topic->save();
                 // Area, only public forums
                 if (!$this->private) {
                     $area->last_topic_id = $topic->id;
                     $area->post_count++;
                     $area->topic_count++;
                     $area->save();
                 }
                 // User
                 self::$user->post_count++;
                 self::$user->save();
                 // News feed
                 if (!$this->private) {
                     NewsfeedItem_Forum::topic(self::$user, $topic);
                 }
                 $this->request->redirect(Route::model($topic));
             }
             isset($post_recipients) and $recipients = $post_recipients;
         } else {
             // Old topic
             $topic->set_fields(Arr::intersect($_POST, array('name', 'status', 'sticky')));
             try {
                 $topic->save();
                 // Recipients
                 if ($this->private) {
                     $topic->set_recipients($post_recipients);
                 }
                 $this->request->redirect(Route::model($topic));
             } catch (Validation_Exception $e) {
                 $errors = $e->array->errors('validate');
             }
         }
     }
     $form['errors'] = $errors;
     $section = $this->section_post_edit($mode, isset($post) ? $post : null);
     $section->forum_topic = $topic;
     $section->errors = $errors;
     $section->cancel = $cancel;
     $section->recipients = isset($recipients) ? implode(', ', $recipients) : null;
     $this->view->add(View_Page::COLUMN_MAIN, $section);
 }
Example #6
0
 /**
  * Edit event
  *
  * @param  integer  $event_id
  */
 protected function _edit_event($event_id = null)
 {
     $this->history = false;
     if ($event_id) {
         // Editing old
         $event = Model_Event::factory($event_id);
         if (!$event->loaded()) {
             throw new Model_Exception($event, $event_id);
         }
         Permission::required($event, Model_Event::PERMISSION_UPDATE, self::$user);
         $cancel = Request::back(Route::model($event), true);
         $this->view = View_Page::factory(HTML::chars($event->name));
         // Set actions
         if (Permission::has($event, Model_Event::PERMISSION_DELETE, self::$user)) {
             $this->view->actions[] = array('link' => Route::model($event, 'delete') . '?token=' . Security::csrf(), 'text' => '<i class="icon-trash icon-white"></i> ' . __('Delete event'), 'class' => 'btn-danger event-delete');
         }
         $edit = true;
     } else {
         // Creating new
         $event = new Model_Event();
         Permission::required($event, Model_Event::PERMISSION_CREATE, self::$user);
         $cancel = Request::back(Route::get('events')->uri(), true);
         $this->view = View_Page::factory(__('New event'));
         $event->author_id = self::$user->id;
         $event->created = time();
         $edit = false;
     }
     // Handle post
     if ($_POST && Security::csrf_valid()) {
         // Handle venue
         if ($venue_hidden = Arr::get($_POST, 'venue_hidden')) {
             // Hidden events require only city
         } else {
             if ($venue_id = (int) Arr::get_once($_POST, 'venue_id')) {
                 // Old venue
                 $venue = Model_Venue::factory($venue_id);
             } else {
                 if ($venue_name = Arr::get($_POST, 'venue_name')) {
                     // Check for duplicate venue
                     $venues = Model_Venue::factory()->find_by_name($venue_name);
                     if ($venues->count()) {
                         $city_name = strtolower(Arr::get($_POST, 'city_name'));
                         foreach ($venues as $venue_old) {
                             if (strtolower($venue_old->city_name) == $city_name) {
                                 $venue = $venue_old;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
         $post = Arr::intersect($_POST, Model_Event::$editable_fields);
         if (isset($post['stamp_begin']['date']) && isset($post['stamp_end']['time'])) {
             $post['stamp_end']['date'] = $post['stamp_begin']['date'];
         }
         $event->set_fields($post);
         if (Arr::get($_POST, 'free')) {
             $event->price = 0;
         }
         // Venue/location
         $event->venue_hidden = (bool) $venue_hidden;
         if ($venue_hidden) {
             // Hidden events don't have a venue
             $event->venue_id = null;
             $event->venue_name = null;
         } else {
             if (isset($venue)) {
                 // Venue loaded
                 $event->venue_id = $venue->id;
                 $event->city_name = $venue->city_name;
             } else {
                 if (!empty($venue_name)) {
                     // Create new venue
                     $venue = Model_Venue::factory();
                     $venue->name = Arr::get($_POST, 'venue_name');
                     $venue->address = Arr::get($_POST, 'address');
                     $venue->latitude = Arr::get($_POST, 'latitude');
                     $venue->longitude = Arr::get($_POST, 'longitude');
                     $venue->event_host = true;
                     $venue->author_id = self::$user->id;
                     $venue->city_name = $event->city_name;
                     try {
                         $venue->save();
                         $event->venue_id = $venue->id;
                     } catch (Validation_Exception $venue_validation) {
                     }
                 }
             }
         }
         // Validate event
         try {
             $event->is_valid();
         } catch (Validation_Exception $event_validation) {
         }
         // If no errors found, save
         if (!isset($venue_validation) && !isset($event_validation)) {
             // Make sure end time is after start time, i.e. the next day
             if ($event->stamp_end < $event->stamp_begin) {
                 $event->stamp_end += Date::DAY;
             }
             $event->save();
             // Set tags
             $event->set_tags(Arr::get($_POST, 'tag'));
             $edit ? NewsfeedItem_Events::event_edit(self::$user, $event) : NewsfeedItem_Events::event(self::$user, $event);
             $this->request->redirect(Route::model($event));
         }
     }
     // Fill the required information to view
     $this->view->event = $event;
     $this->view->event_errors = isset($event_validation) ? $event_validation->array->errors('validation') : null;
     $this->view->venue = isset($venue) ? $venue : null;
     $this->view->venue_errors = isset($venue_validation) ? $venue_validation->array->errors('validation') : null;
     // Tags
     $tags = array();
     $tag_group = new Model_Tag_Group('Music');
     if ($tag_group->loaded() && count($tag_group->tags())) {
         foreach ($tag_group->tags() as $tag) {
             $tags[$tag->id()] = $tag->name();
         }
     }
     // Form
     $section = $this->section_event_edit($event);
     $section->event_errors = isset($event_validation) ? $event_validation->array->errors('validation') : null;
     $section->venue = isset($venue) ? $venue : $event->venue;
     $section->venue_errors = isset($venue_validation) ? $venue_validation->array->errors('validation') : null;
     $section->cancel = $cancel;
     $this->view->add(View_Page::COLUMN_TOP, $section);
 }
Example #7
0
 /**
  * Var method for birthdays.
  *
  * @return  array
  */
 protected function _birthdays()
 {
     if ($this->_birthdays === null) {
         $today = strtotime('today');
         $stamp = strtotime('today', $this->stamp);
         $stamp_to = strtotime('+' . $this->days . ' days', $this->stamp);
         $friends = Visitor::$user ? Visitor::$user->find_friends() : null;
         // Load birthdays
         $this->_birthdays = array();
         while ($stamp < $stamp_to) {
             // Load all birthdays from date
             $birthdays = Model_User::find_by_birthday($stamp);
             $today_count = $stamp == $today ? count($birthdays) : 0;
             $birthdays_friends = $friends ? array_filter(Arr::get_once($birthdays, $friends)) : array();
             $friend_count = count($birthdays_friends);
             // Show only some birthdays
             if ($stamp != $today) {
                 // Include only friends if not today
                 $birthdays = $birthdays_friends;
             } else {
                 // Fill with random if less friends than limit
                 $birthdays_random = $this->limit ? array() : $birthdays;
                 if ($friend_count < $this->limit) {
                     if ($limit = min(count($birthdays), $this->limit - $friend_count)) {
                         $birthdays_random = Arr::extract($birthdays, array_rand($birthdays, $limit));
                     }
                 }
                 // Friends first
                 $birthdays = $birthdays_friends + $birthdays_random;
             }
             // Build day's birthdays
             if ($birthdays) {
                 $year = date('Y', $stamp);
                 $users = array();
                 foreach ($birthdays as $user_id => $dob) {
                     $users[] = array('user' => HTML::user($user_id), 'age' => $year - date('Y', strtotime($dob)));
                 }
                 // Sort by age and name
                 usort($users, function ($a, $b) {
                     if ($a['age'] > $b['age']) {
                         return -1;
                     } else {
                         if ($a['age'] < $b['age']) {
                             return 1;
                         } else {
                             return strcasecmp($a['user'], $b['user']);
                         }
                     }
                 });
                 // Build date
                 $span = $stamp - $today;
                 if ($span == 0) {
                     $date = __('Today');
                 } else {
                     if ($span == Date::DAY) {
                         $date = __('Tomorrow');
                     } else {
                         if ($span < Date::DAY * 7) {
                             $date = date('l', $stamp);
                         } else {
                             $date = Date::format(Date::DM_SHORT, $stamp);
                         }
                     }
                 }
                 // Build array
                 $_birthdays = array('date' => $date, 'users' => $users);
                 if ($today_count) {
                     $_birthdays['link'] = ($this->limit ? HTML::separator() . HTML::anchor(Route::url('users'), __('Show all')) : '') . ' (' . $today_count . ')';
                 }
                 $this->_birthdays[] = $_birthdays;
             }
             $stamp += Date::DAY;
         }
     }
     return $this->_birthdays;
 }
Example #8
0
File: page.php Project: anqh/anqh
    /**
     * Render page title.
     *
     * @return  string
     */
    protected function _title()
    {
        if ($this->title || $this->title_html || $this->actions || $this->breadcrumbs || $this->tabs) {
            ob_start();
            ?>

<header id="title" class="content">
	<div class="container">

		<?php 
            if ($this->breadcrumbs) {
                ?>
		<nav class="breadcrumbs">
			<?php 
                echo implode(' &rsaquo; ', $this->breadcrumbs);
                ?>
		</nav>
		<?php 
            }
            ?>

		<?php 
            if ($this->actions) {
                ?>
		<div class="actions pull-right">
			<?php 
                foreach ($this->actions as $action) {
                    $attributes = $action;
                    unset($attributes['link'], $attributes['text']);
                    $attributes['class'] = $attributes['class'] ? 'btn ' . $attributes['class'] : 'btn btn-default';
                    echo HTML::anchor($action['link'], $action['text'], $attributes) . ' ';
                }
                ?>
		</div>
		<?php 
            }
            ?>

		<?php 
            if ($this->title_icon) {
                ?>
		<div class="pull-left">
			<?php 
                echo $this->title_icon;
                ?>
		</div>
		<?php 
            }
            ?>

		<?php 
            if ($this->title_html || $this->title) {
                ?>
		<h1><?php 
                echo $this->title_html ? $this->title_html : HTML::chars($this->title);
                ?>
</h1>
		<?php 
            }
            ?>

		<?php 
            if ($this->subtitle) {
                ?>
		<p><?php 
                echo $this->subtitle;
                ?>
</p>
		<?php 
            }
            ?>

		<?php 
            if ($this->tabs) {
                ?>
		<ul class="nav nav-tabs">

		<?php 
                foreach ($this->tabs as $tab_id => $tab) {
                    if (is_array($tab)) {
                        // Tab is a link
                        $attributes = $tab;
                        unset($attributes['link'], $attributes['text'], $attributes['dropdown'], $attributes['active']);
                        if ($tab['dropdown']) {
                            $attributes['class'] .= ' dropdown-toggle';
                            $attributes['data-toggle'] = 'dropdown';
                            $attributes['data-target'] = '#';
                            ?>

			<li class="dropdown<?php 
                            echo $tab_id === $this->tab ? ' active' : '';
                            ?>
">
				<?php 
                            echo HTML::anchor($tab['link'], $tab['text'] . ' <span class="caret"></span>', $attributes);
                            ?>
				<ul class="dropdown-menu">
					<?php 
                            foreach ($tab['dropdown'] as $dropdown) {
                                ?>
						<?php 
                                if ($dropdown['divider']) {
                                    ?>
					<li class="divider"></li>
						<?php 
                                } else {
                                    ?>
					<li><?php 
                                    echo HTML::anchor(Arr::get_once($dropdown, 'link'), Arr::get_once($dropdown, 'text'), $dropdown);
                                    ?>
</li>
						<?php 
                                }
                                ?>
					<?php 
                            }
                            ?>
				</ul>
			</li>

		<?php 
                        } else {
                            echo '<li' . ($tab_id === $this->tab ? ' class="active"' : '') . '>' . HTML::anchor($tab['link'], $tab['text'], $attributes) . '</li>';
                        }
                    } else {
                        // Action is HTML
                        echo '<li' . ($tab_id === $this->tab ? ' class="active"' : '') . '>' . $tab . '</li>';
                    }
                }
                ?>

		</ul>
		<?php 
            }
            ?>

	</div>
</header><!-- #title -->

<?php 
            return ob_get_clean();
        }
        return '';
    }
Example #9
0
 /**
  * Wrap requested view inside module and render
  *
  * @return  string
  */
 public function render($file = null)
 {
     return (string) View::factory('generic/mod', array('class' => 'mod ' . Arr::get_once($this->_data, 'mod_class', strtr(basename($this->_file, '.php'), '_', '-')), 'id' => Arr::get_once($this->_data, 'mod_id'), 'actions' => isset($this->_data['mod_actions']) ? (string) View::factory('generic/actions', array('actions' => Arr::get_once($this->_data, 'mod_actions'))) : null, 'actions2' => isset($this->_data['mod_actions2']) ? (string) View::factory('generic/actions', array('actions' => Arr::get_once($this->_data, 'mod_actions2'))) : null, 'title' => Arr::get_once($this->_data, 'mod_title'), 'subtitle' => Arr::get_once($this->_data, 'mod_subtitle'), 'pagination' => Arr::get_once($this->_data, 'pagination'), 'content' => parent::render($file)));
 }
Example #10
0
File: events.php Project: anqh/anqh
 /**
  * Edit event
  *
  * @param  integer  $event_id
  */
 protected function _edit_event($event_id = null)
 {
     $this->history = false;
     if ($event_id) {
         // Editing old
         $event = Model_Event::factory($event_id);
         if (!$event->loaded()) {
             throw new Model_Exception($event, $event_id);
         }
         Permission::required($event, Model_Event::PERMISSION_UPDATE);
         $cancel = Request::back(Route::model($event), true);
         $this->view = View_Page::factory(HTML::chars($event->name));
         // Set actions
         if (Permission::has($event, Model_Event::PERMISSION_DELETE)) {
             $this->view->actions[] = array('link' => Route::model($event, 'delete') . '?token=' . Security::csrf(), 'text' => '<i class="fa fa-trash-o"></i> ' . __('Delete event'), 'class' => 'btn-danger event-delete');
         }
         $edit = true;
         $event->update_count++;
         $event->modified = time();
     } else {
         // Creating new
         $event = new Model_Event();
         Permission::required($event, Model_Event::PERMISSION_CREATE);
         $cancel = Request::back(Route::get('events')->uri(), true);
         $this->view = View_Page::factory(__('New event'));
         $event->author_id = Visitor::$user->id;
         $event->created = time();
         $edit = false;
     }
     // Handle post
     if ($_POST && Security::csrf_valid()) {
         $preview = isset($_POST['preview']);
         // Handle venue
         if ($venue_hidden = Arr::get($_POST, 'venue_hidden')) {
             // Hidden events require only city
         } else {
             if ($venue_id = (int) Arr::get_once($_POST, 'venue_id')) {
                 // Old venue
                 $venue = Model_Venue::factory($venue_id);
             } else {
                 if ($venue_name = Arr::get($_POST, 'venue_name')) {
                     // Check for duplicate venue
                     $venues = Model_Venue::factory()->find_by_name($venue_name);
                     if ($venues->count()) {
                         $city_name = strtolower(Arr::get($_POST, 'city_name'));
                         foreach ($venues as $venue_old) {
                             if (strtolower($venue_old->city_name) == $city_name) {
                                 $venue = $venue_old;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
         $post = Arr::intersect($_POST, Model_Event::$editable_fields);
         if (isset($post['stamp_begin']['date']) && isset($post['stamp_end']['time']) && !isset($post['stamp_end']['date'])) {
             $post['stamp_end']['date'] = $post['stamp_begin']['date'];
         }
         $event->set_fields($post);
         if (Arr::get($_POST, 'free')) {
             $event->price = 0;
         }
         // Venue/location
         $event->venue_hidden = (bool) $venue_hidden;
         if ($venue_hidden) {
             // Hidden events don't have a venue
             $event->venue_id = null;
             $event->venue_name = null;
         } else {
             if (isset($venue)) {
                 // Venue loaded
                 $event->venue_id = $venue->id;
                 $event->city_name = $venue->city_name;
             } else {
                 if (!empty($venue_name)) {
                     // Create new venue
                     $venue = Model_Venue::factory();
                     $venue->name = Arr::get($_POST, 'venue_name');
                     $venue->address = Arr::get($_POST, 'address');
                     $venue->latitude = Arr::get($_POST, 'latitude');
                     $venue->longitude = Arr::get($_POST, 'longitude');
                     $venue->foursquare_id = Arr::get($_POST, 'foursquare_id');
                     $venue->event_host = true;
                     $venue->author_id = Visitor::$user->id;
                     $venue->city_name = $event->city_name;
                     if (!$preview) {
                         try {
                             $venue->save();
                             $event->venue_id = $venue->id;
                         } catch (Validation_Exception $venue_validation) {
                         }
                     }
                 }
             }
         }
         // Validate event
         try {
             $event->is_valid();
         } catch (Validation_Exception $event_validation) {
         }
         // Handle preview request
         if ($preview) {
             if ($this->ajax) {
                 $preview = '<p>' . self::_event_subtitle($event) . '</p>';
                 $preview .= '<div id="main" class="col-md-8">';
                 $preview .= $this->section_event_main($event);
                 $preview .= '<hr></div>';
                 $this->response->body($preview);
             }
             return;
         }
         // Flyer
         if ($flyer_url = Arr::get($_POST, 'flyer')) {
             $event->flyer_url = $flyer_url;
             $image = new Model_Image();
             $image->remote = $flyer_url;
             $image->created = time();
             $image->author_id = Visitor::$user->id;
             try {
                 $image->save();
                 try {
                     $flyer = new Model_Flyer();
                     $flyer->set_fields(array('image_id' => $image->id, 'name' => $event->name, 'stamp_begin' => $event->stamp_begin));
                     $flyer->save();
                 } catch (Validation_Exception $flyer_validation) {
                     $flyer_error = print_r($flyer_validation->array->errors('validation'), true);
                 }
             } catch (Validation_Exception $image_validation) {
                 $flyer_error = print_r($image_validation->array->errors('validation'), true);
             } catch (Kohana_Exception $e) {
                 $flyer_error = $e->getMessage();
             }
         }
         // If no errors found, save
         if (!isset($venue_validation) && !isset($event_validation) && !isset($flyer_error)) {
             // Make sure end time is after start time, i.e. the next day
             if ($event->stamp_end < $event->stamp_begin) {
                 $event->stamp_end += Date::DAY;
             }
             $event->save();
             // Handle flyer
             if (isset($image) && isset($flyer) && $flyer->loaded()) {
                 $flyer->event_id = $event->id;
                 $flyer->save();
                 $event->set_flyer($flyer);
                 $event->save();
             }
             // Set tags
             $event->set_tags(Arr::get($_POST, 'tag'));
             if ($edit) {
                 // Don't flood edits right after save
                 if (time() - $event->created > 60 * 30) {
                     NewsfeedItem_Events::event_edit(Visitor::$user, $event);
                 }
             } else {
                 NewsfeedItem_Events::event(Visitor::$user, $event);
                 // Add to favorites
                 $event->add_favorite(Visitor::$user);
                 // Create forum topic
                 if ($event->add_forum_topic()) {
                     Visitor::$user->post_count++;
                     Visitor::$user->save();
                 }
             }
             $this->request->redirect(Route::model($event));
         }
     }
     // Remove orphan flyer on all errors
     if (isset($flyer)) {
         $flyer->delete();
     } else {
         if (isset($image)) {
             $image->delete();
         }
     }
     // Tags
     $tags = array();
     $tag_group = new Model_Tag_Group('Music');
     if ($tag_group->loaded() && count($tag_group->tags())) {
         foreach ($tag_group->tags() as $tag) {
             $tags[$tag->id()] = $tag->name();
         }
     }
     // Form
     $section = $this->section_event_edit($event);
     $section->event_errors = isset($event_validation) ? $event_validation->array->errors('validation') : null;
     $section->flyer_error = isset($flyer_error) ? $flyer_error : null;
     $section->venue = isset($venue) ? $venue : $event->venue;
     $section->venue_errors = isset($venue_validation) ? $venue_validation->array->errors('validation') : null;
     $section->cancel = $cancel;
     $this->view->add(View_Page::COLUMN_TOP, $section);
 }
Example #11
0
File: form.php Project: anqh/anqh
 /**
  * Creates checkboxes list.
  *
  * @param   string        $name        input name
  * @param   array         $values      input values
  * @param   array         $checked     checked statuses
  * @param   array         $attributes  html attributes
  *
  * @param   string        $label
  * @param   string|array  $error
  * @param   string|array  $tip
  * @return  string
  */
 public static function checkboxes_wrap($name, $values = array(), $checked = array(), array $attributes = null, $label = null, $error = null, $tip = null)
 {
     $list_class = 'list-unstyled ' . Arr::get_once($attributes, 'class');
     $input = '<ul class="' . $list_class . '">' . "\n";
     foreach ($values as $checkbox_value => $checkbox_title) {
         $id = self::input_id($name) . '-' . $checkbox_value;
         $input .= '<li>';
         $input .= Form::checkbox_wrap($name . '[]', $checkbox_value, isset($checked[$checkbox_value]), array('id' => $id), $checkbox_title);
         $input .= "</li>\n";
     }
     $input .= "</ul>\n";
     return Form::wrap($input, $name, $label, $error, $tip);
 }