Advertisement
imadu2310

Xclusive plugin

Dec 22nd, 2018
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 36.81 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Plugin Name:       Xclusive Custom Features
  4.  * Description:       A plugin handles login into the xclusive website as well as display of events listing from event vendors .
  5.  * Version:           1.0.0
  6.  * Author:            Rightclick (A-sin Cole)
  7.  * License:           GPL-2.0+
  8.  * Text Domain:       xclusive
  9.  */
  10.  
  11.  
  12.  class Xclusive_Plugin
  13.  {
  14.      /**
  15.      * Creates the plugin class.
  16.      *
  17.      * To keep the initialization fast, only add filter and action
  18.      * hooks in the constructor.
  19.      */
  20.      public function __construct()
  21.      {
  22.          // the code below registers the shortcode for the login form in the plugin
  23.          add_shortcode('xclusive-login-form', array( $this, 'render_login_form' ));
  24.          // code below redirects user to our custom login page
  25.          add_action('login_form_login', array( $this, 'redirect_to_custom_login' ));
  26.          add_filter('authenticate', 'wp_authenticate_username_password', 20, 3);
  27.          add_filter('authenticate', 'wp_authenticate_spam_check', 99);
  28.          add_filter('authenticate', array( $this, 'maybe_redirect_at_authenticate' ), 101, 3);
  29.          add_action('wp_logout', array( $this, 'redirect_after_logout' ));
  30.          add_filter('login_redirect', array( $this, 'redirect_after_login' ), 10, 3);
  31.          // the code below registers the shortcode for the registeration form in the plugin
  32.          add_shortcode('xclusive-register-form', array( $this, 'render_register_form' ));
  33.          // code below redirects user to our custom registration page
  34.          add_action('login_form_register', array( $this, 'redirect_to_custom_register' ));
  35.          // call registration function when user submits the form
  36.          add_action('login_form_register', array( $this, 'do_register_user' ));
  37.  
  38.          // the code below registers the shortcode for the events page in the plugin
  39.          add_shortcode('nairabox-events', array($this, 'render_events_page' ));
  40.          // the code below registers the shortcode for the movies page in the plugin
  41.          add_shortcode('nairabox-movies', array($this, 'render_movies_page'));
  42.          // the code below registers the shortcode for the afri tickets event page in the plugin
  43.          add_shortcode('afritickets-events', array($this, 'render_afrievents_page'));
  44.          // add filter for ajax calls to increment and edit data for movies tickets quota
  45.          add_action('wp_ajax_my_action', array($this,'update_nairabox_movies_quota'));
  46.          // add filter for ajax calls to increment and edit data for events tickets quota
  47.                   // add filter for ajax calls to increment and edit data for events tickets quota
  48.          add_action('wp_ajax_nairabox_events', array($this,'make_nairabox_ticket_request'));
  49.          add_action('wp_ajax_afriticket_events', array($this,'make_afriticket_request'));
  50.          
  51.          add_action('wp_ajax_get_nairabox_event_quota', array($this,'get_nairabox_event_quota'));
  52.          //  register cron job
  53.          add_action('monthly_quota_event', array($this, 'update_tickets_quota_monthly' ));
  54.      }
  55.  
  56.  
  57.      /**
  58.     * Plugin activation hook.
  59.     *
  60.     * Creates all WordPress pages needed by the plugin.
  61.     * this code runs once when plugin is activated
  62.     */
  63.  
  64.      public static function plugin_activated()
  65.      {
  66.          // Information needed for creating the plugin's pages
  67.          $page_definitions = array(
  68.             'member-login' => array(
  69.                 'title' => __('Sign In', 'xclusive'),
  70.                 'content' => '[xclusive-login-form]'
  71.             ),
  72.             'member-account' => array(
  73.                 'title' => __('Your Account', 'xclusive'),
  74.                 'content' => '[account-info]'
  75.             ),
  76.             'events-listing' => $arrayName = array(
  77.                 'title' => __('Events', 'xclusive'),
  78.                 'content' => '[nairabox-events]'
  79.             ),
  80.             'afrievents-listing' => $arrayName = array(
  81.                 'title' => __('Events', 'xclusive'),
  82.                 'content' => '[afritickets-events]'
  83.             ),
  84.             'movies-listing' => $arrayName = array(
  85.                 'title' => __('Movies', 'xclusive'),
  86.                 'content' => '[nairabox-movies]'
  87.             ),
  88.             'member-register' => array(
  89.                 'title' => __('Register', 'xclusive'),
  90.                 'content' => '[xclusive-register-form]'
  91.             ),
  92.         );
  93.    
  94.          foreach ($page_definitions as $slug => $page) {
  95.              // Check that the page doesn't exist already
  96.              $query = new WP_Query('pagename=' . $slug);
  97.              if (! $query->have_posts()) {
  98.                  // Add the page using the data from the array above
  99.                  wp_insert_post(
  100.                     array(
  101.                         'post_content'   => $page['content'],
  102.                         'post_name'      => $slug,
  103.                         'post_title'     => $page['title'],
  104.                         'post_status'    => 'publish',
  105.                         'post_type'      => 'page',
  106.                         'ping_status'    => 'closed',
  107.                         'comment_status' => 'closed',
  108.                     )
  109.                 );
  110.              }
  111.          }
  112.  
  113.         //  create movies ticket count in wordpress options table
  114.          update_option("monthly_movies_ticket_count", 1500);
  115.         //  create events ticket count in wordpress options table
  116.          update_option("quarterly_events_ticket_count", 1500);
  117.      }
  118.  
  119.      public static function send_success_message($data, $send_200){
  120.          if($send_200){
  121.              status_header(200);
  122.          }
  123.          wp_send_json_success($data);
  124.      }
  125.  
  126.      public static function send_error_message($data, $error_code){
  127.        switch ($error_code) {
  128.            case 0:
  129.                status_header(500);
  130.                wp_send_json_error($data);
  131.                break;
  132.             case 1:
  133.                status_header(400);
  134.                wp_send_json_error($data);
  135.                break;
  136.             case 2:
  137.                status_header(404);
  138.                wp_send_json_error($data);
  139.                break;
  140.            default:
  141.             status_header(500);
  142.             wp_send_json_error($data);  
  143.                break;
  144.        }
  145.     }
  146.  
  147.     public  function insert_users_into_events_table($email, $phone, $event_name){
  148.         global $wpdb;
  149.         $table_name = $wpdb->prefix . 'nairabox_events';
  150.  
  151.         $user_id = get_current_user_id();
  152.         $wpdb->insert($table_name, array('email' => $email,  'phone' => $phone, 'event_name' => $event_name, 'date'=>date("Y/m/d")));
  153.         die();
  154.     }
  155.  
  156.  
  157.      public function make_nairabox_ticket_request(){
  158.         $user = wp_get_current_user( );
  159.         $user_id = get_current_user_id();
  160.          $remote_url ="https://nairaboxapi.herokuapp.com/v1/event/purchase/";
  161.          $auth_key = "abcdefghijkl1234";
  162.          $phone = get_user_meta($user_id, 'phone', true);
  163.          $email =  $user -> user_email;
  164.          $classId = sanitize_text_field($_POST['classId']);
  165.          $qty = sanitize_text_field($_POST['qty']);
  166.          $event_name = sanitize_text_field($_POST['event_name']);
  167.          $reference =  sanitize_text_field($_POST['reference']);
  168.          $value = intval(sanitize_text_field($_POST['value']));
  169.        
  170.              //set current month
  171.             $current_month = date('m');
  172.  
  173.             //set the arguments for the request
  174.             $args = array(
  175.                      'headers' => array('Content-Type'=>'application/x-www-form-urlencoded'),
  176.                      'body' => array(
  177.                          'auth' => $auth_key,
  178.                          'email'=> $email,
  179.                          'phone'=> $phone,
  180.                          'classId'=> $classId,
  181.                          'qty' => $qty,
  182.                          'reference'=>$reference,
  183.                          )
  184.                      );
  185.             $response = wp_safe_remote_post($remote_url, $args);
  186.             if(!is_wp_error($response)){
  187.                 $body = wp_remote_retrieve_body($response);
  188.                 $body = json_decode($body,true);
  189.                 if($body['status'] === 200){
  190.                     $this ->insert_users_into_events_table($email, $phone, $event_name);
  191.                     $this ->update_nairabox_events_quota($current_month,$user_id,$value);
  192.                     $this ->send_success_message($response, $send_200);
  193.                 } elseif ($body['status'] === 400){
  194.                     $this ->update_nairabox_events_quota($current_month,$user_id,$value);
  195.                     $error_code = 1;
  196.                     $response = array(
  197.                         'success' => false,
  198.                         'message' => 'Quota exhausted',
  199.                     );
  200.                     $this ->send_error_message($response, $error_code);
  201.  
  202.                 } elseif ($body['status'] === 404) {
  203.                     $error_code = 2;
  204.                     $response = array(
  205.                         'success' => false,
  206.                         'message' => 'failed to purchase ticket',
  207.                     );
  208.                     $this ->send_error_message($response, $error_code);
  209.                 }
  210.  
  211.             } else {
  212.                 $error_code = 0;
  213.                 $this ->send_error_message($body, $error_code);
  214.             }
  215.      }
  216.  
  217.      public function make_afriticket_request(){
  218.          //set variables to make request
  219.         $user = wp_get_current_user( );
  220.         $user_id = get_current_user_id();
  221.          $remote_url ="https://afritickets.com/api/v1/premiumlux/create_usage/";
  222.          $benefit_id = "plb14821";
  223.          $key = "plb14821";
  224.          $email =  $user -> user_email;
  225.          // collet information from ajax call
  226.          $value =  intval(sanitize_text_field($_POST['value']));
  227.          $name =  sanitize_text_field($_POST['name']);
  228.          $ticket_id = sanitize_text_field($_POST['ticket_id']);
  229.          $amount = sanitize_text_field($_POST['amount']);
  230.          $event_id = sanitize_text_field($_POST['event_id']);
  231.          $event_name = sanitize_text_field($_POST['event_name']);
  232.          $reference =  sanitize_text_field($_POST['reference']);
  233.          //set current month
  234.          $current_month = date('m');
  235.  
  236.          //set the arguments for the request
  237.          $args = array(
  238.             'headers' => array('Content-Type'=>'application/x-www-form-urlencoded'),
  239.             'body' => array(
  240.                 'benefit_id' => $benefit_id,
  241.                 'key' => $key,
  242.                 'email'=> $email,
  243.                 'name'=> $name,
  244.                 'ticket_id'=> $ticket_id,
  245.                 'amount'=> $amount,
  246.                 'event_id'=>$event_id,
  247.                 'reference'=>$reference,
  248.                 )
  249.             );
  250.  
  251.             $response = wp_safe_remote_get($url,$args);
  252.             if(!is_wp_error(response)){
  253.                 $body = wp_remote_retrieve_body($response);
  254.                 $body = json_decode($body,true);
  255.                 if($body['responseCode'] === 1){
  256.                     $response = array(
  257.                         'success' => true,
  258.                         'message' => 'ticket purchased',
  259.                     );
  260.                     insert_users_into_events_table($email, $phone, $event_name);
  261.                     update_nairabox_events_quota($current_month,$user_id,$value);
  262.                     send_success_message($response, $send_200);
  263.                 } elseif ($body['responseCode'] === 5){
  264.                     $error_code = 1;
  265.                     $response = array(
  266.                         'success' => false,
  267.                         'message' => 'Quota exhausted',
  268.                     );
  269.                     update_nairabox_events_quota($current_month,$user_id,$value);
  270.                     send_error_message($response, $error_code);
  271.                 } elseif($body['responseCode'] === 6){
  272.                     $error_code = 2;
  273.                     $response = array(
  274.                         'success' => false,
  275.                         'message' => 'failed to purchase ticket',
  276.                     );
  277.                     send_error_message($response, $error_code);
  278.                 }
  279.             } else {
  280.                 $error_code = 0;
  281.                 send_error_message($response-> get_error_message(), $error_code);
  282.             }
  283.  
  284.  
  285.      }
  286.  
  287.      public function update_nairabox_events_quota($current_month,$user_id,$value)
  288.      {
  289.         //  get number of tickets user has left for the period
  290.          $events_ticket_quota_left = get_user_meta($user_id, 'events_ticket_quota_left', true);
  291.         //  check last month user redeemed ticket
  292.          $events_ticket_last_redeemed_month = get_user_meta($user_id, 'events_ticket_last_redeemed_month', true);
  293.          $current_monthly_events_ticket_count = get_option("quarterly_events_ticket_count");
  294.          if ($current_month != $events_ticket_last_redeemed_month) {
  295.             $new_monthly_events_ticket_count = $current_monthly_events_ticket_count - $value;
  296.             $new_monthly_events_ticket_count = $current_monthly_events_ticket_count - $value;
  297.              update_user_meta($user_id, 'events_ticket_last_redeemed_month', $current_month);
  298.              update_user_meta($user_id, 'events_ticket_quota_left', ($events_ticket_quota_left -  $value));
  299.              update_option("quarterly_events_ticket_count", $new_monthly_events_ticket_count);
  300.              wp_die(); // this is required to terminate immediately and return a proper response
  301.          } elseif ($current_month == $events_ticket_last_redeemed_month && $events_ticket_quota_left > 0) {
  302.              update_user_meta($user_id, 'events_ticket_quota_left', ($events_ticket_quota_left -  $value));
  303.              $new_monthly_events_ticket_count = $current_monthly_events_ticket_count - $value;
  304.              update_option("quarterly_events_ticket_count", $new_monthly_events_ticket_count);
  305.              wp_die(); // this is required to terminate immediately and return a proper response
  306.          } elseif ($current_month == $events_ticket_last_redeemed_month && $events_ticket_quota_left == 0) {
  307.              wp_die(); // this is required to terminate immediately and return a proper response
  308.          }
  309.      }
  310.  
  311.      public function update_nairabox_movies_quota()
  312.      {
  313.          $value =  intval(sanitize_text_field($_POST['value']));
  314.          $user_id = get_current_user_id();
  315.          $movies_ticket_quota_left = get_user_meta($user_id, 'movies_ticket_quota_left', true);
  316.          $movies_ticket_last_redeemed_month = get_user_meta($user_id, 'movies_ticket_last_redeemed_month', true);
  317.          $current_month = date('m');
  318.          $current_monthly_movies_ticket_count = get_option("monthly_movies_ticket_count");
  319.          if ($current_month != $movies_ticket_last_redeemed_month) {
  320.              update_user_meta($user_id, 'movies_ticket_last_redeemed_month', $current_month);
  321.              update_user_meta($user_id, 'movies_ticket_quota_left', $value);
  322.              //update_user_meta($user_id, 'movies_ticket_quota_left', ($movies_ticket_quota_left -  $value));
  323.              $new_monthly_movies_ticket_count = $current_monthly_movies_ticket_count - $value;
  324.              update_option("monthly_movies_ticket_count", $new_monthly_movies_ticket_count);
  325.  
  326.              wp_die(); // this is required to terminate immediately and return a proper response
  327.          } elseif ($current_month == $movies_ticket_last_redeemed_month && $movies_ticket_quota_left > 0) {
  328.              update_user_meta($user_id, 'movies_ticket_quota_left', ($movies_ticket_quota_left -  $value));
  329.              $new_monthly_movies_ticket_count = $current_monthly_movies_ticket_count - $value;
  330.              update_option("monthly_movies_ticket_count", $new_monthly_movies_ticket_count);
  331.              wp_die(); // this is required to terminate immediately and return a proper response
  332.          } elseif ($current_month == $movies_ticket_last_redeemed_month && $movies_ticket_quota_left == 0) {
  333.              wp_die(); // this is required to terminate immediately and return a proper response
  334.          }
  335.      }
  336.  
  337.  
  338.      public function insert_users_into_movies_table()
  339.      {
  340.         global $wpdb;
  341.         //  number of tickets retrieved from API call
  342.          $value =  intval(sanitize_text_field($_POST['value']));
  343.          $email = sanitize_text_field($_POST['user']);
  344.          $movie_title = sanitize_text_field($_POST['movie_title']);
  345.          $phone = sanitize_text_field($_POST['phone']);
  346.          $table_name = $wpdb->prefix . 'nairabox_movies';
  347.  
  348.          //get_current_user_id
  349.          $user_id = get_current_user_id();
  350.  
  351.          $wpdb->insert($table_name, array('email' => $email,  'phone' => $phone, 'qty'=> $value, 'movie_title' => $movie_title, 'date'=>date("Y/m/d")));
  352.          die();
  353.      }
  354.      
  355.  
  356.      public function get_nairabox_event_quota()
  357.      {
  358.          $user_id = get_current_user_id();
  359.          $quota_used = get_user_meta($user_id, 'movies_ticket_quota_left', true);
  360.          echo $quota_used;
  361.  
  362.          wp_die();
  363.      }
  364.  
  365.    
  366.  
  367.      /**
  368.      * A shortcode for rendering the new user registration form.
  369.      *
  370.      * @param  array   $attributes  Shortcode attributes.
  371.      * @param  string  $content     The text content for shortcode. Not used.
  372.      *
  373.      * @return string  The shortcode output
  374.      */
  375.      public function render_register_form($attributes, $content = null)
  376.      {
  377.          // Parse shortcode attributes
  378.          $default_attributes = array( 'show_title' => false );
  379.          $attributes = shortcode_atts($default_attributes, $attributes);
  380.    
  381.          if (is_user_logged_in()) {
  382.              return __('You are already signed in.', 'xclusive');
  383.          } elseif (! get_option('users_can_register')) {
  384.              return __('Registering new users is currently not allowed.', 'xclusive');
  385.          } else {
  386.              // Retrieve possible errors from request parameters
  387.              $attributes['errors'] = array();
  388.              if (isset($_REQUEST['register-errors'])) {
  389.                  $error_codes = explode(',', $_REQUEST['register-errors']);
  390.            
  391.                  foreach ($error_codes as $error_code) {
  392.                      $attributes['errors'] []= $this->get_error_message($error_code);
  393.                  }
  394.              }
  395.              return $this->get_template_html('register_form', $attributes);
  396.          }
  397.      }
  398.  
  399.      /**
  400.      * Redirects the user to the custom registration page instead
  401.      * of wp-login.php?action=register.
  402.      */
  403.      public function redirect_to_custom_register()
  404.      {
  405.          if ('GET' == $_SERVER['REQUEST_METHOD']) {
  406.              if (is_user_logged_in()) {
  407.                  $this->redirect_logged_in_user();
  408.              } else {
  409.                  wp_redirect(home_url('member-register'));
  410.              }
  411.              exit;
  412.          }
  413.      }
  414.  
  415.      /**
  416.      * Validates and then completes the new user signup process if all went well.
  417.      *
  418.      * @param string $email         The new user's email address
  419.      * @param string $first_name    The new user's first name
  420.      * @param string $last_name     The new user's last name
  421.      * @param string $phone         The user's phone number
  422.      *
  423.      * @return int|WP_Error         The id of the user that was created, or error if failed.
  424.      */
  425.      private function register_user($email, $first_name, $last_name, $phone)
  426.      {
  427.          $errors = new WP_Error();
  428.    
  429.          // Email address is used as both username and email. It is also the only
  430.          // parameter we need to validate
  431.          if (! is_email($email)) {
  432.              $errors->add('email', $this->get_error_message('email'));
  433.              return $errors;
  434.          }
  435.    
  436.          if (username_exists($email) || email_exists($email)) {
  437.              // $errors->add( 'email_exists', $this->get_error_message( 'email_exists') );
  438.              $creds = array(
  439.                 'user_login'    => $email,
  440.                 'user_password' => 'Vu0bqg^h1P7pECozLLLabILp766dssjbHH',
  441.                 'remember'      => true
  442.             );
  443.              $user = wp_signon($creds, false);
  444.              return $user;
  445.          }
  446.    
  447.          // Generate the password so that the subscriber will have to check email...
  448.          $password = 'Vu0bqg^h1P7pECozLLLabILp766dssjbHH';
  449.    
  450.          $user_data = array(
  451.             'user_login'    => $email,
  452.             'user_email'    => $email,
  453.             'user_pass'     => $password,
  454.             'first_name'    => $first_name,
  455.             'last_name'     => $last_name,
  456.             'nickname'      => $first_name,
  457.         );
  458.    
  459.          $user_id = wp_insert_user($user_data);
  460.          add_user_meta($user_id, 'phone', $phone);
  461.          // wp_new_user_notification( $user_id, $password );
  462.          
  463.         //  set current month as last time user redeemed movies ticket in wordpress options table
  464.          update_user_meta($user_id, 'movies_ticket_last_redeemed_month', date('m'));
  465.         //  set users movies ticket quota to 2
  466.          update_user_meta($user_id, 'movies_ticket_quota_left', 2);
  467.          //  set current month as last time user redeemed event ticket in wordpress options table
  468.          update_user_meta($user_id, 'events_ticket_last_redeemed_month', date('m'));
  469.          //  set users event ticket quota to 1
  470.          update_user_meta($user_id, 'events_ticket_quota_left', 1);
  471.    
  472.          // redirect_after_login(get_home_url());
  473.          return $user_id;
  474.      }
  475.  
  476.      /**
  477.      * Handles the registration of a new user.
  478.      *
  479.      * Used through the action hook "login_form_register" activated on wp-login.php
  480.      * when accessed through the registration action.
  481.      */
  482.      public function do_register_user()
  483.      {
  484.          global $prev_url, $splitted_url, $alt_url;
  485.          $prev_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
  486.          $splitted_url = parse_str(parse_url($prev_url, PHP_URL_QUERY), $queries);
  487.          $alt_url = urldecode($queries['redirect_to']);
  488.  
  489.          if ('POST' == $_SERVER['REQUEST_METHOD']) {
  490.              $redirect_url = home_url('member-register');
  491.    
  492.              if (! get_option('users_can_register')) {
  493.                  // Registration closed, display error
  494.                  $redirect_url = add_query_arg('register-errors', 'closed', $redirect_url);
  495.              } else {
  496.                  $email = $_POST['email'];
  497.                  $first_name = sanitize_text_field($_POST['first_name']);
  498.                  $last_name = sanitize_text_field($_POST['last_name']);
  499.                  $phone = sanitize_text_field(($_POST['phone']));
  500.    
  501.                  $result = $this->register_user($email, $first_name, $last_name, $phone);
  502.    
  503.                  if (is_wp_error($result)) {
  504.                      // Parse errors into a string and append as parameter to redirect
  505.                      $errors = join(',', $result->get_error_codes());
  506.                      $redirect_url = add_query_arg('register-errors', $errors, $redirect_url);
  507.                  } else {
  508.                      // Success, redirect to page where request came from .
  509.                      $redirect_url = $alt_url;
  510.                      $redirect_url  = add_query_arg('registered', $email, $redirect_url);
  511.                      if(strlen($alt_url)== 0){
  512.                         $redirect_url = home_url();
  513.                         $redirect_url = add_query_arg('registered', $email, $redirect_url);
  514.                      }
  515.  
  516.                  }
  517.              }
  518.    
  519.              wp_redirect($redirect_url);
  520.              exit;
  521.          }
  522.      }
  523.  
  524.    
  525.      /**
  526.      * A shortcode for rendering the movies page.
  527.      *
  528.      * @param  array   $attributes  Shortcode attributes.
  529.      * @param  string  $content     The text content for shortcode. Not used.
  530.      *
  531.      * @return string  The shortcode output
  532.      */
  533.      public function render_movies_page($attributes, $content = null)
  534.      {
  535.          // Parse shortcode attributes
  536.          $default_attributes = array( 'show_title' => false );
  537.          $attributes = shortcode_atts($default_attributes, $attributes);
  538.          $show_title = $attributes['show_title'];
  539.    
  540.        
  541.          // Pass the redirect parameter to the WordPress login functionality: by default,
  542.          // don't specify a redirect, but if a valid redirect URL has been passed as
  543.          // request parameter, use it.
  544.          $attributes['redirect'] = '';
  545.          if (isset($_REQUEST['redirect_to'])) {
  546.              $attributes['redirect'] = wp_validate_redirect($_REQUEST['redirect_to'], $attributes['redirect']);
  547.          }
  548.          // Error messages
  549.          $errors = array();
  550.          if (isset($_REQUEST['login'])) {
  551.              $error_codes = explode(',', $_REQUEST['login']);
  552.    
  553.              foreach ($error_codes as $code) {
  554.                  $errors []= $this->get_error_message($code);
  555.              }
  556.          }
  557.          $attributes['errors'] = $errors;
  558.  
  559.          // Check if user just logged out
  560.          $attributes['logged_out'] = isset($_REQUEST['logged_out']) && $_REQUEST['logged_out'] == true;
  561.  
  562.          // Render the login form using an external template
  563.          return $this->get_template_html('movies', $attributes);
  564.      }
  565.  
  566.  
  567.      /**
  568.      * A shortcode for rendering the events page.
  569.      *
  570.      * @param  array   $attributes  Shortcode attributes.
  571.      * @param  string  $content     The text content for shortcode. Not used.
  572.      *
  573.      * @return string  The shortcode output
  574.      */
  575.      public function render_events_page($attributes, $content = null)
  576.      {
  577.          // Parse shortcode attributes
  578.          $default_attributes = array( 'show_title' => false );
  579.          $attributes = shortcode_atts($default_attributes, $attributes);
  580.          $show_title = $attributes['show_title'];
  581.    
  582.        
  583.          // Pass the redirect parameter to the WordPress login functionality: by default,
  584.          // don't specify a redirect, but if a valid redirect URL has been passed as
  585.          // request parameter, use it.
  586.          $attributes['redirect'] = '';
  587.          if (isset($_REQUEST['redirect_to'])) {
  588.              $attributes['redirect'] = wp_validate_redirect($_REQUEST['redirect_to'], $attributes['redirect']);
  589.          }
  590.          // Error messages
  591.          $errors = array();
  592.          if (isset($_REQUEST['login'])) {
  593.              $error_codes = explode(',', $_REQUEST['login']);
  594.    
  595.              foreach ($error_codes as $code) {
  596.                  $errors []= $this->get_error_message($code);
  597.              }
  598.          }
  599.          $attributes['errors'] = $errors;
  600.  
  601.          // Check if user just logged out
  602.          $attributes['logged_out'] = isset($_REQUEST['logged_out']) && $_REQUEST['logged_out'] == true;
  603.  
  604.          // Render the login form using an external template
  605.          return $this->get_template_html('events', $attributes);
  606.      }
  607.  
  608.      /**
  609.      * A shortcode for rendering the events page.
  610.      *
  611.      * @param  array   $attributes  Shortcode attributes.
  612.      * @param  string  $content     The text content for shortcode. Not used.
  613.      *
  614.      * @return string  The shortcode output
  615.      */
  616.      public function render_afrievents_page($attributes, $content = null)
  617.      {
  618.          // Parse shortcode attributes
  619.          $default_attributes = array( 'show_title' => false );
  620.          $attributes = shortcode_atts($default_attributes, $attributes);
  621.          $show_title = $attributes['show_title'];
  622.    
  623.        
  624.          // Pass the redirect parameter to the WordPress login functionality: by default,
  625.          // don't specify a redirect, but if a valid redirect URL has been passed as
  626.          // request parameter, use it.
  627.          $attributes['redirect'] = '';
  628.          if (isset($_REQUEST['redirect_to'])) {
  629.              $attributes['redirect'] = wp_validate_redirect($_REQUEST['redirect_to'], $attributes['redirect']);
  630.          }
  631.          // Error messages
  632.          $errors = array();
  633.          if (isset($_REQUEST['login'])) {
  634.              $error_codes = explode(',', $_REQUEST['login']);
  635.    
  636.              foreach ($error_codes as $code) {
  637.                  $errors []= $this->get_error_message($code);
  638.              }
  639.          }
  640.          $attributes['errors'] = $errors;
  641.  
  642.          // Check if user just logged out
  643.          $attributes['logged_out'] = isset($_REQUEST['logged_out']) && $_REQUEST['logged_out'] == true;
  644.  
  645.          // Render the login form using an external template
  646.          return $this->get_template_html('afritickets_events', $attributes);
  647.      }
  648.  
  649.  
  650.      /**
  651.      * A shortcode for rendering the login form.
  652.      *
  653.      * @param  array   $attributes  Shortcode attributes.
  654.      * @param  string  $content     The text content for shortcode. Not used.
  655.      *
  656.      * @return string  The shortcode output
  657.      */
  658.      public function render_login_form($attributes, $content = null)
  659.      {
  660.          // Parse shortcode attributes
  661.          $default_attributes = array( 'show_title' => false );
  662.          $attributes = shortcode_atts($default_attributes, $attributes);
  663.          $show_title = $attributes['show_title'];
  664.    
  665.          if (is_user_logged_in()) {
  666.              return __('You are already signed in.', 'xclusive');
  667.          }
  668.        
  669.          // Pass the redirect parameter to the WordPress login functionality: by default,
  670.          // don't specify a redirect, but if a valid redirect URL has been passed as
  671.          // request parameter, use it.
  672.          $attributes['redirect'] = home_url();
  673.          if (isset($_REQUEST['redirect_to'])) {
  674.              $attributes['redirect'] = wp_validate_redirect($_REQUEST['redirect_to'], $attributes['redirect']);
  675.          }
  676.          // Error messages
  677.          $errors = array();
  678.          if (isset($_REQUEST['login'])) {
  679.              $error_codes = explode(',', $_REQUEST['login']);
  680.    
  681.              foreach ($error_codes as $code) {
  682.                  $errors []= $this->get_error_message($code);
  683.              }
  684.          }
  685.          $attributes['errors'] = $errors;
  686.  
  687.          // Check if user just logged out
  688.          $attributes['logged_out'] = isset($_REQUEST['logged_out']) && $_REQUEST['logged_out'] == true;
  689.  
  690.          // Render the login form using an external template
  691.          return $this->get_template_html('login_form', $attributes);
  692.      }
  693.  
  694.      /**
  695.     * Renders the contents of the given template to a string and returns it.
  696.     *
  697.     * @param string $template_name The name of the template to render (without .php)
  698.     * @param array  $attributes    The PHP variables for the template
  699.     *
  700.     * @return string               The contents of the template.
  701.     */
  702.      private function get_template_html($template_name, $attributes = null)
  703.      {
  704.          if (! $attributes) {
  705.              $attributes = array();
  706.          }
  707.    
  708.          ob_start();
  709.    
  710.          do_action('xclusive_before_' . $template_name);
  711.    
  712.          require('templates/' . $template_name . '.php');
  713.    
  714.          do_action('xclusive_after_' . $template_name);
  715.    
  716.          $html = ob_get_contents();
  717.          ob_end_clean();
  718.    
  719.          return $html;
  720.      }
  721.  
  722.      /**
  723.     * Redirect the user to the custom login page instead of wp-login.php.
  724.     */
  725.      public function redirect_to_custom_login()
  726.      {
  727.          $redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : null;
  728.        
  729.          if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  730.              $redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : null;
  731.        
  732.              if (is_user_logged_in()) {
  733.                  $this->redirect_logged_in_user($redirect_to);
  734.                  exit;
  735.              }
  736.    
  737.              // The rest are redirected to the login page
  738.              $login_url = home_url('login');
  739.              if (! empty($redirect_to)) {
  740.                  $login_url = add_query_arg('redirect_to', $redirect_to, $login_url);
  741.              }
  742.    
  743.              wp_redirect($login_url);
  744.              exit;
  745.          }
  746.      }
  747.  
  748.      /**
  749.     * Redirects the user to the correct page depending on whether he / she
  750.     * is an admin or not.
  751.     *
  752.     * @param string $redirect_to   An optional redirect_to URL for admin users
  753.     */
  754.      private function redirect_logged_in_user($redirect_to = null)
  755.      {
  756.          $user = wp_get_current_user();
  757.          if (user_can($user, 'manage_options')) {
  758.              if ($redirect_to) {
  759.                  wp_safe_redirect($redirect_to);
  760.              } else {
  761.                  wp_redirect(admin_url());
  762.              }
  763.          } else {
  764.              wp_redirect(home_url('member-account'));
  765.          }
  766.      }
  767.  
  768.      /**
  769.     * Redirect the user after authentication if there were any errors.
  770.     *
  771.     * @param Wp_User|Wp_Error  $user       The signed in user, or the errors that have occurred during login.
  772.     * @param string            $username   The user name used to log in.
  773.     * @param string            $password   The password used to log in.
  774.     *
  775.     * @return Wp_User|Wp_Error The logged in user, or error information if there were errors.
  776.     */
  777.      public function maybe_redirect_at_authenticate($user, $username, $password)
  778.      {
  779.          // Check if the earlier authenticate filter (most likely,
  780.          // the default WordPress authentication) functions have found errors
  781.          if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  782.              if (is_wp_error($user)) {
  783.                  $error_codes = join(',', $user->get_error_codes());
  784.    
  785.                  $login_url = home_url('member-login');
  786.                  $login_url = add_query_arg('login', $error_codes, $login_url);
  787.    
  788.                  wp_redirect($login_url);
  789.                  exit;
  790.              }
  791.          }
  792.    
  793.          return $user;
  794.      }
  795.  
  796.      /**
  797.     * Finds and returns a matching error message for the given error code.
  798.     *
  799.     * @param string $error_code    The error code to look up.
  800.     *
  801.     * @return string               An error message.
  802.     */
  803.      private function get_error_message($error_code)
  804.      {
  805.          switch ($error_code) {
  806.             case 'empty_username':
  807.                 return __('You do have an email address, right?', 'xclusive');
  808.    
  809.             case 'empty_password':
  810.                 return __('You need to enter a password to login.', 'xclusive');
  811.    
  812.             case 'invalid_username':
  813.                 return __(
  814.                     "We don't have any users with that email address. Maybe you used a different one when signing up?",
  815.                     'xclusive'
  816.                 );
  817.    
  818.             case 'incorrect_password':
  819.                 $err = __(
  820.                     "The password you entered wasn't quite right. <a href='%s'>Did you forget your password</a>?",
  821.                     'xclusive'
  822.                 );
  823.                 return sprintf($err, wp_lostpassword_url());
  824.          // Registration errors
  825.  
  826.             case 'email':
  827.             return __('The email address you entered is not valid.', 'xclusive');
  828.  
  829.             case 'email_exists':
  830.             return __('An account exists with this email address.', 'xclusive');
  831.  
  832.             case 'closed':
  833.             return __('Registering new users is currently not allowed.', 'xclusive');
  834.  
  835.             default:
  836.                 break;
  837.         }
  838.        
  839.          return __('An unknown error occurred. Please try again later.', 'xclusive');
  840.      }
  841.  
  842.      /**
  843.     * Redirect to custom login page after the user has been logged out.
  844.     */
  845.      public function redirect_after_logout()
  846.      {
  847.          $redirect_url = home_url('login?logged_out=true');
  848.          wp_safe_redirect($redirect_url);
  849.          exit;
  850.      }
  851.  
  852.      /**
  853.     * Returns the URL to which the user should be redirected after the (successful) login.
  854.     *
  855.     * @param string           $redirect_to           The redirect destination URL.
  856.     * @param string           $requested_redirect_to The requested redirect destination URL passed as a parameter.
  857.     * @param WP_User|WP_Error $user                  WP_User object if login was successful, WP_Error object otherwise.
  858.     *
  859.     * @return string Redirect URL
  860.     */
  861.      public function redirect_after_login($redirect_to, $requested_redirect_to, $user)
  862.      {
  863.          $redirect_url = home_url();
  864.    
  865.          if (! isset($user->ID)) {
  866.              return $redirect_url;
  867.          }
  868.    
  869.          if (user_can($user, 'manage_options')) {
  870.              // Use the redirect_to parameter if one is set, otherwise redirect to admin dashboard.
  871.              if ($requested_redirect_to == '') {
  872.                  $redirect_url = admin_url();
  873.              } else {
  874.                  $redirect_url = $requested_redirect_to;
  875.              }
  876.          } else {
  877.              // Non-admin users always go to their account page after login
  878.              $redirect_url = $alt_url;
  879.          }
  880.    
  881.          return wp_validate_redirect($redirect_url, home_url());
  882.      }
  883.  }
  884.  
  885.  // Initialize the plugin class
  886. $xclusive_pages_plugin = new Xclusive_Plugin();
  887.  
  888. // Create the custom pages on plugin activation
  889. register_activation_hook(__FILE__, array( 'Xclusive_Plugin', 'plugin_activated' ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement