public static function do_job()
 {
     //error_log("******* in the chronos ********");
     $job_batch = get_option("rm_option_jobman_job", null);
     if ($job_batch == null) {
         return;
     }
     //echo "<br>Batch:<br>";
     //return;
     //self::log_var_dump($job_batch);
     $gopts = new RM_Options();
     $from_email = $gopts->get_value_of('senders_email_formatted');
     $header = "From: {$from_email}\r\n";
     $header .= "MIME-Version: 1.0\r\n";
     $header .= "Content-Type: text/html; charset=utf-8\r\n";
     foreach ($job_batch as $key => $job) {
         $results = RM_DBManager::get_submissions_for_form($job->form_id, $job->job_size, $job->offset);
         //echo "<br>in foreach:<br>";
         //var_dump($results);
         if ($results != false) {
             foreach ($results as $result) {
                 //error_log("Doing a job, email: " . $result->user_email);
                 $sub_values = maybe_unserialize($result->data);
                 $processed_msg = $job->mail_packet['message'];
                 foreach ($job->form_fields as $field_placeholder) {
                     $abab = explode("_", $field_placeholder);
                     $field_id = $abab[1];
                     if (isset($sub_values[$field_id])) {
                         if (is_array($sub_values[$field_id]->value)) {
                             $sub_values[$field_id]->value = implode(",", $sub_values[$field_id]->value);
                         }
                         $processed_msg = str_replace("{{" . $field_placeholder . "}}", $sub_values[$field_id]->value, $processed_msg);
                     }
                 }
                 $cron_mail = new stdClass();
                 $cron_mail->to = $result->user_email;
                 $cron_mail->header = $header;
                 $cron_mail->message = wpautop($processed_msg);
                 $cron_mail->subject = $job->mail_packet['subject'];
                 $cron_mail->attachments = array();
                 RM_Utilities::send_mail($cron_mail);
                 //wp_mail($result->user_email,
                 //$job->mail_packet['subject'] ,
                 //$processed_msg,
                 //$header);
             }
             $job_batch[$key]->offset += count($results);
             //$job->job_size;
             if ($job->callback !== null) {
                 $job->callback(true);
             }
         }
         if ($job_batch[$key]->offset >= $job_batch[$key]->total) {
             unset($job_batch[$key]);
         }
     }
     update_option("rm_option_jobman_job", $job_batch);
 }
 /**
  * Register the stylesheets for the public-facing side of the site.
  *
  * @since    1.0.0
  * 
  */
 public function enqueue_styles()
 {
     $settings = new RM_Options();
     $theme = $settings->get_value_of('theme');
     $layout = $settings->get_value_of('form_layout');
     switch ($theme) {
         case 'classic':
             if ($layout == 'label_top') {
                 wp_enqueue_style('rm_theme_classic_label_top', plugin_dir_url(__FILE__) . 'css/theme_rm_classic_label_top.css', array(), $this->version, 'all');
             } elseif ($layout == 'two_columns') {
                 wp_enqueue_style('rm_theme_classic_two_columns', plugin_dir_url(__FILE__) . 'css/theme_rm_classic_two_columns.css', array(), $this->version, 'all');
             } else {
                 wp_enqueue_style('rm_theme_classic', plugin_dir_url(__FILE__) . 'css/theme_rm_classic.css', array(), $this->version, 'all');
             }
             break;
             /*case 'blue' :
                  if ($layout == 'label_top')
                      wp_enqueue_style('rm_theme_blue_label_top', plugin_dir_url(__FILE__) . 'css/theme_rm_blue_label_top.css', array(), $this->version, 'all');
                  elseif ($layout == 'two_columns')
                      wp_enqueue_style('rm_theme_blue_two_columns', plugin_dir_url(__FILE__) . 'css/theme_rm_blue_two_columns.css', array(), $this->version, 'all');
                  else
                      wp_enqueue_style('rm_theme_blue', plugin_dir_url(__FILE__) . 'css/theme_rm_blue.css', array(), $this->version, 'all');
                  break;
               */
         /*case 'blue' :
              if ($layout == 'label_top')
                  wp_enqueue_style('rm_theme_blue_label_top', plugin_dir_url(__FILE__) . 'css/theme_rm_blue_label_top.css', array(), $this->version, 'all');
              elseif ($layout == 'two_columns')
                  wp_enqueue_style('rm_theme_blue_two_columns', plugin_dir_url(__FILE__) . 'css/theme_rm_blue_two_columns.css', array(), $this->version, 'all');
              else
                  wp_enqueue_style('rm_theme_blue', plugin_dir_url(__FILE__) . 'css/theme_rm_blue.css', array(), $this->version, 'all');
              break;
           */
         default:
             if ($layout == 'label_top') {
                 wp_enqueue_style('rm_theme_matchmytheme_label_top', plugin_dir_url(__FILE__) . 'css/theme_rm_matchmytheme_label_top.css', array(), $this->version, 'all');
             } else {
                 wp_enqueue_style('rm_theme_matchmytheme', plugin_dir_url(__FILE__) . 'css/theme_rm_matchmytheme.css', array(), $this->version, 'all');
             }
             break;
     }
     //wp_enqueue_style('rm-jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css', false, $this->version, 'all');
     wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/style_rm_front_end.css', array(), $this->version, 'all');
 }
 public function notify_users($note)
 {
     $gopt = new RM_Options();
     if ($gopt->get_value_of('user_notification_for_notes') == "yes") {
         if ($note->get_status() != 'publish') {
             return;
         }
         $submission = new RM_Submissions();
         $submission->load_from_db($note->get_submission_id());
         $email = new stdClass();
         //echo '<pre>';
         //print_r($submission); die;
         $email->to = $submission->get_user_email();
         $from_email = $gopt->get_value_of('senders_email_formatted');
         $header = "From: {$from_email}\r\n";
         $header .= "MIME-Version: 1.0\r\n";
         $header .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
         $email->subject = get_bloginfo('name', 'display') . " Notification from Admin ";
         $email->message = RM_UI_Strings::get('MSG_NOTE_FROM_ADMIN') . $note->get_notes();
         $email->header = $header;
         $email->attachments = array();
         RM_Utilities::send_mail($email);
     }
 }
 public function migrate_submissions($offset = 0, $limit = 9999999)
 {
     global $wpdb;
     $qry = "";
     $fields = array();
     $pfields = array();
     $plogs = array();
     $form_field = array();
     $data_mapping = $this->value_map['submissions'];
     $dst_data = array();
     $dst_data_sub = array();
     $users = array();
     $emails = array();
     $dbcolumns = array('sub_field_id', 'submission_id', 'field_id', 'form_id', 'value');
     $dbcolumns_sub = array('submission_id', 'form_id', 'data', 'user_email', 'submitted_on', 'unique_token');
     //$dbcolumns_sub_ph = array('%d', '%d', '%s', '%s', '%s', '%s');
     //$dbcolumns_ph = array('%d', '%d', '%d', '%d', '%s');
     $dbcolumns_sub_ph = "(%d,%d,%s,%s,%s,%s)";
     $dbcolumns_ph = "(%d,%d,%d,%d,%s)";
     $all_sub = array();
     $all_sub_fields = array();
     $table_name_fields = $wpdb->prefix . 'crf_fields';
     $table_name_pfields = $wpdb->prefix . 'crf_fields';
     $table_name_plogs = $wpdb->prefix . 'crf_paypal_log';
     $table_name_src = $wpdb->prefix . 'crf_submissions';
     $table_name_dst = $wpdb->prefix . 'rm_submission_fields';
     $table_name_dst_sub = $wpdb->prefix . 'rm_submissions';
     $table_name_fields_rm = $wpdb->prefix . 'rm_fields';
     $options = new RM_Options();
     $srcdata = $wpdb->get_results("SELECT * FROM {$table_name_src} WHERE 1 LIMIT {$offset}, {$limit}");
     $fieldsdata = $wpdb->get_results("SELECT * FROM {$table_name_fields} WHERE 1");
     $pfieldsdata = $wpdb->get_results("SELECT * FROM {$table_name_pfields} WHERE 1");
     $plogsdata = $wpdb->get_results("SELECT * FROM {$table_name_plogs} WHERE 1");
     if (is_array($fieldsdata)) {
         foreach ($fieldsdata as $f_data) {
             $fields[$f_data->Id] = $f_data;
             if (!isset($form_field[$f_data->Form_Id])) {
                 $form_field[$f_data->Form_Id] = array();
             }
             if (!isset($form_field[$f_data->Form_Id][$f_data->Type])) {
                 $form_field[$f_data->Form_Id][$f_data->Type] = $f_data->Id;
             }
         }
         unset($fieldsdata);
         if (is_array($plogsdata)) {
             foreach ($plogsdata as $p_data) {
                 $log = maybe_unserialize($p_data->log);
                 $plogs[$log['custom']] = $log['mc_currency'];
             }
         }
         unset($plogsdata);
         if (is_array($pfieldsdata)) {
             foreach ($pfieldsdata as $p_data) {
                 $pfields[$p_data->Id] = $p_data;
             }
         }
         unset($pfieldsdata);
         $i = 0;
         if ($srcdata && is_array($srcdata)) {
             foreach ($srcdata as $s) {
                 $dst_data[$i] = array();
                 $is_row_valid = true;
                 if (isset($form_field[$s->form_id]['email'])) {
                     $ef_id = $form_field[$s->form_id]['email'];
                 } else {
                     $ef_id = 0;
                 }
                 if (!isset($dst_data_sub[$s->submission_id])) {
                     $dst_data_sub[$s->submission_id] = array();
                     foreach ($dbcolumns_sub as $index) {
                         $dst_data_sub[$s->submission_id][$index] = null;
                     }
                     $dst_data_sub[$s->submission_id]['submission_id'] = $s->submission_id;
                     $dst_data_sub[$s->submission_id]['form_id'] = $s->form_id;
                     $dst_data_sub[$s->submission_id]['data'] = array();
                 }
                 foreach ($data_mapping as $a => $b) {
                     $value = $s->{$a};
                     if ($a === 'field') {
                         switch ($s->{$a}) {
                             case 'first_name':
                                 if (isset($form_field[$s->form_id]['first_name'])) {
                                     $f_id = $form_field[$s->form_id]['first_name'];
                                     $value = $fields[$f_id]->Id;
                                     $dst_data_sub[$s->submission_id]['data'][$value] = new stdClass();
                                     $dst_data_sub[$s->submission_id]['data'][$value]->label = stripslashes($fields[$f_id]->Name);
                                     $dst_data_sub[$s->submission_id]['data'][$value]->value = stripslashes($s->value);
                                 } else {
                                     $dst_data_sub[$s->submission_id]['data']['first_name'] = new stdClass();
                                     $dst_data_sub[$s->submission_id]['data']['first_name']->label = 'first_name';
                                     $dst_data_sub[$s->submission_id]['data']['first_name']->value = stripslashes($s->value);
                                 }
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['first_name'] = $s->value;
                                 break;
                             case 'last_name':
                                 if (isset($form_field[$s->form_id]['last_name'])) {
                                     $f_id = $form_field[$s->form_id]['last_name'];
                                     $value = $fields[$f_id]->Id;
                                     $dst_data_sub[$s->submission_id]['data'][$value] = new stdClass();
                                     $dst_data_sub[$s->submission_id]['data'][$value]->label = stripslashes($fields[$f_id]->Name);
                                     $dst_data_sub[$s->submission_id]['data'][$value]->value = stripslashes($s->value);
                                 } else {
                                     $dst_data_sub[$s->submission_id]['data']['last_name'] = new stdClass();
                                     $dst_data_sub[$s->submission_id]['data']['last_name']->label = 'last_name';
                                     $dst_data_sub[$s->submission_id]['data']['last_name']->value = stripslashes($s->value);
                                 }
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['last_name'] = $s->value;
                                 break;
                             case 'description':
                                 if (isset($form_field[$s->form_id]['description'])) {
                                     $f_id = $form_field[$s->form_id]['description'];
                                     $value = $fields[$f_id]->Id;
                                     $dst_data_sub[$s->submission_id]['data'][$value] = new stdClass();
                                     $dst_data_sub[$s->submission_id]['data'][$value]->label = stripslashes($fields[$f_id]->Name);
                                     $dst_data_sub[$s->submission_id]['data'][$value]->value = stripslashes($s->value);
                                 } else {
                                     $dst_data_sub[$s->submission_id]['data']['description'] = new stdClass();
                                     $dst_data_sub[$s->submission_id]['data']['description']->label = 'description';
                                     $dst_data_sub[$s->submission_id]['data']['description']->value = stripslashes($s->value);
                                 }
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['bio'] = $s->value;
                                 break;
                             case 'token':
                                 $dst_data_sub[$s->submission_id]['unique_token'] = $s->value;
                                 $is_row_valid = false;
                                 break;
                             case 'entry_time':
                                 $dst_data_sub[$s->submission_id]['submitted_on'] = RM_Utilities::get_current_time($s->value);
                                 $is_row_valid = false;
                                 break;
                             case 'user_email':
                                 $dst_data_sub[$s->submission_id]['user_email'] = $s->value;
                                 $dst_data_sub[$s->submission_id]['data']['user_email'] = new stdClass();
                                 $dst_data_sub[$s->submission_id]['data']['user_email']->label = 'user_email';
                                 $dst_data_sub[$s->submission_id]['data']['user_email']->value = stripslashes($s->value);
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['user_email'] = $s->value;
                                 break;
                             case 'form_type':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['form_type'] = $s->value;
                                 break;
                             case 'user_approval':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['user_approval'] = $s->value;
                                 break;
                             case 'role':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['role'] = $s->value;
                                 break;
                             case 'payment_status':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['payment_status'] = $s->value;
                                 break;
                             case 'user_name':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['user_name'] = $s->value;
                                 break;
                             case 'user_pass':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['user_pass'] = $s->value;
                                 break;
                             case 'pass_encrypt':
                                 $is_row_valid = false;
                                 if (!isset($users[$s->submission_id])) {
                                     $users[$s->submission_id] = array();
                                 }
                                 $users[$s->submission_id]['pass_encrypt'] = $s->value;
                                 break;
                             default:
                                 $tmp = explode('_', $s->{$a});
                                 $f_id = array_pop($tmp);
                                 if (is_numeric($f_id)) {
                                     $label = implode('_', $tmp);
                                     $value = $f_id;
                                     if (isset($fields[$f_id]) && $fields[$f_id]->Name === $label) {
                                         switch ($fields[$f_id]->Type) {
                                             case 'checkbox':
                                             case 'repeatable_text':
                                                 $s->value = maybe_serialize(explode(',', $s->value));
                                                 break;
                                             case 'DatePicker':
                                                 $x = explode('-', $s->value);
                                                 $s->value = $x[1] . '/' . $x[2] . '/' . $x[0];
                                                 break;
                                             case 'file':
                                                 $x = explode(',', $s->value);
                                                 $x['rm_field_type'] = 'File';
                                                 $s->value = maybe_serialize($x);
                                                 break;
                                             case 'pricing':
                                                 if (isset($plogs[$s->submission_id])) {
                                                     $curr = $plogs[$s->submission_id];
                                                 } else {
                                                     $curr = get_option('crf_currency');
                                                 }
                                                 if (!$curr) {
                                                     $curr = 'USD';
                                                 }
                                                 if ($pfields[$fields[$f_id]->Value]->Type === 'checkbox') {
                                                     $v = array();
                                                     $ab = explode(',', $s->value);
                                                     foreach ($ab as $ba) {
                                                         $ac = explode('_', $ba);
                                                         $pr = array_pop($ac);
                                                         $pr_name = implode('_', $ac);
                                                         $v[] = $pr_name . '(' . $options->get_formatted_amount($pr, $curr) . ')';
                                                     }
                                                     $s->value = maybe_serialize($v);
                                                 } elseif ($pfields[$fields[$f_id]->Value]->Type === 'checkbox') {
                                                     $ac = explode('_', $ba);
                                                     $pr = array_pop($ac);
                                                     $pr_name = implode('_', $ac);
                                                     $s->value = $pr_name . '(' . $options->get_formatted_amount($pr, $curr) . ')';
                                                 } else {
                                                     $s->value = $options->get_formatted_amount($s->value, $curr);
                                                 }
                                                 break;
                                         }
                                         if ($ef_id === $f_id && !isset($emails[$s->submission_id])) {
                                             $emails[$s->submission_id] = new stdClass();
                                             $emails[$s->submission_id]->id = $ef_id;
                                             $emails[$s->submission_id]->value = $s->value;
                                         }
                                         $dst_data_sub[$s->submission_id]['data'][$f_id] = new stdClass();
                                         $dst_data_sub[$s->submission_id]['data'][$f_id]->label = stripslashes($fields[$f_id]->Name);
                                         $dst_data_sub[$s->submission_id]['data'][$f_id]->value = maybe_unserialize($s->value);
                                     } else {
                                         $dst_data_sub[$s->submission_id]['data'][$f_id] = new stdClass();
                                         $dst_data_sub[$s->submission_id]['data'][$f_id]->label = stripslashes($label);
                                         $dst_data_sub[$s->submission_id]['data'][$f_id]->value = maybe_unserialize($s->value);
                                     }
                                 } else {
                                     $is_row_valid = false;
                                 }
                                 break;
                         }
                     }
                     if ($is_row_valid) {
                         if (isset($s->{$a}) && $value !== null) {
                             $dst_data[$i][$b] = $value;
                         } else {
                             $dst_data[$i][$b] = null;
                         }
                     }
                 }
                 if ($is_row_valid) {
                     $i++;
                 } else {
                     $dst_data[$i] = array();
                 }
             }
             if ($dst_data && count($dst_data) !== 0) {
                 $qry .= "INSERT INTO {$table_name_dst} (`" . implode('`,`', $dbcolumns) . "`) values ";
                 $i = 0;
                 foreach ($dst_data as $d) {
                     if (is_array($d) && count($d) !== 0) {
                         foreach ($d as $d_single) {
                             $all_sub_fields[] = $d_single;
                         }
                         if ($i === 0) {
                             $qry .= $dbcolumns_ph;
                         } else {
                             $qry .= ", " . $dbcolumns_ph;
                         }
                         $i++;
                     }
                 }
                 $qry_sub = "INSERT INTO {$table_name_dst_sub} (`" . implode('`,`', $dbcolumns_sub) . "`) values ";
                 $i = 0;
                 foreach ($dst_data_sub as $sub_id => $d_sub) {
                     if (!isset($d_sub['user_email'])) {
                         if (isset($emails[$sub_id])) {
                             $dst_data_sub[$sub_id] = $emails[$sub_id]->value;
                             $this->created[] = $d_sub['form_id'];
                             $wpdb->update($table_name_fields_rm, array('is_field_primary' => 1), array('field_id' => $emails[$sub_id]->id), '%d', '%d');
                         } else {
                             $dst_data_sub[$sub_id] = null;
                         }
                     }
                     if (isset($d_sub['data'])) {
                         $d_sub['data'] = maybe_serialize($d_sub['data']);
                     }
                     if (is_array($d_sub) && count($d_sub) !== 0) {
                         foreach ($d_sub as $d_sub_single) {
                             $all_sub[] = $d_sub_single;
                         }
                         if ($i === 0) {
                             $qry_sub .= $dbcolumns_sub_ph;
                         } else {
                             $qry_sub .= ", " . $dbcolumns_sub_ph;
                         }
                         $i++;
                     }
                 }
             } else {
                 error_log('no_data_sub_fields');
             }
             if (count($users) !== 0) {
                 foreach ($users as $user) {
                     if ($user['form_type'] === 'reg_form' && (isset($user['user_approval']) && $user['user_approval'] != 'yes' || isset($user['payment_status']) && $user['payment_status'] === 'pending') && isset($user['user_email']) && is_email($user['user_email']) && !email_exists($user['user_email']) && isset($user['user_pass']) && isset($user['user_name'])) {
                         $password = null;
                         if (isset($user['pass_encrypt']) && $user['pass_encrypt'] == 1) {
                             $password = $this->crf_encrypt_decrypt_pass('decrypt', $user['user_pass']);
                             $password = $this->enc_str($password);
                         } else {
                             $password = $user['user_pass'];
                         }
                         $user_id = wp_create_user($user['user_name'], $password, $user['user_email']);
                         update_user_meta($user_id, 'rm_user_status', 1);
                         if (isset($user['first_name']) && $user['first_name']) {
                             update_user_meta($user_id, 'first_name', 1);
                         }
                         if (isset($user['last_name']) && $user['last_name']) {
                             update_user_meta($user_id, 'last_name', 1);
                         }
                         if (isset($user['bio']) && $user['bio']) {
                             update_user_meta($user_id, 'description', 1);
                         }
                     }
                 }
             }
             //$qry = esc_sql($qry);
             //error_log("Query: ".$qry);
             $result = $wpdb->query($wpdb->prepare($qry, $all_sub_fields));
             if (!$result) {
                 error_log('submission_fields_not_migrated');
             }
             $result_sub = $wpdb->query($wpdb->prepare($qry_sub, $all_sub));
             if (!$result_sub) {
                 error_log('submissions_not_migrated');
             }
             return;
         }
     }
     return false;
 }
 public function facebook_login_callback()
 {
     global $rm_env_requirements;
     if (!($rm_env_requirements & RM_REQ_EXT_CURL)) {
         return;
     }
     global $rm_fb_sdk_req;
     $gopts = new RM_Options();
     $fb_app_id = $gopts->get_value_of('facebook_app_id');
     $fb_app_secret = $gopts->get_value_of('facebook_app_secret');
     if (!$fb_app_id || !$fb_app_secret) {
         return;
     }
     if ($rm_fb_sdk_req === RM_FB_SDK_REQ_OK) {
         $fb = new Facebook\Facebook(array('app_id' => $fb_app_id, 'app_secret' => $fb_app_secret, 'default_graph_version' => 'v2.2'));
         $helper = $fb->getRedirectLoginHelper();
         try {
             $accessToken = $helper->getAccessToken();
         } catch (Facebook\Exceptions\FacebookResponseException $e) {
             // When Graph returns an error
             echo 'Graph returned an error: ' . $e->getMessage();
             exit;
         } catch (Facebook\Exceptions\FacebookSDKException $e) {
             // When validation fails or other local issues
             echo 'Facebook SDK returned an error: ' . $e->getMessage();
             exit;
         }
         if (!isset($accessToken)) {
             if ($helper->getError()) {
                 header('HTTP/1.0 401 Unauthorized');
                 echo "Error: " . $helper->getError() . "\n";
                 echo "Error Code: " . $helper->getErrorCode() . "\n";
                 echo "Error Reason: " . $helper->getErrorReason() . "\n";
                 echo "Error Description: " . $helper->getErrorDescription() . "\n";
             } else {
                 header('HTTP/1.0 400 Bad Request');
                 echo 'Bad request';
             }
             exit;
         }
         // Logged in
         // echo '<h3>Access Token</h3>';
         //var_dump($accessToken->getValue());
         // The OAuth 2.0 client handler helps us manage access tokens
         $oAuth2Client = $fb->getOAuth2Client();
         // Get the access token metadata from /debug_token
         $tokenMetadata = $oAuth2Client->debugToken($accessToken);
         //echo '<h3>Metadata</h3>';
         //var_dump($tokenMetadata);
         // Validation (these will throw FacebookSDKException's when they fail)
         $tokenMetadata->validateAppId($fb_app_id);
         // Replace {app-id} with your app id
         // If you know the user ID this access token belongs to, you can validate it here
         //$tokenMetadata->validateUserId('123');
         $tokenMetadata->validateExpiration();
         if (!$accessToken->isLongLived()) {
             // Exchanges a short-lived access token for a long-lived one
             try {
                 $accessToken2 = $oAuth2Client->getLongLivedAccessToken($accessToken);
             } catch (Facebook\Exceptions\FacebookSDKException $e) {
                 echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
                 exit;
             }
             //echo '<h3>Long-lived</h3>';
             //var_dump($accessToken2->getValue());
         }
         //$_SESSION['fb_access_token'] = (string) $accessToken;
         try {
             // Returns a `Facebook\FacebookResponse` object
             $response = $fb->get('/me?fields=id,name,email,first_name,last_name', (string) $accessToken);
         } catch (Facebook\Exceptions\FacebookResponseException $e) {
             echo 'Graph returned an error: ' . $e->getMessage();
             exit;
         } catch (Facebook\Exceptions\FacebookSDKException $e) {
             echo 'Facebook SDK returned an error: ' . $e->getMessage();
             exit;
         }
         $user = $response->getGraphUser();
         //var_dump($user->getFirstName());
         $user_name = $user->getName();
         $user_email = $user->getEmail();
         $user_name = $user->getName();
         $user_fname = $user->getFirstName();
         $user_lname = $user->getLastName();
         $redirection_post = $gopts->get_value_of('post_submission_redirection_url');
         if (email_exists($user_email)) {
             // user is a member
             $user = get_user_by('email', $user_email);
             $user_id = $user->ID;
             wp_set_auth_cookie($user_id, true);
         } else {
             // this user is a guest
             $random_password = wp_generate_password(10, false);
             $user_id = wp_create_user($user_email, $random_password, $user_email);
             if (!is_wp_error($user_id)) {
                 if (function_exists('is_multisite') && is_multisite()) {
                     add_user_to_blog(get_current_blog_id(), $user_id, 'subscriber');
                 }
                 update_user_meta($user_id, 'avatar_image', 'https://graph.facebook.com/' . $user->getId() . '/picture?type=large');
                 wp_update_user(array('ID' => $user_id, 'display_name' => $user_name, 'first_name' => $user_fname, 'last_name' => $user_lname));
                 wp_set_auth_cookie($user_id, true);
             }
         }
     } else {
         $fb = new Facebook(array('appId' => $fb_app_id, 'secret' => $fb_app_secret));
         $user = $fb->getUser();
         if ($user) {
             $user_profile = $fb->api('/me?fields=id,name,email,first_name,last_name');
             if (isset($user_profile['email'])) {
                 $user_email = $user_profile['email'];
                 $redirection_post = $gopts->get_value_of('post_submission_redirection_url');
                 if (email_exists($user_email)) {
                     // user is a member
                     $user = get_user_by('email', $user_email);
                     $user_id = $user->ID;
                     wp_set_auth_cookie($user_id, true);
                 } else {
                     // this user is a guest
                     $random_password = wp_generate_password(10, false);
                     $user_id = wp_create_user($user_email, $random_password, $user_email);
                     if (!is_wp_error($user_id)) {
                         if (function_exists('is_multisite') && is_multisite()) {
                             add_user_to_blog(get_current_blog_id(), $user_id, 'subscriber');
                         }
                         update_user_meta($user_id, 'avatar_image', 'https://graph.facebook.com/' . $user_profile['id'] . '/picture?type=large');
                         wp_update_user(array('ID' => $user_id, 'display_name' => $user_profile['name'], 'first_name' => $user_profile['first_name'], 'last_name' => $user_profile['last_name']));
                         wp_set_auth_cookie($user_id, true);
                     }
                 }
             } else {
                 die('Error: Unable to fetch email address from Facebbok.');
             }
         }
     }
     if ($redirection_post > 0) {
         $after_login_url = get_permalink($redirection_post);
     } else {
         $after_login_url = home_url();
     }
     RM_Utilities::redirect($after_login_url);
 }
    public function include_scripts()
    {
        $options = new RM_Options();
        $fab_color = $options->get_value_of('fab_color');
        $fab_theme = $options->get_value_of('fab_theme');
        ?>
            <link rel="stylesheet" href="<?php 
        echo RM_BASE_URL;
        ?>
public/css/floating-button.css" type="text/css"> 
            <script type="text/javascript">
                var rm_fab_theme = '<?php 
        echo $fab_theme;
        ?>
';
                var rm_fab_color = '<?php 
        echo $fab_color;
        ?>
';
                var ajaxurl = '<?php 
        echo admin_url('admin-ajax.php');
        ?>
'; 
            </script>
            <script src="<?php 
        echo RM_BASE_URL;
        ?>
public/js/modernizr-custom.min.js" type="text/javascript"></script>
            <script src="<?php 
        echo RM_BASE_URL;
        ?>
admin/js/jscolor.min.js" type="text/javascript"></script>
            <script src="<?php 
        echo RM_BASE_URL;
        ?>
public/js/floating-button.js" type="text/javascript"></script>
            <?php 
    }
 public function view($model, RM_Services $service, $request, $params)
 {
     if (isset($request->req['rm_submission_id'])) {
         if (!$model->load_from_db($request->req['rm_submission_id'])) {
             $view = $this->mv_handler->setView('show_notice');
             $data = RM_UI_Strings::get('MSG_DO_NOT_HAVE_ACCESS');
             $view->render($data);
         } else {
             if (isset($request->req['rm_action']) && $request->req['rm_action'] == 'delete') {
                 $request->req['rm_form_id'] = $model->get_form_id();
                 $request->req['rm_selected'] = $request->req['rm_submission_id'];
                 $this->remove($model, $service, $request, $params);
                 unset($request->req['rm_selected']);
             } else {
                 $settings = new RM_Options();
                 $data = new stdClass();
                 $data->submission = $model;
                 $data->payment = $service->get('PAYPAL_LOGS', array('submission_id' => $model->get_submission_id()), array('%d'), 'row', 0, 99999);
                 if ($data->payment != null) {
                     $data->payment->total_amount = $settings->get_formatted_amount($data->payment->total_amount, $data->payment->currency);
                     if ($data->payment->log) {
                         $data->payment->log = maybe_unserialize($data->payment->log);
                     }
                 }
                 $data->notes = $service->get('NOTES', array('submission_id' => $model->get_submission_id()), array('%d'), 'results', 0, 99999, '*', null, true);
                 $i = 0;
                 if (is_array($data->notes)) {
                     foreach ($data->notes as $note) {
                         $data->notes[$i]->author = get_userdata($note->published_by)->display_name;
                         if ($note->last_edited_by) {
                             $data->notes[$i++]->editor = get_userdata($note->last_edited_by)->display_name;
                         } else {
                             $data->notes[$i++]->editor = null;
                         }
                     }
                 }
                 /*
                  * Check submission type
                  */
                 $form = new RM_Forms();
                 $form->load_from_db($model->get_form_id());
                 $form_type = $form->get_form_type() == "1" ? "Registration" : "Contact";
                 $data->form_type = $form_type;
                 $data->form_type_status = $form->get_form_type();
                 //$data->form_name = $form->get_form_name();
                 $data->form_is_unique_token = $form->get_form_is_unique_token();
                 /*
                  * User details if form is registration type
                  */
                 if ($form->get_form_type() == "1") {
                     $email = $model->get_user_email();
                     if ($email != "") {
                         $user = get_user_by('email', $email);
                         $data->user = $user;
                     }
                 }
                 $view = $this->mv_handler->setView('view_submission');
                 $view->render($data);
             }
         }
     } else {
         throw new InvalidArgumentException(RM_UI_Strings::get('MSG_INVALID_SUBMISSION_ID'));
     }
 }
 public function save_fab_settings($theme, $color)
 {
     $option = new RM_Options();
     if ($theme) {
         $option->set_value_of('fab_theme', $theme);
     }
     if ($color) {
         $option->set_value_of('fab_color', $color);
     }
     echo 'dhfdkf';
     die;
 }
 public function create_form($form_id)
 {
     //Load form from database
     $this->backend_form = new RM_Forms();
     $this->backend_form->load_from_db($form_id);
     //Update form diary
     global $rm_form_diary;
     if (isset($rm_form_diary[$form_id])) {
         $rm_form_diary[$form_id]++;
     } else {
         $rm_form_diary[$form_id] = 1;
     }
     $primary_field_req_names = array();
     //Load corresponding fields from db
     $fields = array();
     $db_fields = $this->service->get_all_form_fields($form_id);
     if ($db_fields) {
         foreach ($db_fields as $db_field) {
             $field_options = maybe_unserialize($db_field->field_options);
             $form_options = $this->backend_form->get_form_options();
             if (isset($form_options->style_textfield)) {
                 $field_options->style_textfield = $form_options->style_textfield;
             }
             if (isset($form_options->style_label)) {
                 $field_options->style_label = $form_options->style_label;
             }
             $opts = $this->service->set_properties($field_options);
             $db_field->field_value = maybe_unserialize($db_field->field_value);
             $field_name = $db_field->field_type . "_" . $db_field->field_id;
             $db_field->field_label = $db_field->field_label;
             if (isset($field_options->icon)) {
                 $x_opts = (object) array('icon' => $field_options->icon);
             } else {
                 $x_opts = null;
             }
             switch ($db_field->field_type) {
                 case 'Price':
                     $gopts = new RM_Options();
                     $currency_pos = $gopts->get_value_of('currency_symbol_position');
                     $currency_symbol = $gopts->get_currency_symbol();
                     $fields[$field_name] = new RM_Frontend_Field_Price($db_field->field_id, $db_field->field_label, $opts, $db_field->field_value, $currency_pos, $currency_symbol, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'File':
                     $fields[$field_name] = new RM_Frontend_Field_File($db_field->field_id, $db_field->field_label, $opts, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Select':
                     $fields[$field_name] = new RM_Frontend_Field_Select($db_field->field_id, $db_field->field_label, $opts, $db_field->field_value, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Multi-Dropdown':
                     break;
                 case 'Phone':
                     break;
                 case 'Mobile':
                     break;
                 case 'Nickname':
                     $fields[$field_name] = new RM_Frontend_Field_Base($db_field->field_id, 'Nickname', $db_field->field_label, $opts, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Image':
                     break;
                 case 'Facebook':
                     break;
                 case 'Website':
                     $opts['Pattern'] = "((?:https?\\:\\/\\/|www\\.)(?:[-a-z0-9]+\\.)*[-a-z0-9]+.*)";
                     //$opts['Title'] =  RM_UI_Strings::get("WEBSITE_ERROR");
                     $fields[$field_name] = new RM_Frontend_Field_Base($db_field->field_id, 'Website', $db_field->field_label, $opts, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Twitter':
                     break;
                 case 'Google':
                     break;
                 case 'Instagram':
                     break;
                 case 'Linked':
                     break;
                 case 'SoundCloud':
                     break;
                 case 'Youtube':
                     break;
                 case 'VKontacte':
                     break;
                 case 'Skype':
                     break;
                 case 'Bdate':
                     break;
                 case 'SecEmail':
                     break;
                 case 'Gender':
                     break;
                 case 'Language':
                     break;
                 case 'Terms':
                     $opts['cb_label'] = isset($field_options->tnc_cb_label) ? $field_options->tnc_cb_label : null;
                 case 'Radio':
                 case 'Checkbox':
                     $classname = "RM_Frontend_Field_" . $db_field->field_type;
                     $fields[$field_name] = new $classname($db_field->field_id, $db_field->field_label, $opts, $db_field->field_value, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Shortcode':
                     $classname = "RM_Frontend_Field_Visible_Only";
                     $db_field->field_value = do_shortcode($db_field->field_value);
                     $fields[$field_name] = new $classname($db_field->field_id, 'HTMLCustomized', $field_name, $db_field->field_label, $opts, $db_field->field_value, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Divider':
                     $classname = "RM_Frontend_Field_Visible_Only";
                     $fields[$field_name] = new $classname($db_field->field_id, 'HTMLCustomized', $field_name, $db_field->field_label, $opts, ' <hr class="rm_divider" width="100%" size="8" align="center">', $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Spacing':
                     $classname = "RM_Frontend_Field_Visible_Only";
                     $fields[$field_name] = new $classname($db_field->field_id, 'HTMLCustomized', $field_name, $db_field->field_label, $opts, '<div class="rm_spacing"></div>', $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'HTMLH':
                 case 'HTMLP':
                     $classname = "RM_Frontend_Field_Visible_Only";
                     $fields[$field_name] = new $classname($db_field->field_id, $db_field->field_type, $db_field->field_label, $opts, $db_field->field_value, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Time':
                     break;
                 case 'Rating':
                     break;
                 case 'Email':
                     // in this case pre-populate the primary email field with logged-in user's email.
                     if ($db_field->is_field_primary) {
                         $primary_field_req_names['user_email'] = $db_field->field_type . "_" . $db_field->field_id;
                         if (is_user_logged_in()) {
                             $current_user = wp_get_current_user();
                             $opts['value'] = $current_user->user_email;
                         }
                     }
                     $fields[$field_name] = new RM_Frontend_Field_Base($db_field->field_id, $db_field->field_type, $db_field->field_label, $opts, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
                 case 'Address':
                 case 'Map':
                     break;
                 default:
                     $fields[$field_name] = new RM_Frontend_Field_Base($db_field->field_id, $db_field->field_type, $db_field->field_label, $opts, $db_field->page_no, $db_field->is_field_primary, $x_opts);
                     break;
             }
         }
     }
     switch ($this->backend_form->get_form_type()) {
         case RM_REG_FORM:
             $this->frontend_form = new RM_Frontend_Form_Reg($this->backend_form);
             $primary_field_req_names['username'] = '******';
             $primary_field_req_names['password'] = '******';
             $this->frontend_form->set_primary_field_index($primary_field_req_names);
             break;
             //Contact form is default case to keep compatibility with previous code
         //Contact form is default case to keep compatibility with previous code
         default:
             //$this->frontend_form = new RM_Frontend_Form_Multipage($this->backend_form);
             $this->frontend_form = new RM_Frontend_Form_Contact($this->backend_form);
             $this->frontend_form->set_primary_field_index($primary_field_req_names);
             break;
     }
     $this->frontend_form->add_fields_array($fields);
     $this->frontend_form->set_form_number($rm_form_diary[$form_id]);
     //Set up FE form object
     //Return  new FE form
     return $this->frontend_form;
 }
 public static function disable_review_banner()
 {
     $options = new RM_Options();
     $options->set_value_of('done_with_review_banner', 'yes');
 }
 public function get_submissions_to_export($form_id, $is_searched = false, $search = null)
 {
     $export_data = array();
     $is_payment = false;
     $option = new RM_Options();
     if (!(int) $form_id) {
         return false;
     }
     $fields = $this->get_all_form_fields($form_id);
     if (!$fields) {
         return false;
     }
     $field_ids = array();
     foreach ($fields as $field) {
         if ($field->field_type != 'Price' && $field->field_type != 'HTMLH' && $field->field_type != 'HTMLP') {
             $field_ids[] = $field->field_id;
             $export_data[0][$field->field_id] = $field->field_label;
         }
         $i = 0;
         if ($field->field_type == 'price' && $i == 0) {
             $is_payment = true;
             $export_data[0]['invoice'] = 'Payment Invoice';
             $export_data[0]['txn_id'] = 'Payment TXN Id';
             $export_data[0]['status'] = 'Payment Status';
             $export_data[0]['total_amount'] = 'Paid Amount';
             $export_data[0]['date'] = 'Date of Payment';
             $i++;
         }
     }
     if (!$is_searched && !$search instanceof stdClass) {
         $submission_ids = $this->get('SUBMISSIONS', array('form_id' => $form_id), array('%d'), 'col', 0, 999999, 'submission_id', null, true);
         if (!$submission_ids) {
             return false;
         }
         $submissions = RM_DBManager::get_results_for_array('SUBMISSION_FIELDS', 'field_id', $field_ids);
     } else {
         $submission_ids = RM_DBManager::get_results_for_last_col($search->interval, $form_id, $search->id, $search->value);
         if (!$submission_ids) {
             return false;
         }
         $submissions = RM_DBManager::get_sub_fields_for_array('SUBMISSION_FIELDS', 'field_id', $field_ids, 'submission_id', $submission_ids);
     }
     foreach ($submission_ids as $s_id) {
         $export_data[$s_id] = array();
         $payment = $this->get('PAYPAL_LOGS', array('submission_id' => $s_id), array('%d'), 'row', 0, 10, '*', null, true);
         foreach ($field_ids as $f_id) {
             $export_data[$s_id][$f_id] = null;
         }
         if ($is_payment) {
             $export_data[$s_id]['invoice'] = isset($payment->invoice) ?: null;
             $export_data[$s_id]['txn_id'] = isset($payment->txn_id) ?: null;
             $export_data[$s_id]['status'] = isset($payment->status) ?: null;
             $export_data[$s_id]['total_amount'] = isset($payment->total_amount) ? $option->get_formatted_amount($payment->total_amount, $payment->currency) : null;
             $export_data[$s_id]['date'] = isset($payment->posted_date) ? RM_Utilities::localize_time($payment->posted_date, get_option('date_format')) : null;
         }
     }
     foreach ($submissions as $submission) {
         $value = maybe_unserialize($submission->value);
         if (is_array($value)) {
             if (isset($value['rm_field_type']) && $value['rm_field_type'] == 'File') {
                 unset($value['rm_field_type']);
                 if (count($value) == 0) {
                     $value = null;
                 } else {
                     $file = array();
                     foreach ($value as $a) {
                         $file[] = wp_get_attachment_url($a);
                     }
                     $value = implode(',', $file);
                 }
             } else {
                 $value = implode(',', $value);
             }
         }
         if (array_key_exists($submission->submission_id, $export_data)) {
             $export_data[$submission->submission_id][$submission->field_id] = stripslashes($value);
         }
     }
     return $export_data;
 }
 public static function set_default_form()
 {
     if (isset($_POST['rm_def_form_id'])) {
         $gopts = new RM_Options();
         $gopts->set_value_of('default_form_id', $_POST['rm_def_form_id']);
     }
     die;
 }
 public function fab($model, $service, $request)
 {
     $setting = new RM_Options();
     if ($setting->get_value_of('display_floating_action_btn') === 'yes') {
         $param = new stdClass();
         $param->action_btn_style = 'background-color:#' . $setting->get_value_of('floating_icon_bck_color');
         $param->default_form = (int) $setting->get_value_of('default_form_id');
         $floating_widget = new RM_Floating_Widget($param);
         $floating_widget->show_widget();
     }
 }
 public function isValid($value)
 {
     $valid = true;
     $name_explode = explode("_", $this->name);
     $field_id = $name_explode[1];
     $field = new RM_Fields();
     $gopts = new RM_Options();
     $field->load_from_db($field_id);
     //Sanitize value before use, remove white space, trim extra pipes.
     $fv = explode("|", trim(preg_replace('/\\s+/', '', $field->get_field_value()), '|'));
     $allowed_types = array();
     $multiple = $gopts->get_value_of('allow_multiple_file_uploads');
     if (!$fv || count($fv) === 1 && $fv[0] == "") {
         $allowed_types = explode("|", $gopts->get_value_of('allowed_file_types'));
     } else {
         foreach ($fv as $key => $value) {
             $fv[$key] = strtolower($value);
         }
         $allowed_types = $fv;
     }
     //die;
     if ($multiple == "yes") {
         if (isset($_FILES[$this->name]) && !empty($_FILES[$this->name])) {
             foreach ($_FILES[$this->name]['name'] as $filename) {
                 if ($filename == "") {
                     if (!$this->isRequiredFileField) {
                         return true;
                     } else {
                         $this->message = " %element% " . RM_UI_Strings::get('ERROR_REQUIRED');
                         return false;
                     }
                 } elseif (strpos($filename, '.') === 0) {
                     return false;
                 } elseif (strpos($filename, '.') === false) {
                     return false;
                 } else {
                     $arrx = explode('.', $filename);
                     $ext = $arrx[count($arrx) - 1];
                     if ($ext == "") {
                         return false;
                     }
                     $ext = strtolower($ext);
                     if (!in_array($ext, $allowed_types)) {
                         return false;
                     }
                 }
             }
             return true;
         }
         return true;
     } else {
         if (isset($_FILES[$this->name]) && !empty($_FILES[$this->name])) {
             $filename = $_FILES[$this->name]['name'];
             if ($filename == "") {
                 if (!$this->isRequiredFileField) {
                     return true;
                 } else {
                     $this->message = " %element% " . RM_UI_Strings::get('ERROR_REQUIRED');
                     return false;
                 }
             } elseif (strpos($filename, '.') === 0) {
                 return false;
             } elseif (strpos($filename, '.') === false) {
                 return false;
             } else {
                 $arrx = explode('.', $filename);
                 $ext = $arrx[count($arrx) - 1];
                 if ($ext == "") {
                     return false;
                 }
                 if (!in_array($ext, $allowed_types)) {
                     return false;
                 }
             }
             return true;
         }
         return true;
     }
     return false;
 }
 public function prepare_email($type, $submissions, $form, $request = '')
 {
     $email = new stdClass();
     $email_content = '<div class="mail-wrapper">';
     if ($submissions != null) {
         $data = $submissions->get_data();
     }
     $gopt = new RM_Options();
     $values = '';
     if ($type == "to_admin") {
         /*
          * Loop through serialized data for submission
          */
         foreach ($data as $val) {
             $email_content .= '<div class="row"> <span class="key">' . $val->label . ':</span>';
             if (is_array($val->value)) {
                 $values = '';
                 // Check attachment type field
                 if (isset($val->value['rm_field_type']) && $val->value['rm_field_type'] == 'File') {
                     unset($val->value['rm_field_type']);
                     /*
                      * Grab all the attachments as links
                      */
                     foreach ($val->value as $attachment_id) {
                         $values .= wp_get_attachment_link($attachment_id) . '    ';
                     }
                     $email_content .= '<span class="key-val">' . $values . '</span><br/>';
                 } else {
                     $email_content .= '<span class="key-val">' . implode(', ', $val->value) . '</span><br/>';
                 }
             } else {
                 $email_content .= '<span class="key-val">' . $val->value . '</span><br/>';
             }
         }
         $email->message = $email_content . "</div>";
         // Prepare recipients
         $to = array();
         $header = '';
         if ($gopt->get_value_of('admin_notification') == "yes") {
             $to = explode(',', $gopt->get_value_of('admin_email'));
         } else {
             $to = null;
         }
         $subject = $form->form_name . " " . RM_UI_Strings::get('LABEL_NEWFORM_NOTIFICATION') . " ";
         $from_email = $gopt->get_value_of('senders_email_formatted');
         $header = "From: {$from_email}\r\n";
         $header .= "Content-Type: text/html; charset=utf-8\r\n";
         $email->to = $to;
         $email->header = $header;
         $email->subject = $subject;
         $email->attachments = array();
     }
     if ($type == "to_registrar") {
         /* Preparing content for front end notification */
         $email_content .= wpautop($form->form_options->form_email_content) . '<br><br>';
         foreach ($request->req as $key => $val) {
             //echo "<pre", var_dump($request->req),die;
             if (!is_array($val)) {
                 $email_content = str_replace('{{' . $key . '}}', $val, $email_content);
             } else {
                 $email_content = str_replace('{{' . $key . '}}', implode(',', $val), $email_content);
             }
         }
         $out = array();
         $preg_result = preg_match_all('/{{(.*?)}}/', $email_content, $out);
         if ($preg_result) {
             $id_vals = array();
             foreach ($request->req as $key => $val) {
                 //$val would be like '{field_type}_{field_id}'
                 $key_parts = explode('_', $key);
                 $k_c = count($key_parts);
                 if ($k_c >= 2 && is_numeric($key_parts[$k_c - 1])) {
                     if (is_array($val)) {
                         $val = implode(",", $val);
                     }
                     if ($key_parts[0] === 'Fname' || $key_parts[0] === 'Lname' || $key_parts[0] === 'BInfo') {
                         $id_vals[$key_parts[0]] = $val;
                     } else {
                         $id_vals[$key_parts[1]] = $val;
                     }
                 }
             }
             foreach ($out[1] as $caught) {
                 //echo "<br>".$caught;
                 $x = explode("_", $caught);
                 $id = $x[count($x) - 1];
                 if (is_numeric($id)) {
                     if (isset($id_vals[(int) $id])) {
                         $email_content = str_replace('{{' . $caught . '}}', $id_vals[(int) $id], $email_content);
                     }
                 } else {
                     switch ($caught) {
                         case 'first_name':
                             if (isset($id_vals['Fname'])) {
                                 $email_content = str_replace('{{' . $caught . '}}', $id_vals['Fname'], $email_content);
                             }
                             break;
                         case 'last_name':
                             if (isset($id_vals['Lname'])) {
                                 $email_content = str_replace('{{' . $caught . '}}', $id_vals['Lname'], $email_content);
                             }
                             break;
                         case 'description':
                             if (isset($id_vals['BInfo'])) {
                                 $email_content = str_replace('{{' . $caught . '}}', $id_vals['BInfo'], $email_content);
                             }
                             break;
                     }
                 }
                 //Blank the placeholder if still any remaining.
                 $email_content = str_replace('{{' . $caught . '}}', '', $email_content);
             }
         }
         $email->message = $email_content . "</div>";
         $email->subject = $form->form_options->form_email_subject ?: RM_UI_Strings::get('MAIL_REGISTRAR_DEF_SUB');
         $email->to = $submissions->get_user_email();
         $email->attachments = array();
         $from_email = $gopt->get_value_of('senders_email_formatted');
         $header = "From: {$from_email}\r\n";
         $header .= "Content-Type: text/html; charset=utf-8\r\n";
         $email->header = $header;
     }
     if ($type == "new_user") {
         //$email->message = "Your account has been successfully created on ".get_bloginfo( 'name', 'display' ).". You can now login using following credentials:<br>Username : $request->username<br>Password : $request->password";
         $msg = RM_UI_Strings::get('MAIL_BODY_NEW_USER_NOTIF');
         $msg = str_replace('%SITE_NAME%', get_bloginfo('name', 'display'), $msg);
         $msg = str_replace('%USER_NAME%', $request->username, $msg);
         $msg = str_replace('%USER_PASS%', $request->password, $msg);
         $email->message = $email_content . $msg . "</div>";
         $email->subject = RM_UI_Strings::get('MAIL_NEW_USER_DEF_SUB');
         $email->to = $request->email;
         $email->attachments = array();
         $from_email = $gopt->get_value_of('senders_email_formatted');
         $header = "From: {$from_email}\r\n";
         $header .= "Content-Type: text/html; charset=utf-8\r\n";
         $email->header = $header;
     } elseif ($type === 'user_activation') {
         $user_email = $request->email;
         /* $boundary = uniqid('rm');
         
                       $header_html = "Content-type: text/html;charset=utf-8\r\n\r\n";
                       $header_text = "Content-type: text/plain;charset=utf-8\r\n\r\n"; */
         /* $msg_text = 'A new user has been regitered on %SITE_NAME%. \r\n User Name : %USER_NAME% \r\n User Email : %USER_EMAIL% \r\n\r\n Please click on the link below to activate the user.';
         
                       $msg_text = str_replace('%SITE_NAME%', get_bloginfo('name', 'display'), $msg_text);
                       $msg_text = str_replace('%USER_NAME%', $params->username, $msg_text);
                       $msg_text = str_replace('%USER_EMAIL%', $user_email, $msg_text); */
         //$msg_css = '<style type=text/css> .mail-wrapper{ border: 1px solid black; padding: 20px; background-color: #fdfdfd; box-shadow: .1px .1px 8px .1px grey; font-size: 14px; font-family: monospace; } a.rm_btn{ border: 1px solid; padding: 4px; background-color: powderblue; box-shadow: 1px 1px 3px .1px; } a.rm_btn:hover{ box-shadow: 1px 1px 3px .1px inset; } a.rm-link{ color: blue; font-size: 11px; } div.rm-btn-link{ width: 100%; text-align: center; margin-top: 10px; margin-bottom: 15px; } div.link-div{ border: 1px dotted; padding: 13px; background-color: ivory; margin-top: 4px; width: 100%; } div.mail_body{ background-color: floralwhite; padding: 20px; } </style>';
         $html_pre = '<!DOCTYPE html>
                             <html>
                             <head>
                               <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                               <meta http-equiv="Content-Style-Type" content="text/css">
                                 <meta name="viewport" content="width=device-width, initial-scale=1.0">
                               <title></title>
                               <meta name="Generator" content="Cocoa HTML Writer">
                               <meta name="CocoaVersion" content="1404.34">
                                 <link rel="stylesheet" type="text/css" href="matchmytheme.css">
                             </head>
                             <body style="font-size:14px">';
         $html_post = '</body></html>';
         $msg_html = '<div class="mail-wrapper" style="border: 1px solid black; padding: 20px; box-shadow: .1px .1px 8px .1px grey; font-size: 14px; font-family: monospace;"> <div class="mail_body" style="padding: 20px;">' . RM_UI_Strings::get('MAIL_NEW_USER1') . '.<br/> ' . RM_UI_Strings::get('LABEL_USER_NAME') . ' : %USER_NAME% <br/> ' . RM_UI_Strings::get('LABEL_USEREMAIL') . ' : %USER_EMAIL% <br/> <br/>' . RM_UI_Strings::get('MAIL_NEW_USER2') . '<br/> <div class="rm-btn-link" style="width: 100%; text-align: center; margin-top: 10px; margin-bottom: 15px;"><a class="rm_btn" href="%ACTIVATION_LINk%" style="border: 1px solid; padding: 4px; background-color: powderblue; box-shadow: 1px 1px 3px .1px;">Activate</a></div> <div class="link-div" style="border: 1px dotted; padding: 13px; background-color: white; margin-top: 4px; width: 100%;"> ' . RM_UI_Strings::get('MAIL_NEW_USER3') . '.<br/> <a class="rm-link" href="%ACTIVATION_LINk%" style="color: blue; font-size: 11px;">%ACTIVATION_LINk%</a> </div> </div> </div>';
         $msg_html = str_replace('%SITE_NAME%', get_bloginfo('name', 'display'), $msg_html);
         $msg_html = str_replace('%USER_NAME%', $request->username, $msg_html);
         $msg_html = str_replace('%USER_EMAIL%', $user_email, $msg_html);
         $msg_html = str_replace('%ACTIVATION_LINk%', $request->link, $msg_html);
         //$email->message = "msg \r\n\r\n--" . $boundary . "\r\n" . $header_text . $msg_text . "\r\n\r\n--" . $boundary . "\r\n" . $header_html . $html_pre .$msg_css . $msg_html . $html_post . "\r\n\r\n--" . $boundary . "--\r\n";
         $email->message = $html_pre . $msg_html . $html_post;
         $email->subject = RM_UI_Strings::get('MAIL_ACTIVATE_USER_DEF_SUB');
         $email->to = get_option('admin_email');
         $email->attachments = array();
         $from_email = $gopt->get_value_of('senders_email_formatted');
         $header = "From: {$from_email}\r\n";
         $header .= "Content-Type: text/html; charset=utf-8\r\n";
         $email->header = $header;
     }
     return $email;
 }
 public function callback($payment_status, $rm_pproc_id)
 {
     switch ($payment_status) {
         case 'success':
             if ($rm_pproc_id) {
                 $log_id = $rm_pproc_id;
                 $log = RM_DBManager::get_row('PAYPAL_LOGS', $log_id);
                 if ($log) {
                     if ($log->log) {
                         $paypal_log = maybe_unserialize($log->log);
                         $payment_status = $paypal_log['payment_status'];
                         if ($payment_status == 'Completed') {
                             echo '<div id="rmform">';
                             echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_SUCCESS") . "</br>";
                             echo '</div></div>';
                             return 'success';
                         } else {
                             if ($payment_status == 'Denied' || $payment_status == 'Failed' || $payment_status == 'Refunded' || $payment_status == 'Reversed' || $payment_status == 'Voided') {
                                 echo '<div id="rmform">';
                                 echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_FAILED") . "</br>";
                                 echo '</div></div>';
                                 return 'failed';
                             } else {
                                 if ($payment_status == 'In-Progress' || $payment_status == 'Pending' || $payment_status == 'Processed') {
                                     echo '<div id="rmform">';
                                     echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_PENDING") . "</br>";
                                     echo '</div></div>';
                                     return 'pending';
                                 } else {
                                     if ($payment_status == 'Canceled_Reversal') {
                                         return 'canceled_reversal';
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             return false;
         case 'cancel':
             echo '<div id="rmform">';
             echo "<div class='rminfotextfront'>" . RM_UI_Strings::get("MSG_PAYMENT_CANCEL") . "</br>";
             echo '</div></div>';
             return;
         case 'ipn':
             $trasaction_id = $_POST["txn_id"];
             $payment_status = $_POST["payment_status"];
             $cstm = $_POST["custom"];
             $abcd = explode("|", $cstm);
             $user_id = (int) $abcd[1];
             $acbd = explode("|", $cstm);
             $log_entry_id = (int) $acbd[0];
             //$_POST["custom"];
             $log_array = maybe_serialize($_POST);
             $curr_date = RM_Utilities::get_current_time();
             // date_i18n(get_option('date_format'));
             RM_DBManager::update_row('PAYPAL_LOGS', $log_entry_id, array('status' => $payment_status, 'txn_id' => $trasaction_id, 'posted_date' => $curr_date, 'log' => $log_array), array('%s', '%s', '%s', '%s'));
             if ($this->paypal->validate_ipn()) {
                 //IPN is valid, check payment status and process logic
                 if ($payment_status == 'Completed') {
                     if ($user_id) {
                         $gopt = new RM_Options();
                         if ($gopt->get_value_of('user_auto_approval') == "yes") {
                             $user_service = new RM_User_Services();
                             $user_service->activate_user_by_id($user_id);
                         }
                     }
                     return 'success';
                 } else {
                     if ($payment_status == 'Denied' || $payment_status == 'Failed' || $payment_status == 'Refunded' || $payment_status == 'Reversed' || $payment_status == 'Voided') {
                         return 'failed';
                     } else {
                         if ($payment_status == 'In-Progress' || $payment_status == 'Pending' || $payment_status == 'Processed') {
                             return 'pending';
                         } else {
                             if ($payment_status == 'Canceled_Reversal') {
                                 return 'canceled_reversal';
                             }
                         }
                     }
                 }
                 return 'unknown';
             }
             return 'invalid_ipn';
     }
 }
 public function get_setting($name)
 {
     $global_settings = new RM_Options();
     $result = $global_settings->get_value_of($name);
     return $result;
 }
 public function submissions($model, RM_Front_Service $service, $request, $params)
 {
     $i = 0;
     $user_email = $service->get_user_email();
     //var_dump($user_email);die;
     if (null != $user_email && is_email($user_email)) {
         if (isset($request->req['submission_id'])) {
             $submission = new RM_Submissions();
             $submission->load_from_db($request->req['submission_id']);
             if ($submission->get_user_email() == $user_email) {
                 $view = $this->mv_handler->setView('front_submission_data', true);
                 $data = new stdClass();
                 $settings = new RM_Options();
                 $data->is_authorized = true;
                 $data->submission = $submission;
                 $data->payment = $service->get('PAYPAL_LOGS', array('submission_id' => $submission->get_submission_id()), array('%d'), 'row', 0, 99999);
                 if ($data->payment != null) {
                     $data->payment->total_amount = $settings->get_formatted_amount($data->payment->total_amount, $data->payment->currency);
                     if ($data->payment->log) {
                         $data->payment->log = maybe_unserialize($data->payment->log);
                     }
                 }
                 $data->notes = $service->get('NOTES', array('submission_id' => $submission->get_submission_id(), 'status' => 'publish'), array('%d', '%s'), 'results', 0, 99999, '*', null, true);
                 $i = 0;
                 if (is_array($data->notes)) {
                     foreach ($data->notes as $note) {
                         $data->notes[$i]->author = get_userdata($note->published_by)->display_name;
                         if ($note->last_edited_by) {
                             $data->notes[$i++]->editor = get_userdata($note->last_edited_by)->display_name;
                         } else {
                             $data->notes[$i++]->editor = null;
                         }
                     }
                 }
                 /*
                  * Check submission type
                  */
                 $form = new RM_Forms();
                 $form->load_from_db($submission->get_form_id());
                 $form_type = $form->get_form_type() == "1" ? "Registration" : "Contact";
                 $data->form_type = $form_type;
                 $data->form_type_status = $form->get_form_type();
                 $data->form_name = $form->get_form_name();
                 $data->form_is_unique_token = $form->get_form_is_unique_token();
                 /*
                  * User details if form is registration type
                  */
                 if ($form->get_form_type() == "1") {
                     $email = $submission->get_user_email();
                     if ($email != "") {
                         $user = get_user_by('email', $email);
                         $data->user = $user;
                     }
                 }
                 return $view->read($data);
             } else {
                 $view = $this->mv_handler->setView('not_authorized', true);
             }
             $msg = RM_UI_Strings::get('MSG_INVALID_SUBMISSION_ID_FOR_EMAIL');
             return $view->read($msg);
         } else {
             $data = new stdClass();
             $data->is_authorized = true;
             $data->submissions = array();
             $data->form_names = array();
             $data->submission_exists = false;
             //data for user page
             $user = get_user_by('email', $user_email);
             if ($user instanceof WP_User) {
                 $data->is_user = true;
                 $data->user = $user;
                 $data->custom_fields = $service->get_custom_fields($user_email);
             } else {
                 $data->is_user = false;
             }
             //For pagination of submissions
             $entries_per_page_sub = 20;
             $req_page_sub = isset($request->req['rm_reqpage_sub']) && $request->req['rm_reqpage_sub'] > 0 ? $request->req['rm_reqpage_sub'] : 1;
             $offset_sub = ($req_page_sub - 1) * $entries_per_page_sub;
             $total_entries_sub = $service->get_submission_count($user_email);
             $submissions = $service->get_submissions_by_email($user_email, $entries_per_page_sub, $offset_sub);
             $submission_ids = array();
             if ($submissions) {
                 $data->submission_exists = true;
                 foreach ($submissions as $submission) {
                     $form_name = $service->get('FORMS', array('form_id' => $submission->form_id), array('%d'), 'var', 0, 1, 'form_name');
                     $data->submissions[$i] = new stdClass();
                     $data->submissions[$i]->submission_ids = array();
                     $data->submissions[$i]->submission_id = $submission->submission_id;
                     $submission_ids[$i] = $submission->submission_id;
                     $data->submissions[$i]->submitted_on = $submission->submitted_on;
                     $data->submissions[$i]->form_name = $form_name;
                     $data->form_names[$submission->submission_id] = $form_name;
                     $i++;
                 }
                 $settings = new RM_Options();
                 $data->date_format = get_option('date_format');
                 $data->payments = $service->get_payments_by_submission_id($submission_ids, 999999, 0, null, true);
                 $i = 0;
                 if ($data->payments) {
                     foreach ($data->payments as $p) {
                         $data->payments[$i]->total_amount = $settings->get_formatted_amount($data->payments[$i]->total_amount, $data->payments[$i]->currency);
                         $i++;
                     }
                 }
                 //For pagination of payments
                 $entries_per_page_pay = 20;
                 $req_page_pay = isset($request->req['rm_reqpage_pay']) && $request->req['rm_reqpage_pay'] > 0 ? $request->req['rm_reqpage_pay'] : 1;
                 $data->offset_pay = $offset_pay = ($req_page_pay - 1) * $entries_per_page_pay;
                 $total_entries_pay = $i;
                 $data->total_pages_pay = (int) ($total_entries_pay / $entries_per_page_pay) + ($total_entries_pay % $entries_per_page_pay == 0 ? 0 : 1);
                 $data->curr_page_pay = $req_page_pay;
                 $data->starting_serial_number_pay = $offset_pay + 1;
                 $data->end_offset_this_page = $data->curr_page_pay < $data->total_pages_pay ? $data->offset_pay + $entries_per_page_pay : $total_entries_pay;
                 //Pagination Ends payments
                 $data->total_pages_sub = (int) ($total_entries_sub / $entries_per_page_sub) + ($total_entries_sub % $entries_per_page_sub == 0 ? 0 : 1);
                 $data->curr_page_sub = $req_page_sub;
                 $data->starting_serial_number_sub = $offset_sub + 1;
                 //Pagination Ends submissions
                 $data->active_tab_index = isset($request->req['rm_tab']) ? (int) $request->req['rm_tab'] : 0;
                 $view = $this->mv_handler->setView('front_submissions', true);
                 return $view->read($data);
             } elseif ($data->is_user === true) {
                 $data->payments = false;
                 $data->submissions = false;
                 $view = $this->mv_handler->setView('front_submissions', true);
                 return $view->read($data);
             } else {
                 $view = $this->mv_handler->setView('not_authorized', true);
                 $msg = RM_UI_Strings::get('MSG_NO_SUBMISSION_FRONT');
                 return $view->read($msg);
             }
         }
     } else {
         $view = $this->mv_handler->setView('not_authorized', true);
         $msg = RM_UI_Strings::get('MSG_NOT_AUTHORIZED');
         return $view->read($msg);
     }
 }