<?php

if(!function_exists('get_option')) {
  $config_path = realpath('../../../wp-config.php');
  @include_once($config_path);
}

if(!function_exists('commentpig_double_check')) {
  function commentpig_api_check_result_is_pass($check_result) {
    $result = false;

    if($check_result) {
      # A list of subscriptions for this plugin...
      $pass_array = array(
        'bronze',   # to be removed soon
        'free',
        'commentpig',
        '.*?pro',
      );

      # Compare...
      $tmp_list = strtolower(':' . str_replace(',', ':', str_replace(' ', '', $check_result)) . ':');
      foreach($pass_array as $pattern) {
        $result = preg_match("/:$pattern:/", $tmp_list);
        if($result) {
          break;
        }
      }

      unset($pass_array);
    }

    return $result;
  }

  function commentpig_api_check($force = false) {
    $result = false;

    #echo "commentpig_api_check:: here <BR />\n";
    if($_REQUEST['blogpig_api_key']) {
      $api_key = $_REQUEST['blogpig_api_key'];
    }
    else {
      $api_key = get_option('blogpig_api_key');
    }
    if($api_key) {
      $api_check_result = get_option('blogpig_api_check_result');
      $old_api_key = get_option('blogpig_old_api_key');
      $api_key_changed = $api_key != $old_api_key;
      $yesterday = time() - 24 * 60 * 60;
      if($api_key_changed ||                                              # api key changed since the last check or
         //!commentpig_api_check_result_is_pass($api_check_result) ||     # api key did not pass or
         $force ||                                                        # forced refresh
         get_option('blogpig_api_check_date') < $yesterday) {             # the last check was more than 24h ago...
        $api_check_url = "http://blogpig.com/api_check_new.php?key={$api_key}&id=1";
        if(function_exists('curl_init')) { # try for CURL first...
          #echo "commentpig_api_check:: curl <BR />\n";
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_USERAGENT, "CommentPiG/2.1");
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
          curl_setopt($ch, CURLOPT_URL, $api_check_url);

          # Proxy
          if(class_exists('WP_HTTP_Proxy')) {
            $proxy = new WP_HTTP_Proxy();
            if($proxy->is_enabled() && $proxy->send_through_proxy($api_check_url)) {
              $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>=');
              if ($isPHP5) {
                curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
                curl_setopt($ch, CURLOPT_PROXY, $proxy->host());
                curl_setopt($ch, CURLOPT_PROXYPORT, $proxy->port());
              }
              else {
                curl_setopt($ch, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port());
              }

              if($proxy->use_authentication()) {
                if ($isPHP5) {
                  curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
                }
                curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy->authentication());
              }
            }
          }

          $api_check_result = curl_exec($ch);
          curl_close($ch);
          unset($ch);
        }
        else {
          $reply = false;
          if(class_exists('WP_Http')) {
            $request = new WP_Http;
            $reply = $request->request($api_check_url, array('user-agent' => 'CommentPiG/2.1'));
          }
          if($reply && is_array($reply)) {
            $api_check_result = $reply['body'];
          }
          else {
            $api_check_result = file_get_contents($api_check_url);
          }
        }
        # Does it have the ID?
        $idx = strpos($api_check_result, '|');
        if($idx !== false) {
          $api_member_id = substr($api_check_result, 0, $idx);
          update_option('blogpig_api_member_id', $api_member_id);
          $api_check_result = substr($api_check_result, $idx + 1);
        }
        update_option('blogpig_api_check_result', $api_check_result);
        update_option('blogpig_api_check_date', time());
        update_option('blogpig_old_api_key', $api_key);
      }
      $result = commentpig_api_check_result_is_pass($api_check_result);
    }
    else {
      update_option('blogpig_api_check_result', '[ no key ]');
    }

    return trim($result);
  }
}

if(!function_exists('commentpig_api_show_field')) {
  function commentpig_api_show_field($plugin_dir = '') {
    $result = false;

    $force = false;
    if($_POST['btnSubmitKey']) {
      update_option('blogpig_api_key', $_POST['blogpig_api_key']);
      $force = true;
    }

    $api_key = get_option('blogpig_api_key');
    $api_check_result = commentpig_api_check($force);
    if($api_key) {
      $api_key_info = trim(get_option('blogpig_api_check_result'));
    }
    else {
      $api_key_info = 'no key';
    }

    global $wp_version;

    echo "
      <div class='postbox ' >
        <h3 class='hndle' style='cursor:default;'>
          <span style='vertical-align: top;'>BlogPiG API Key</span>";
    commentpig_show_header_link('blogpig-api-key', $plugin_dir);
    echo "
        </h3>
        <div class='inside'>

          <p>
            <TABLE width='100%' style='margin-top:12px;'>
              <TR>
                <TD width='20%'>
                  API Key:
                </TD>
                <TD width='80%'>
                  <INPUT type='text' name='blogpig_api_key' id = 'blogpig_api_key' value='{$api_key}' size='35' />
                  <INPUT type='submit' class='button' name='btnSubmitKey' id='btnSubmitKey' value='Save Key' />
                  <BR />
                </TD>
              </TR>
              <TR>
                <TD width='20%'>
                  Your Licenses:
                </TD>
                <TD width='80%'>
      ";
    if(!$api_check_result) {
      echo '<span style="color:red; ">';
    }
    else {
      echo '<span style="color:green; ">';
    }
    echo "
                  {$api_key_info}</span>
                </TD>
              </TR>
            </TABLE>
          </p>
          <BR />

        </div> <!--- class='inside' --->
      </div> <!--- class='postbox ' --->
    ";


    return $result;
  }
}


/*
 * Options Functions
 */

if(!function_exists('commentpig_double_check')) {
  function wpcommentpig_default_options() {
    $options = array(
                     'wpcommentpig_delay' => '10-15',
                     //'wpcommentpig_comments' => '',
                     //'wpcommentpig_users' => '',
                     'wpcommentpig_oldposts' => '',
                     'wpcommentpig_oldpostsdelay' => '2',
                     'wpcommentpig_excludecats' => '',
                     'wpcommentpig_excludecats_list' => '',
                     'wpcommentpig_reusecomments' => '',
                     //'wpcommentpig_lastrun' => 'never',
                     'wpcommentpig_target' => 'tags',
                     'wpcommentpig_target_field' => '',
                     'wpcommentpig_target_minsize' => '2',
                     'wpcommentpig_status' => 'approved',
                     'wpcommentpig_retrycount' => '0',

                     'wpcommentpig_source' => 'youtube2,twitter,friendfeed,wordpress',
                     'wpcommentpig_weight_youtube' => '1',
                     'wpcommentpig_weight_youtube2' => '1',
                     'wpcommentpig_weight_twitter' => '1',
                     'wpcommentpig_weight_backtype' => '1',
                     'wpcommentpig_weight_friendfeed' => '1',
                     'wpcommentpig_weight_yahooanswers' => '1',
                     'wpcommentpig_weight_wordpress' => '1',
                     'wpcommentpig_weight_localdb' => '1',
                     'wpcommentpig_username_source' => 'comments',
                     'wpcommentpig_yahoo_app_id' => 'YahooDemo',

                     'wpcommentpig_keywordexists' => '',
                     'wpcommentpig_commentsizemin' => '',
                     'wpcommentpig_commentsizemax' => '',
                     'wpcommentpig_longcomments' => 'skip',
                     'wpcommentpig_badwords' => '',
                     'wpcommentpig_badwords_list' => '',
                     'wpcommentpig_badaccounts' => '',
                     'wpcommentpig_badaccounts_list' => '',
                     'wpcommentpig_striplinks' => '',

                     'wpcommentpig_userlinkrate' => '',
                     'wpcommentpig_userlinktype' => 'random',
                     'wpcommentpig_userlinkrelnofollow' => 'do',
                     'wpcommentpig_ownlinkrate' => '',
                     'wpcommentpig_ownlinks' => '',
                     'wpcommentpig_ownlinkrelnofollow' => 'do',
                    );
    return $options;
  }

  function wpcommentpig_read_default_settings() {
    $result = false;

    $options = wpcommentpig_default_options();
    if(function_exists('wpcommentpig_pro_add_options')) {
      wpcommentpig_pro_add_options($options);
    }

    foreach($options as $name => $value) {
      if($name) {
        # Write it to the DB... Should I check something first?
        update_option($name, $value);
      }
    }

    return $result;
  }

  /*
   * Remove this plugin from the update list...
   */
  function commentpig_no_updates($r, $url) {
    if(0 !== strpos( $url, 'http://api.wordpress.org/plugins/update-check'))
      return $r; // Not a plugin update request. Bail immediately.
    $plugins = unserialize($r['body']['plugins']);
    $file = dirname(__FILE__) . '/commentpig.php';
    unset($plugins->plugins[plugin_basename($file)]);
    unset($plugins->active[array_search(plugin_basename($file), $plugins->active)]);
    $r['body']['plugins'] = serialize($plugins);
    return $r;
  }
  add_filter('http_request_args', 'commentpig_no_updates', 5, 2);


  /*
   * Tooltips...
   */

  function commentpig_show_tooltip($param, $plugin_dir = '', $image = 'tooltip') {
    $result = false;
    if($param) {
      @include(ABSPATH . "/wp-content/plugins/{$plugin_dir}tooltips.php");
      if($tooltips[$param]) {
        echo "
          <a href='#' onclick='return false;' class='bptooltips'><img src='" . get_option('siteurl') . "/wp-content/plugins/{$plugin_dir}images/{$image}.png' /><span class='bptooltips'>" . $tooltips[$param] . "</span></a>
        ";
      }
    }
    return $result;
  }

  function commentpig_show_header_link($section_name, $plugin_dir = '', $section_ref = '', $color = false, $link_text = 'more info') {
    $result = false;
    if($section_name) {
      @include(ABSPATH . "/wp-content/plugins/{$plugin_dir}tooltips.php");
      if($headers[$section_name]) {
        $href = "http://www.youtube.com/v/{$headers[$section_name]}?version=3&enablejsapi=1&fs=1&hd=1&cc_load_policy=1&feature=player_embedded&autoplay=1";
        if(preg_match('@^http://@i', $headers[$section_name])) {
          $href = $headers[$section_name];
        }
        else {
          // Get video title...
          $link_text = get_option('blogpig_header_link_title-' . $headers[$section_name], $link_text);
          if(!$link_text || $link_text == 'more info') {
            if(!class_exists('WP_Http')) {
              include_once(ABSPATH . WPINC. '/class-http.php');
            }
            $http = new WP_Http;
            if($http) {
              $reply = $http->request('http://gdata.youtube.com/feeds/api/videos/' . $headers[$section_name]);
              $gdata = ($reply && is_array($reply) ? $reply['body'] : '');
              if($gdata) {
                $found = array();
                if(preg_match('@<title.*?>(.*?)</title>@i', $gdata, $found)) {
                  $link_text = $found[1];
                  update_option('blogpig_header_link_title-' . $headers[$section_name], $link_text);
                }
                unset($found);
              }
            }
          }
        }

        echo "
          &nbsp;<a class='colorboxtips' " . ($color ? "style='color:{$color};'" : "") . " href='{$href}' title='{$link_text}'><IMG src='" . get_option('siteurl') . "/wp-content/plugins/{$plugin_dir}images/" . ($color ? "pro_" : "") . "camera.png' ></a>
        ";
      }
    }
    return $result;
  }

}

if(!function_exists('wpcommentpig_post_comment_now')) {
  function wpcommentpig_post_comment_now() {
    global $wpdb;
    $whatever = $_POST['whatever'];
    $whatever += 10;
    echo $whatever;
    die();
  }
  add_action('wp_ajax_commentpig_post_comment_now', 'wpcommentpig_post_comment_now');
}

if(!function_exists('post_comment_now_javascript')) {
  function post_comment_now_javascript() {
    ?>
    <script type="text/javascript">
    //<![CDATA[
    function post_comment_now(post_id) {
      var data = {
        action: 'post_comment_now',
        post_id: post_id,
        post_title: jQuery('#title').attr('value'),
        post_content: jQuery('#content').attr('value'),
        post_excerpt: jQuery('#excerpt').attr('value')
      };

      jQuery('#post-comment-now-status').html(' <img src="<?php echo plugins_url('/images/wait.gif', __FILE__); ?>" />');
      jQuery.post(ajaxurl, data, function(response) {
        jQuery('#post-comment-now-status').html('');
        if(!response) {
          response = 'Failed to trigger comment posting!';
        }
        jQuery('#wpcommentpig-conf').prepend('<div id=\'message\' class=\'updated fade\' style=\'padding:4px;\'><strong>' + response + '</strong></div>');
      });
    }
    //]]>
    </script>
    <?php
  }
  add_action('admin_head', 'post_comment_now_javascript');
}

if(!function_exists('post_comment_now_callback')) {
  function post_comment_now_callback() {
    $result = false;

    global $wpdb;

    if(function_exists('wpcommentpig_cron_run')) {
      ob_start();
      wpcommentpig_cron_run(false);
      $run_result = ob_get_contents();
      ob_end_clean();
      $run_message = "Triggered comment posting... (" . $run_result . ")";
      $result = $run_message;
    }

    echo $result;

    die();
  }
  add_action('wp_ajax_post_comment_now', 'post_comment_now_callback');
}

/*
 * Main CommentPiG Functions
 */

if(commentpig_api_check()) {

  if(!function_exists('commentpig_double_check')) {

  }

}

if(!function_exists('commentpig_double_check')) {
  function commentpig_double_check() {
    return true;
  }
}

if(!function_exists('commentpig_load_ioncube')) {
  function commentpig_load_ioncube() {
    if(!extension_loaded('ionCube Loader')){
      $__oc=strtolower(substr(php_uname(),0,3));
      $__ln='/ioncube/ioncube_loader_'.$__oc.'_'.substr(phpversion(),0,3).(($__oc=='win')?'.dll':'.so');
      $__oid=$__id=realpath(ini_get('extension_dir'));
      $__here=dirname(__FILE__);
      if((@$__id[1])==':'){
        $__id=str_replace('\\','/',substr($__id,2));
        $__here=str_replace('\\','/',substr($__here,2));
      }
      $__rd=str_repeat('/..',substr_count($__id,'/')).$__here.'/';
      $__i=strlen($__rd);
      while($__i--){
        if($__rd[$__i]=='/'){
          $__lp=substr($__rd,0,$__i).$__ln;
          if(file_exists($__oid.$__lp)){
            $__ln=$__lp;
            break;
          }
        }
      }
      if(function_exists('dl')) {
        @dl($__ln);
      }
    }
  }
}

?>
