Minggu, 02 Juni 2013

Multiple Event Calendar with Codeigniter

Well, after long time didn't post about sharing. Now i'm sharing about multiple event calendar with Codeigniter framework that named "Evencal" (sorry for other code that have same name.. ^_^ ).


This is an update from my event calendar. Evencal using :
  1. Codeigniter 2.1.3 update Codeigniter 3
  2. jQuery 1.7.2
  3. jQuery Colorbox
  4. CSS Notification Boxes

This is screenshoot :

At first, create code SQL for database Evencal. This application using MYSQL Database :
CREATE TABLE IF NOT EXISTS `events` (
  `event_date` date NOT NULL,
  `total_events` int(50) NOT NULL DEFAULT '0',
  PRIMARY KEY (`event_date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `event_detail` (
  `idevent` int(11) NOT NULL AUTO_INCREMENT,
  `event_date` date NOT NULL,
  `event_time` time NOT NULL,
  `event` varchar(200) NOT NULL,
  PRIMARY KEY (`idevent`),
  KEY `event_date` (`event_date`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;

ALTER TABLE `event_detail`
  ADD CONSTRAINT `event_detail_ibfk_1` FOREIGN KEY (`event_date`) REFERENCES `events` (`event_date`);

and then create controller evencal.php
class Evencal extends CI_Controller {
 function __construct(){
  parent::__construct();
  $this->load->model('evencal_model', 'evencal');
  $this->load->library('calendar', $this->_setting());
 }
 
 function index($year = null, $month = null, $day = null){
  $year  = (empty($year) || !is_numeric($year))?  date('Y') :  $year;
  $month = (is_numeric($month) &&  $month > 0 && $month < 13)? $month : date('m');
  $day   = (is_numeric($day) &&  $day > 0 && $day < 31)?  $day : date('d');
  
  $date      = $this->evencal->getDateEvent($year, $month);
  $cur_event = $this->evencal->getEvent($year, $month, $day);
  $data      = array(
      'notes' => $this->calendar->generate($year, $month, $date),
      'year'  => $year, 
      'mon'   => $month,
      'month' => $this->_month($month),
      'day'   => $day,
      'events'=> $cur_event
     );
  $this->load->view('index', $data);
 }
 
 // for convert (int) month to (string) month in Indonesian
 function _month($month){
  $month = (int) $month;
  switch($month){
   case 1 : $month = 'Januari'; Break;
   case 2 : $month = 'Februari'; Break;
   case 3 : $month = 'Maret'; Break;
   case 4 : $month = 'April'; Break;
   case 5 : $month = 'Mei'; Break;
   case 6 : $month = 'Juni'; Break;
   case 7 : $month = 'Juli'; Break;
   case 8 : $month = 'Agustus'; Break;
   case 9 : $month = 'September'; Break;
   case 10 : $month = 'Oktober'; Break;
   case 11 : $month = 'November'; Break;
   case 12 : $month = 'Desember'; Break;
  }
  return $month;
 }
 
 // get detail event for selected date
 function detail_event(){  
  $this->form_validation->set_rules('year', 'Year', 'trim|required|is_natural_no_zero|xss_clean');
  $this->form_validation->set_rules('mon', 'Month', 'trim|required|is_natural_no_zero|less_than[13]|xss_clean');
  $this->form_validation->set_rules('day', 'Day', 'trim|required|is_natural_no_zero|less_than[32]|xss_clean');
  
  if ($this->form_validation->run() == FALSE){
   echo json_encode(array('status' => false, 'title_msg' => 'Error', 'msg' => 'Please insert valid value'));
  }else{
   $data = $this->evencal->getEvent($this->input->post('year'), $this->input->post('mon'), $this->input->post('day'));
   if($data == null){
    echo json_encode(array('status' => false, 'title_msg' => 'No Event', 'msg' => 'There\'s no event in this date'));
   }else{   
    echo json_encode(array('status' => true, 'data' => $data));
   }
  }
 }
 
 // popup for adding event
 function add_event(){
  $data = array(
     'day'   => $this->input->post('day'),
     'mon'   => $this->input->post('mon'),
     'month' => $this->_month($this->input->post('mon')),
     'year'  => $this->input->post('year'),
    );
  $this->load->view('add_event', $data);
 }
 
 // do adding event for selected date
 function do_add(){
  $this->form_validation->set_rules('year', 'Year', 'trim|required|is_natural_no_zero|xss_clean');
  $this->form_validation->set_rules('mon', 'Month', 'trim|required|is_natural_no_zero|less_than[13]|xss_clean');
  $this->form_validation->set_rules('day', 'Day', 'trim|required|is_natural_no_zero|less_than[32]|xss_clean');
  $this->form_validation->set_rules('hour', 'Hour', 'trim|required|xss_clean');
  $this->form_validation->set_rules('minute', 'Minute', 'trim|required|xss_clean');
  $this->form_validation->set_rules('event', 'Event', 'trim|required|xss_clean');
  
  if ($this->form_validation->run() == FALSE){
   echo json_encode(array('status' => false, 'title_msg' => 'Error', 'msg' => 'Please insert valid value'));
  }else{
   $this->evencal->addEvent($this->input->post('year'), 
            $this->input->post('mon'), 
            $this->input->post('day'), 
            $this->input->post('hour').":".$this->input->post('minute').":00",
            $this->input->post('event'));
   echo json_encode(array('status' => true, 'time' => $this->input->post('time'), 'event' => $this->input->post('event')));
  }
 }
 
 // delete event
 function delete_event(){
  $this->form_validation->set_rules('year', 'Year', 'trim|required|is_natural_no_zero|xss_clean');
  $this->form_validation->set_rules('mon', 'Month', 'trim|required|is_natural_no_zero|less_than[13]|xss_clean');
  $this->form_validation->set_rules('day', 'Day', 'trim|required|is_natural_no_zero|less_than[32]|xss_clean');
  $this->form_validation->set_rules('del', 'ID', 'trim|required|is_natural_no_zero|xss_clean');
  
  if ($this->form_validation->run() == FALSE){
   echo json_encode(array('status' => false));
  }else{
   $rows = $this->evencal->deleteEvent($this->input->post('year'),$this->input->post('mon'),$this->input->post('day'), $this->input->post('del'));
   if($rows > 0){
    echo json_encode(array('status' => true, 'row' => $rows));
   }else{
    echo json_encode(array('status' => true, 'row' => $rows, 'title_msg' => 'No Event', 'msg' => 'There\'s no event in this date'));
   }
  }
 }
 
 // same as index() function
 function detail($year = null, $month = null, $day = null){
  $year  = (empty($year) || !is_numeric($year))?  date('Y') :  $year;
  $month = (is_numeric($month) &&  $month > 0 && $month < 13)? $month : date('m');
  $day   = (is_numeric($day) &&  $day > 0 && $day < 31)?  $day : date('d');
  
  $date      = $this->evencal->getDateEvent($year, $month);
  $cur_event = $this->evencal->getEvent($year, $month, $day);
  $data     = array(
      'notes' => $this->calendar->generate($year, $month, $date),
      'year'  => $year,
      'mon'   => $month,
      'month' => $this->_month($month),
      'day'   => $day,
      'events'=> $cur_event
     );
  $this->load->view('index', $data);
 }
 
 // setting for calendar
 function _setting(){
  return array(
   'start_day'   => 'monday',
   'show_next_prev'  => true,
   'next_prev_url'  => site_url('evencal/index'),
   'month_type'     => 'long',
            'day_type'       => 'short',
   'template'    => '{table_open}<table class="date">{/table_open}
           {heading_row_start}&nbsp;{/heading_row_start}
           {heading_previous_cell}<caption><a href="{previous_url}" class="prev_date" title="Previous Month">&lt;&lt;Prev</a>{/heading_previous_cell}
           {heading_title_cell}{heading}{/heading_title_cell}
           {heading_next_cell}<a href="{next_url}" class="next_date"  title="Next Month">Next&gt;&gt;</a></caption>{/heading_next_cell}
           {heading_row_end}<col class="weekday" span="5"><col class="weekend_sat"><col class="weekend_sun">{/heading_row_end}
           {week_row_start}<thead><tr>{/week_row_start}
           {week_day_cell}<th>{week_day}</th>{/week_day_cell}
           {week_row_end}</tr></thead><tbody>{/week_row_end}
           {cal_row_start}<tr>{/cal_row_start}
           {cal_cell_start}<td>{/cal_cell_start}
           {cal_cell_content}<div class="date_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">{content}</span></div>{/cal_cell_content}
           {cal_cell_content_today}<div class="active_date_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">{content}</span></div>{/cal_cell_content_today}
           {cal_cell_no_content}<div class="no_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">&nbsp;</span></div>{/cal_cell_no_content}
           {cal_cell_no_content_today}<div class="active_no_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">&nbsp;</span></div>{/cal_cell_no_content_today}
           {cal_cell_blank}&nbsp;{/cal_cell_blank}
           {cal_cell_end}</td>{/cal_cell_end}
           {cal_row_end}</tr>{/cal_row_end}
           {table_close}</tbody></table>{/table_close}');
 }
}

and then for the model evencal_model.php
class Evencal_model extends CI_Model {
 
 // for get all event date in one month
 function getDateEvent($year, $month){
  $year  = ($month < 10 && strlen($month) == 1) ? "$year-0$month" : "$year-$month";
  $query = $this->db->select('event_date, total_events')->from('events')->like('event_date', $year, 'after')->get();
  if($query->num_rows() > 0){
   $data = array();
   foreach($query->result_array() as $row){
    $data[(int) end(explode('-',$row['event_date']))] = $row['total_events'];
   }
   return $data;
  }else{
   return false;
  }
 }
 
 // get event detail for selected date
 function getEvent($year, $month, $day){
  $day   = ($day < 10 && strlen($day) == 1)? "0$day" : $day;
  $year  = ($month < 10 && strlen($month) == 1) ? "$year-0$month-$day" : "$year-$month-$day";
  $query = $this->db->select('idevent as id, event_time as time, event')->order_by('event_time')->get_where('event_detail', array('event_date' => $year));
  if($query->num_rows() > 0){
   return $query->result_array();
  }else{
   return null;
  }
 }
 
 // insert event
 function addEvent($year, $month, $day, $time, $event){ 
  $check = $this->db->get_where('events', array('event_date' => "$year-$month-$day"));
  if($check->num_rows() > 0){
   $this->db->query("UPDATE events SET total_events = total_events + 1 WHERE event_date = ?", array("$year-$month-$day"));
   $this->db->insert('event_detail', array('event_date' => "$year-$month-$day", 'event_time' => $time, 'event' => $event));
  }else{
   $this->db->insert('events', array('event_date' => "$year-$month-$day", 'total_events' => 1));
      $this->db->insert('event_detail', array('event_date' => "$year-$month-$day", 'event_time' => $time, 'event' => $event));
  }
  
 }
 
 // delete event
 function deleteEvent($year, $month, $day, $id){
  $this->db->delete("event_detail", array('idevent' => $id, 'event_date' => "$year-$month-$day"));
  $check = $this->db->query('SELECT count(*) as total FROM event_detail WHERE event_date = ?', array("$year-$month-$day"))->row();
  if($check->total > 0){
   $this->db->update('events', array('total_events' => $check->total), array('event_date' => "$year-$month-$day"));
  }else{
   $this->db->delete("events", array('event_date' => "$year-$month-$day"));
  }
  return $check->total;
 }
}

and for the view, just have 2 views in this application
first view, index.php
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>My Event Calendar (Evencal)</title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url()?>css/style.css"/>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/colorbox.css"/>
 <script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.7.2.min.js"></script>
 <script type="text/javascript" src="<?php echo base_url();?>js/jquery.colorbox-min.js"></script>
</head>
<body>
 <div id="evencal">
  <div class="calendar">
   <?php echo $notes?>
   <span>by <a href="http://zawaruddin.blogspot.com"><strong>zawaruddin.blogspot.com</strong></a></span>
  </div>
  <div class="event_detail">
   <h2 class="s_date">Detail Event <?php echo "$day $month $year";?></h2>
   <div class="detail_event">
    <?php 
     if(isset($events)){
      $i = 1;
      foreach($events as $e){
       if($i % 2 == 0){
        echo '<div class="info1"><h4>'.$e['time'].'<img src="'.base_url().'css/images/delete.png" class="delete" alt="" title="delete this event" day="'.$day.'" val="'.$e['id'].'" /></h4><p>'.$e['event'].'</p></div>';
       }else{
        echo '<div class="info2"><h4>'.$e['time'].'<img src="'.base_url().'css/images/delete.png" class="delete" alt="" title="delete this event" day="'.$day.'" val="'.$e['id'].'" /></h4><p>'.$e['event'].'</p></div>';
       } 
       $i++;
      }
     }else{
      echo '<div class="message"><h4>No Event</h4><p>There\'s no event in this date</p></div>';
     }
    ?>
    <input type="button" name="add" value="Add Event" val="<?php echo $day;?>" class="add_event"/>
   </div>
  </div>
 </div>
 <script>
  $(".detail").live('click',function(){
   $(".s_date").html("Detail Event for "+$(this).attr('val')+" <?php echo "$month $year";?>");
   var day = $(this).attr('val');
   var add = '<input type="button" name="add" value="Add Event" val="'+day+'" class="add_event"/>';
   $.ajax({
    type: 'post',
    dataType: 'json',
    url: "<?php echo site_url("evencal/detail_event");?>",
    data:{<?php echo "year: $year, mon: $mon";?>, day: day},
    success: function( data ) {
     var html = '';
     if(data.status){
      var i = 1;
      $.each(data.data, function(index, value) {
          if(i % 2 == 0){
        html = html+'<div class="info1"><h4>'+value.time+'<img src="<?php echo base_url();?>css/images/delete.png" class="delete" alt="" title="delete this event" day="'+day+'" val="'+value.id+'" /></h4><p>'+value.event+'</p></div>';
       }else{
        html = html+'<div class="info2"><h4>'+value.time+'<img src="<?php echo base_url();?>css/images/delete.png" class="delete" alt="" title="delete this event" day="'+day+'" val="'+value.id+'" /></h4><p>'+value.event+'</p></div>';
       } 
       i++;
      });
     }else{
      html = '<div class="message"><h4>'+data.title_msg+'</h4><p>'+data.msg+'</p></div>';
     }
     html = html+add;
     $( ".detail_event" ).fadeOut("slow").fadeIn("slow").html(html);
    } 
   });
  });
  $(".delete").live("click", function() {
   if(confirm('Are you sure delete this event ?')){
    var deleted = $(this).parent().parent();
    var day =  $(this).attr('day');
    var add = '<input type="button" name="add" value="Add Event" val="'+day+'" class="add_event"/>';
    $.ajax({
     type: 'POST',
     dataType: 'json',
     url: "<?php echo site_url("evencal/delete_event");?>",
     data:{<?php echo "year: $year, mon: $mon";?>, day: day,del: $(this).attr('val')},
     success: function(data) {
      if(data.status){
       if(data.row > 0){
        $('.d'+day).html(data.row);
       }else{
        $('.d'+day).html('');
        $( ".detail_event" ).fadeOut("slow").fadeIn("slow").html('<div class="message"><h4>'+data.title_msg+'</h4><p>'+data.msg+'</p></div>'+add);
       }
       deleted.remove();
      }else{
       alert('an error for deleting event');
      }
     }
    });
   }
  });
  $(".add_event").live('click', function(){
   $.colorbox({ 
     overlayClose: false,
     href: '<?php echo site_url('evencal/add_event');?>',
     data:{year:<?php echo $year;?>,mon:<?php echo $mon;?>, day: $(this).attr('val')}
   });
  });
</script>
</body>
</html>

and second view for add event form, add_event.php
<?php 
 $h = '<select name="hour" id="hour">';
 $m = '<select name="minute" id="minute">';
 for($i = 0; $i< 60; $i++){
  if($i < 24){
   $h .= '<option value="'.(($i > 9)? $i : "0$i").'">'.(($i > 9)? $i : "0$i").'</option>';
  }
  $m .= '<option value="'.(($i > 9)? $i : "0$i").'">'.(($i > 9)? $i : "0$i").'</option>';
 }
 $h .= '</select>';
 $m .= '</select>';
?>
<div style="width:500px; height:135px; overflow:auto; color:#000000; margin-bottom:20px;" align="center">
 <h4>Adding event for <?php echo "$day $month $year"?></h4>
 <div class="spacer"></div>
 <table>
  <tr><td>Time <span class="require">*</span></td><td>:</td><td><?php echo "$h&nbsp;:&nbsp;$m";?>&nbsp;:&nbsp;<select name="second" disabled><option value="00">00</option></select></td></tr>
  <tr><td>Event <span class="require">*</span></td><td>:</td><td><input type="text" name="event" id="event" maxlength="50" size="50" /></td></tr>
  <tr><td colspan="2"></td><td><input type="button" name="cancel" value="Cancel" class="cancel">&nbsp;&nbsp;
          <input type="button" name="save" value="Save" class="save"></td></tr>
 </table>
 <script> 
 $('.cancel').click(function(){
  var data = false;
  $.fn.colorbox.close(data);
 });
 $('.save').click(function(){
  if($('#event').val().length > 0){
   $.ajax({
    type: 'POST',
    dataType: 'json',
    url: "<?php echo site_url("evencal/do_add");?>",
    data:{<?php echo "year:$year,mon:$mon,day:$day";?>, hour:$('#hour').val(), minute: $('#minute').val(), event:$('#event').val()},
    success: function(data) {
     if(data.status){
      //$.fn.colorbox.close(data);
      window.location = '<?php echo site_url("evencal/detail/$year/$mon/$day")?>';
     }else{
      $('.spacer').html(data.message);
     }
    }
   });
  }else{
   $('.spacer').html('Please complete the field')
   $('#event').attr('class','error_require');
  }
 });
 </script>
</div>

and last, for autoload component in codeigniter
$autoload['libraries'] = array('database','form_validation');
$autoload['helper'] = array('url','form','html');

That's all about my sharing for Multiple Event Calendar - Evencal with codeigniter.
Sorry about my english :D
You can download the source here.

Keywords : Codeigniter Multiple Event Calendar,  Event Calendar, Calendar

To appreciate the IPR (Intellectual Property Rights), reference sources that I use and I have learned will be displayed.
Referensi    : Codeigniter User Guide,
                    www.paulund.co.uk/giveaway-10-css-notification-boxes-for-free
                    www.jacklmoore.com/colorbox
Author        : Moch. Zawaruddin Abdullah, www.zawaruddin.blogspot.com

Rabu, 10 April 2013

PHP send email via GMAIL SMTP from localhost

At this time i want to share about how to send email using sendmail tools (in XAMPP) via GMAIL SMTP from localhost.

First we must download sendmail tools with ssl (GMAIL SMTP recommend to use ssl connection). We can donwload at glob.com.au/sendmail or in my backup here. Then extract the file to C:\\XAMPP\sendmail
Open sendmail.ini and edit code like this
smtp_server=smtp.gmail.com
smtp_port=587

error_logfile=error.log
debug_logfile=debug.log

auth_username=xxx@gmail.com
auth_password=xxx

you can ignore other code in sendmail.ini,

Open php.ini, find word with key "[mail function]" then edit like this
[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost

; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = Off

; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log = "C:\xampp\php\logs\php_mail.log"

save php.ini and restart your apache.

Now, test to send an email
<?php
 $headers  = 'MIME-Version: 1.0' . "\r\n";
 $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 $headers  = 'From: administrator<sender@test.jp>' . "\r\n";
 $headers .= 'Reply To: no-reply@test.jp' . "\r\n";
 $message  = "仮登録いただき、ありがとうございます。";
 mail('receiver', '仮登録完了のお知らせ', $message, $headers); // using sendmail + ssl for send an email.
?>
that's all.
I hope it can help you for send email via GMAIL SMTP from localhost. :)

Sorry about my english :D

Keyword : php mail, sendmail, email

To appreciate the IPR (Intellectual Property Rights), reference sources that I use and I have learned will be displayed.
Referensi    : forums.devshed.com/mail-server-help-111, php.net, stackoverflow.com, blog.rosihanari.net/cara-mengirim-email-dengan-script-php-di-localhost-via-xampp
Author        : Moch. Zawaruddin Abdullah, www.zawaruddin.blogspot.com

Instal Framework Yii di Windows

Pada kali ini saya akan sharing tentang framework php selain Codeigniter yang beberapa hari ini baru saya pelajari yaitu framework Yii. (Hari gini baru blajar Yii.... sama :P)

Kali ini saya akan membahas mengenai tahap instalali dan setting dasar framework Yii sesuai dengan yang saya pelajari. Jadi mohon maaf apabila ada bagian yang sekiranya salah, maklum baru belajar.. hehehe :)

langsung saja, pertama-tama yang dibutuhkan adalah
  1. framework Yii, bisa di download www.yiiframework.com. untuk sekarang yang saya pakai adalah Yii 1.1.13 bisa didapat juga di sini 
  2. web server, untuk web server saya pake XAMPP 1.7.7
Setelah download framework Yii, ekstrak file zip ke dalam folder htdocs yang ada pada XAMPP web server, kemudian rename foldernya menjadi yii.

Selanjutnya lakukan proses membangun aplikasi web menggunakan Yii, caranya
  1. buka cmd, pindah ke path C:\\xampp\htdocs
  2. ketik yii\framework\yiic webapp coba_yii
  3. apabila terdapat message "'"php.exe"' is not recognized as an internal or external command, operable program or batch file."  
  4. lakukan langkah berikut
  • tutup cmd, klik START, klik kanan computer, klik propertise
  • pilih advanced system setting, kemudian buka "environment variables"
  • kemudian buat variabel PATH baru atau edit jika sudah ada dan isikan nilai "C:\xampp\php"(untuk lebih enaknya masukin aja ke user variable dan system variable... hehe)
  • klik ok, keluar dari system propertise,  buka kembali cmd,
  • lakukan kembali proses ke 2.
Apabila proses generate aplikasi berhasil, maka akan terdapat folder "coba_yii" didalam folder  C:\\xampp\htdocs.

(OPTIONAL) untuk kenyamanan atau suka menggabungkan framework Yii dengan aplikasi yang dibuat, copy kan folder yii tadi ke dalam folder coba_yii , kemudian buka file index.php yang ada di folder coba_yii, edit bagian
$yii=dirname(__FILE__).'/../yii/framework/yii.php'; 
menjadi 
$yii=dirname(__FILE__).'/yii/framework/yii.php';
Sekarang coba jalankan aplikasi memanggil alamat "localhost\coba_yii"
Selamat mencoba

Keyword : Instalasi Yii,  install Yii, Yii Windows

Untuk menghargai HKI(Hak Kekayaan Intelektual), sumber referensi yang saya pakai dan saya pelajari akan ditampilkan.
Referensi    : www.yiiframework.com, antik.web.id,
Author        : Moch. Zawaruddin Abdullah, www.zawaruddin.blogspot.com