forms.php 10.4 KB
<?php
//namespace Tz\WordPress\Tools\HybridGallery;

error_reporting(E_ALL ^ E_DEPRECATED);

require_once __DIR__.'/../../../../../wp-config.php';
require_once __DIR__.'/../vendor/autoload.php';

/**
 * @param      $d
 * @param bool $die
 */
function trace($d, $die = false)
{
    print "<pre>";
    print_r($d);
    print "</pre>";
    if ($die) {
        die('-- end of trace --');
    }
}

/**
 * Class Forms
 */
class Forms
{
    protected $postdata = [];
    protected $form = null;
    protected $post_type = 'gallery';
    protected $gallery = '';
    protected $db;
    protected $settings;
    protected $requires_approval = "no";

    /**
     * @param $db
     * @param $user
     */
    public function __construct($db, $user)
    {
        $this->db   = $db;
        $this->user = $user;
    }

    /**
     * @param $form_type
     */
    public function set_form($form_type)
    {
        $this->form = $form_type;
    }

    /**
     * @param array $data
     */
    public function set_data($data = [])
    {
        if (count($data) > 0) {
            // remove unecessary indexes.
            unset($data['approval']);
            unset($data['form_type']);
            unset($data['gallery']);

            $this->postdata = $this->_sanitize_data($data);
        }
    }

    /**
     * @param $a
     */
    public function set_approval($a)
    {
        $this->requires_approval = $a;
    }

    /**
     * @param $post_type
     */
    public function set_post_type($post_type)
    {
        $this->post_type = $post_type;
    }

    /**
     * @param $setting
     */
    public function set_settings($setting)
    {
        $this->settings[] = $setting;
    }

    public function create_entry()
    {
        $gallery = $this->get_gallery($this->gallery);

        $post = new hgPost();

        $post->post_type = 'gallery';

        if ($this->form == "image-form") {

            $post->post_title   = $this->postdata['title'];
            $post->post_content = $this->postdata['description'];
            $post->post_status  = ($this->settings['image-approval'] == 'yes') ? 'pending' : 'publish';

            // verified the link.
            if (isset($this->postdata['imageLinked']) && $this->postdata['imageLinked'] != "") {
                if (!$this->url_exists($this->postdata['imageLinked'])) {
                    die(json_encode(
                        ['status' => 'error', 'details' => "I'm sorry. We tried to find that image, but couldn't."]
                    ));
                }
            }

            $status = "verified";

            $meta = [
                'gallery_type' => 'image',
                'source'       => (isset($this->postdata['imageLinked']) && $this->postdata['imageLinked'] != "")
                    ? "linked" : "uploaded",
                'link'         => (isset($this->postdata['imageLinked']) && $this->postdata['imageLinked'] != "")
                    ? $this->postdata['imageLinked'] : $this->postdata['uploaded_image_filename'],
                'views'        => 0,
                'thumbnail'    => '',
                'tags'         => '',
                'status'       => $status
            ];

            if ($meta['source'] == "uploaded") {
                $post->post_status = "pending";
            }

            //$wpdb = $this->db;


            $post_id = wp_insert_post($post);
            if ($post_id < 1) {
                die(json_encode(['status' => 'error', 'details' => "Could not create gallery post"]));
            }

            $this->db->query(
                "INSERT INTO `".$this->db->prefix."term_relationships` (`object_id`,`term_taxonomy_id`) VALUES ($post_id,"
                .$gallery['term_id'].")"
            );
            $this->db->query(
                "UPDATE `".$this->db->prefix."term_taxonomy` SET `count`=(count+1) WHERE term_id=".$gallery['term_id']
                ." LIMIT 1"
            );

            add_post_meta($post_id, '_gallery_item_details', $meta);

            die(json_encode(['status' => 'success', 'details' => "Thank you for sharing!"]));


        } else {
            $post->post_status = ($this->settings['video-approval'] == 'yes') ? 'pending' : 'publish';

            if (isset($this->postdata['videoLinked']) && $this->postdata['videoLinked'] != "") {

                $videoID = $this->extractYouTubeVideoID($this->postdata['videoLinked']);

                if ($videoID) {
                    // go out and grab the video data....
                    $TzYouTubeConn = new Zend_Gdata_YouTube();
                    $TzYouTubeConn->setMajorProtocolVersion(2);
                    try {
                        $e                  = $TzYouTubeConn->getVideoEntry($videoID);
                        $thumbnail          = "http://i.ytimg.com/vi/".$videoID."/0.jpg";
                        $post->post_title   = htmlspecialchars(mysql_real_escape_string($e->getVideoTitle()));
                        $post->post_content = htmlspecialchars(mysql_real_escape_string($e->getVideoDescription()));
                        $status             = "verified";
                        $msg                = "Thank you for sharing.";
                    } catch (Exception $error) {
                        die(json_encode(
                            [
                                'status'  => 'error',
                                'details' => "I'm sorry. The video could not be verified with YouTube."
                            ]
                        ));
                    }
                } else {
                    die(json_encode(['status' => 'error', 'details' => "That YouTube video url is invalid."]));
                }

            } else {
                $post->post_title   = $this->postdata['video_title'];
                $post->post_content = $this->postdata['video_description'];
                $status             = "unverified";
                $msg                = "Thank you for sharing. We are processing your video.";
                $thumbnail          = "";
            }


            $meta = [
                'gallery_type' => 'video',
                'source'       => (isset($this->postdata['videoLinked']) && $this->postdata['videoLinked'] != "")
                    ? "linked" : "uploaded",
                'link'         => (isset($this->postdata['videoLinked']) && $this->postdata['videoLinked'] != "")
                    ? $this->postdata['videoLinked'] : $this->postdata['uploaded_video_filename'],
                'views'        => 0,
                'thumbnail'    => $thumbnail,
                'tags'         => '',
                'status'       => $status
            ];

            $post_id = wp_insert_post($post);
            $this->db->query(
                "INSERT INTO `".$this->db->prefix."term_relationships` (`object_id`,`term_taxonomy_id`) VALUES ($post_id,"
                .$gallery['term_id'].")"
            );
            $this->db->query(
                "UPDATE `".$this->db->prefix."term_taxonomy` SET `count`=(count+1) WHERE term_id=".$gallery['term_id']
                ." LIMIT 1"
            );

            add_post_meta($post_id, '_gallery_item_details', $meta);
            die(json_encode(['status' => 'success', 'details' => $msg]));
        }
    }

    /**
     * @param string $slug
     *
     * @return mixed
     */
    public function get_gallery($slug = '')
    {
        $result = $this->db->get_row(
            "SELECT t.term_id,t.name, tt.description FROM `".$this->db->prefix."terms` AS t, `".$this->db->prefix
            ."term_taxonomy` as tt WHERE tt.term_id=t.term_id AND t.slug='$slug' LIMIT 1",
            'ARRAY_A'
        );

        return $result;
    }

    /**
     * @param $gallery
     */
    public function set_gallery($gallery)
    {
        $this->gallery = $gallery;
    }

    protected function getRealIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
        {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
        {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        return $ip;
    }

    /**
     * @param string $link
     *
     * @return bool
     */
    protected function extractYouTubeVideoID($link = "")
    {
        $parsed = @parse_url($link);
        if ($parsed) {
            if (isset($parsed['query'])) {
                $querystring = $parsed['query'];
                @parse_str($querystring, $output);
                if (isset($output['v']) && strlen($output['v']) > 1) {
                    return $output['v'];
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * @param string $url
     *
     * @return mixed
     */
    protected function url_exists($url = '')
    {
        // Version 4.x supported
        $handle = curl_init($url);
        if (false === $handle) {
            return false;
        }
        curl_setopt($handle, CURLOPT_HEADER, false);
        curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
        curl_setopt(
            $handle,
            CURLOPT_HTTPHEADER,
            ["User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15"]
        ); // request as if Firefox
        curl_setopt($handle, CURLOPT_NOBODY, true);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
        $connectable = curl_exec($handle);
        curl_close($handle);

        return $connectable;
    }

    /**
     * @param array $data
     *
     * @return array
     */
    protected function _sanitize_data($data = [])
    {
        $tempdata = [];
        foreach ($data as $option => $value) {
            $tempdata[$option] = mysql_escape_string($value);
        }

        return $tempdata;
    }
}

/**
 * Class hgPost
 */
class hgPost
{
    var $post_title = '';
    var $post_content = '';
    var $post_status = 'publish';
    var $post_type = 'gallery'; // can be 'page' or 'post'
    var $comment_status = 'open'; // open or closed for commenting
}

$current_user = null;
get_currentuserinfo();

$form = new Forms($wpdb, $current_user);

$form->set_form($_POST['form_type']);
$form->set_gallery($_POST['gallery']);
$form->set_data($_POST);
$form->set_post_type('gallery');
$form->set_approval($_POST['approval']);
$form->create_entry();