Install Cordova/Phonegap on Window

Installing Cordova on Windows

This document describes how to install Apache Cordova and the Android SDK on a Windows machine. This is a quite complex process, which may take some time depending on your previous experience with installing SKDs and build tools. Care has been taken when writing this document to include all the essential steps needed to get you up and running with a successful install. Kindly let us know if there is something you are missing.
To develop Android apps, you need to install the Android SDK, and also Java if not already installed on your machine. Furthermore the build tool Ant is required.
For the Android SDK, you have the choice between installing the ADT bundle that incudes Eclipse (ADT = Android Developer Tools), or the Android SDK Tools, that does not include Eclipse. In the steps below we will use the Android SDK Tools download.

Install Cordova

Follow these steps to install Cordova:
  1. Install Node.js. Cordova runs on the Node.js platform, which needs to be installed as the first step. Download installer from: http://nodejs.org
  2. Go ahead an run the downloaded installation file. It is recommended to use the default settings. Node.js needs to be added to the PATH environment variable, which is done by default.
  3. To test the installation, open a command window (make sure you open a new command window to get the updated path settings made by the Node.js installation), and type:
    node --version
    If the version number is displayed, Node.js is installed and working!
  4. Install Git. Git is a version control system, which is used by Cordova behind-the-scenes. Download and install from: http://git-scm.com. Default settings are recommended.
  5. Install Cordova. Cordova is installed using the Node Package Manager (npm). Type the following in the command window to install:
    npm install -g cordova
  6. Test the Cordova install by typing:
    cordova --version
    If you see the version number, you have successfully installed Apache Cordova!

Install Java

The Android SDK needs the Java Development Kit (JDK) to be installed (minimum version 1.6). Note that the Java Runtime Environment (JRE) is not sufficient, you will need the JDK. To check if you have the JDK installed already, type this on the command line:
javac -version
If you do not have the JDK installed, proceed as follows:
  1. Download the Java SE JDK (SE = Standard Edition) from Oracle:www.oracle.com/technetwork/java/javase/downloads/. Click the Java SE Download to see the list fo download. Get the "Windows x86" download if you have 32-bit Windows, and "Windows x64" if you have 64-bit Windows. If you do not know which version you have, find out using the Control Panel by selecting "System and Security" and then "System", where you will find the "System type" saying if your Windows version is 32-bit or 64-bit.
  2. Go along and run the downloaded installer file. Using the default selections should be fine, but take a note of the directory in which you install the JDK. You will need to add this to the PATH in a later step below.
  3. Next, update your path to include the JDK. Open the Control Panel, click System and Security, click System, click Change settings, which will open the System Properties window. Select the Advanced tab, then click theEnvironment Variables button.
  4. In the list User variables select PATH and click the Edit button. (If there is no PATH entry in the list, click the New button to create one.)
  5. At the end of the field Variable value, add a semicolon followed by the path to the bin directory of the JDK install. Here is an example (note that this must be the actual path used for the install on your machine):
    ;C:\Program Files\Java\jdk1.8.0_11\bin
    An easy way to do this is to prepare the path to add in a text editor, then paste it at the end of the input field. When done click the OK button.
  6. Next add the JAVA_HOME variable if it is not present (and if it is in the list, you may need to update its value using the Edit button). Click the New button. In the field Variable name type:
    JAVA_HOME
    In the field Variable value enter the path to the directory where the JDK is installed, without the semicolon and the /bin subdirectory, for example:
    C:\Program Files\Java\jdk1.8.0_11
    Click the OK button.
  7. Click the OK button again to close the Environment Variables window.
  8. Now you are ready to test the install. Close any open command windows, and open a new command window and type:
    javac -version
    If you see a version number you are done with the JDK install!

Install Ant

Apache Ant is a build system for Java, which is used by Cordova and the Android SDK. To install Ant, follow these steps:
  1. Download Ant from here: ant.apache.org/bindownload.cgi. Get the zip download available at the page. Click the zip-file link for the most recent release, e.g. apache-ant-1.9.4-bin.zip, and save the file to your machine.
  2. Unpack the zip file to the directory on your machine where you want Ant to be installed. You can pick any directory for the install. In this guide we use this as an example:
    C:\Users\miki\ant
    Note that the files in the ant package should go directly into this directory. Make a note of the directory as you will need to add it to the PATH.
  3. To add Ant to the PATH, open the Control Panel, click System and Security, click System, click Change settings, click the Advanced tab, then click the Environment Variables button.
  4. In the list User variables select PATH and click the Edit button.
  5. At the end of the field Variable value, add a semicolon followed by the path to the bin directory of the Ant install. Here is an example:
    ;C:\Users\miki\ant\bin
    Click the OK button.
  6. Next add the ANT_HOME variable. Click the New button. In the field Variable name type:
    ANT_HOME
    In the field Variable value enter the path to the directory where Ant is installed, without the semicolon and the /bin subdirectory, for example:
    C:\Users\miki\ant
    Click the OK button.
  7. Click the OK button again to close the Environment Variables window.
  8. Now test the install. Close any open command windows, and open a new command window and type:
    ant -version
    If you see a version number you have installed Ant successfully!

Install the Android SDK Tools

The SDK Tools for Android are used by Cordova to build Android apps. Follow these steps to install the SDK Tools:
  1. Go to the page developer.android.com/sdk scroll down the page and click "VIEW ALL DOWNLOADS AND SIZES". Under "SDK Tools Only", click the windows installer exe file and download it (this file is named e.g.installer_r23.0.2-windows.exe).
  2. When downloaded, run the installer. You should do fine to use the default settings used by the installer, but make a note of the directory in which the SDK is installed, as you will have to add this to the PATH in the next step.
  3. To add the SDK Tools to the PATH, open the Control Panel, click System and Security, click System, clickChange settings, click the Advanced tab, then click the Environment Variables button.
  4. In the list User variables select PATH and click the Edit button.
  5. At the end of the field Variable value, add a semicolon followed by the path to the tools and platform-toolsdirectores of the Android SDK install. Here is an example of what to add (note that there are two paths in one line, separated by a semicolon):
    ;C:\Users\miki\AppData\Local\Android\android-sdk\tools;C:\Users\miki\AppData\Local\Android\android-sdk\platform-tools
    You can prepare the path in a text editor, copy it and paste at the end of the input field. Click the OK button when done.
  6. Click the OK button again to close the Environment Variables window.
  7. Now test the install. Close any open command windows, open a new command window and type:
    adb version
    This should display the version of the Android Debug Bridge.
  8. As the final step, you need to get the specific Android SDK version used by Cordova. This is done by running the Android SDK Manager by typing the command:
    android
    This launches a window where you can select to install specific Android SDKs.
  9. First time you launch the Android SDK Manager there will be preset selections. It is recommended to leave these untouched. Also select the entry "Android 4.4.2 (API 19)". This is the version used by the current Cordova 3.5 version. Note that the Android SDK required by Cordova will change in the future, as new versions of Cordova and Android are released. When this happens, open the Android SDK Manager again, and install the required API version(s).

If You Get Stuck

If you get stuck, consult the documentation at the respective web sites for Cordova, Java, Ant, and Android. The Cordova documentation specific for Android is found here:cordova.apache.org/docs/en/3.6.0/guide_platforms_android_index.md.html. You are also welcome to ask for help at theEvothings Forum.
One thing to do is to inspect all the environment variables. You can do this from a command window (note that you have to open a new command window after updating environment variables for updated values to be available). This displays the system PATH:
echo %PATH%
Here is how to inspect the values of JAVA_HOME and ANT_HOME:
echo %JAVA_HOME%
echo %ANT_HOME%

Get random password / Keys

<?php

// Get random password
function get_random_password($chars_min=8, $chars_max=12, $use_upper_case=true, $include_numbers=true, $include_special_chars=true)
    {
        $length = rand($chars_min, $chars_max);
        $selection = 'aeuoyibcdfghjklmnpqrstvwxz';
        if($include_numbers) {
            $selection .= "1234567890";
        }
        if($include_special_chars) {
            $selection .= "!@\"#$%&[]{}?|";
        }

        $password = "";

        for($i=0; $i<$length; $i++) {
            $current_letter = $use_upper_case ? (rand(0,1) ? strtoupper($selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))];          
            $password .=  $current_letter;
        }              
      return $password;
    }

?>
AND CALL THIS :-
<?php
$random_key = get_random_password($chars_min=6, $chars_max=8, $use_upper_case=true, $include_numbers=true, $include_special_chars=false);

echo $random_key;
?>

Cake PhP

PHP mail using SMTP


In Codigniter is use this PHP Code to send mail using SMTP

Simple Mail Transfer Protocols :)


        $mail = array();
        $mail["protocol"] = "smtp";
        $mail["smtp_host"] = "ssl://p3plcpnl019.prod.phx3.secureserver.net";
        $mail["smtp_port"] = 465;
        $mail["smtp_user"] = "Your Email Address";
        $mail["smtp_pass"] = "Your Address";
      
         $this->load->library("email", $mail);
         $this->email->set_newline("\r\n");
        
         //set email information and content
         $this->email->from("support@gerosport.com", "GeroSport");
         $this->email->to($to);
        
         $this->email->subject($subject);
   
         $this->email->message($msg);
        
         if($this->email->send())
         {
            $response = 1;
         } else {
            $response = 0;
         }



Also i get help from :-
http://asif18.com/7/php/send-mails-using-smtp-in-php-by-gmail-server-or-own-domain-server/

Building a RESTful Web API with PHP and Apify

Apify is a small and powerful open source library that delivers new levels of developer productivity by simplifying the creation of RESTful architectures. You can see it in action here. Web services are a great way to extend your web application, however, adding a web API to an existing web application can be a tedious and time-consuming task. Apify takes certain common patterns found in most web services and abstracts them so that you can quickly write web APIs without having to write too much code.
Apify exposes similar APIs as the Zend Framework, so if you are familiar with the Zend Framework, then you already know how to use Apify. Take a look at the UsersController class.

Building a RESTful Web API

In Apify, Controllers handle incoming HTTP requests, interact with the model to get data, and direct domain data to the response object for display. The full request object is injected via the action method and is primarily used to query for request parameters, whether they come from a GET or POST request, or from the URL.
Creating a RESTful Web API with Apify is easy. Each action results in a response, which holds the headers and document to be sent to the user’s browser. You are responsible for generating the response object inside the action method.
class UsersController extends Controller
{
public function indexAction($request)
{
// 200 OK
return new Response();
}
}
The response object describes the status code and any headers that are sent. The default response is always 200 OK, however, it is possible to overwrite the default status code and add additional headers:
class UsersController extends Controller
{
public function indexAction($request)
{
$response = new Response();

// 401 Unauthorized
$response->setCode(Response::UNAUTHORIZED);

// Cache-Control header
$response->setCacheHeader(3600);

// ETag header
$response->setEtagHeader(md5($request->getUrlPath()));

// X-RateLimit header
$limit = 300;
$remaining = 280;
$response->setRateLimitHeader($limit, $remaining);

// Raw header
$response->addHeader('Edge-control: no-store');

return $response;
}
}
Content Negotiation
Apify supports sending responses in HTML, XML, RSS and JSON. In addition, it supports JSONP, which is JSON wrapped in a custom JavaScript function call. There are 3 ways to specify the format you want:
  • Appending a format extension to the end of the URL path (.html, .json, .rss or .xml)
  • Specifying the response format in the query string. This means a format=xml or format=json parameter for XML or JSON, respectively, which will override the Accept header if there is one.
  • Sending a standard Accept header in your request (text/html, application/xml or application/json).
The acceptContentTypes method indicates that the request only accepts certain content types:
class UsersController extends Controller
{
public function indexAction($request)
{
// only accept JSON and XML
$request->acceptContentTypes(array('json', 'xml'));

return new Response();
}
}
Apify will render the error message according to the format of the request.
class UsersController extends Controller
{
public function indexAction($request)
{
$request->acceptContentTypes(array('json', 'xml'));

$response = new Response();
if (! $request->hasParam('api_key')) {
throw new Exception('Missing parameter: api_key', Response::FORBIDDEN);
}
$response->api_key = $request->getParam('api_key');

return $response;
}
}
Request
GET /users.json
Response
Status: 403 Forbidden
Content-Type: application/json
{
"code": 403,
"error": {
"message": "Missing parameter: api_key",
"type": "Exception"
}
}
Resourceful Routes
Apify supports REST style URL mappings where you can map different HTTP methods, such as GET, POST, PUT and DELETE, to different actions in a controller. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods:
HTTP MethodURL PathActionUsed for
GET/usersindexdisplay a list of all users
GET/users/:idshowdisplay a specific user
POST/userscreatecreate a new user
PUT/users/:idupdateupdate a specific user
DELETE/users/:iddestroydelete a specific user

If you wish to enable RESTful mappings, add the following line to the index.php file:
try {
$request = new Request();
$request->enableUrlRewriting();
$request->enableRestfulMapping();
$request->dispatch();
} catch (Exception $e) {
$request->catchException($e);
}
The RESTful UsersController for the above mapping will contain 5 actions as follows:
class UsersController extends Controller
{
public function indexAction($request) {}
public function showAction($request) {}
public function createAction($request) {}
public function updateAction($request) {}
public function destroyAction($request) {}
}
By convention, each action should map to a particular CRUD operation in the database.

Building a Web Application

Building a web application can be as simple as adding a few methods to your controller. The only difference is that each method returns a view object.
class PostsController extends Controller
{
/**
* route: /posts/:id
*
* @param $request Request
* @return View|null
*/
public function showAction($request)
{
$id = $request->getParam('id');
$post = $this->getModel('Post')->find($id);
if (! isset($post->id)) {
return $request->redirect('/page-not-found');
}

$view = $this->initView();
$view->post = $post;
$view->user = $request->getSession()->user

return $view;
}

/**
* route: /posts/create
*
* @param $request Request
* @return View|null
*/
public function createAction($request)
{
$view = $this->initView();
if ('POST' !== $request->getMethod()) {
return $view;
}

try {
$post = new Post(array(
'title' => $request->getPost('title'),
'text' => $request->getPost('text')
));
} catch (ValidationException $e) {
$view->error = $e->getMessage();
return $view;
}

$id = $this->getModel('Post')->save($post);
return $request->redirect('/posts/' . $id);
}
}
The validation is performed inside the Post entity class. An exception is thrown if any given value causes the validation to fail. This allows you to easily implement error handling for the code in your controller.
Entity Class
You can add validation to your entity class to ensure that the values sent by the user are correct before saving them to the database:
class Post extends Entity
{
protected $id;
protected $title;
protected $text;

// sanitize and validate title (optional)
public function setTitle($value)
{
$value = htmlspecialchars(trim($value), ENT_QUOTES);
if (empty($value) || strlen($value) < 3) {
throw new ValidationException('Invalid title');
}
$this->title = $title;
}

// sanitize text (optional)
public function setText($value)
{
$this->text = htmlspecialchars(strip_tags($value), ENT_QUOTES);
}
}
Routes
Apify provides a slimmed down version of the Zend Framework router:
$routes[] = new Route('/posts/:id',
array(
'controller' => 'posts',
'action' => 'show'
),
array(
'id' => '\d+'
)
);
$routes[] = new Route('/posts/create',
array(
'controller' => 'posts',
'action' => 'create'
)
);
HTTP Request
GET /posts/1
Incoming requests are dispatched to the controller “Posts” and action “show”.

Convert field datatype or get time according to time zone..

Hi,  friends..

in this post i found a code which is listed below.

i facing some problem in PHP/SQL to store special charecter or other languages in database. When we save data in varchar datatype field then it show ?????. so after googling i found this code. i change field data type VarChar to varbinary so that data is store into binary form. and when i retrive data then i change datatype of data to varbinary to varchar by using this code...

i using CONVERT function

CONVERT(`name`, CHAR(255)) as `name` -> name is field name.. 

SELECT `groupId`, CONVERT(`name`, CHAR(255)) as `name`, `image`, `type`, `status`, CONVERT_TZ(`addedDate`,'-6:00','".$zone."') as `addedDate` FROM `msg_user_group` WHERE `groupId` = 1;

change time according to GMT or timezones

change time according to GMT or timezones

i facing problem to post posted time in different countries.. correctly. i have need to change date time according to time zones.  I found this code ..

SQL CONVERT_TZ function help me..

CONVERT_TZ function change time according to time zone.

in this example i change date having format (YYYY-MM-DD HH:ii:ss)

which is according to usa timezone (6:00) to indian time zone (05:30)

SELECT  `chatId`,`userId`,`sellerId`,`sellerUserId`,`message`,`status`,`cstatus`,CONVERT_TZ(`date`,'-6:00','+05:30') as date FROM `fast_my_chat`


this code helping you also..

I phone Push notification

I phone Push notification
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // device token id..         
 $deviceToken = '1dec4a0c1b5ae0654c6596162b658fbada168d723be43bd9ac2e05e393f21572';
//password generate when key file is generated... generate by iphone developer
            $passphrase = '12345';
// message you want to send in notification.
            $message = 'My first push notification!';
//  "WP_CONTENT_DIR.'/uploads/pushnotification/AAPush.pem" is the path of certificate main .pem file..
            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', WP_CONTENT_DIR.'/uploads/pushnotification/AAPush.pem');
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

            $fp = stream_socket_client(
                'ssl://gateway.sandbox.push.apple.com:2195', $err,
            $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

            $body['aps'] = array(
                'alert' => $message,
                'sound' => 'default',
                'content-available' => '1'
            );
// use content-aailable for ios backend notificatin handle..
            $payload = json_encode($body);

            $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// in result you got the response.. if no response then you push notification is not working
            $result = fwrite($fp, $msg, strlen($msg));
           
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Web Services in Wordpress.. for Android AND Iphone

Fist install this plugin to start making web services..

http://messenger.amebasoftware.com/wp-admin/plugin-install.php?tab=plugin-information&plugin=wp-simple-web-services&TB_iframe=true&width=772&height=597

Find link "Web Services" on Dashboard..

check post and save.. now you start making web services according to your requirements..

Your code is here /plugins/wp-simple-web-services/classes/class-wpsws-webservice-get-posts.php

you find this code and use, if it helps you :-)

<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class WPSWS_Webservice_get_posts {

    private static $instance = null;

    /**
     * Get singleton instance of class
     *
     * @return null|WPSWS_Webservice_get_posts
     */
    public static function get() {

        if ( self::$instance == null ) {
            self::$instance = new self();
        }

        return self::$instance;

    }

    /**
     * Constructor
     */
    private function __construct() {
        $this->hooks();
    }

    /**
     * Setup hooks
     */
    private function hooks() {
        add_action( 'wpsws_webservice_get_posts', array( $this, 'get_posts' ) );
        add_action( 'wpsws_general_settings', array( $this, 'settings' ), 1 );
    }

    /**
     * get_posts settings screen
     */
    public function settings() {
        ?>
        <script type="text/javascript">
            (function($) {
                $('body').ready(function() {
                    var allPanels = $('.accordion > dd').hide();

                    $('.accordion > dt > a').click(function() {
                        allPanels.slideUp();
                        $(this).parent().next().slideDown();
                        return false;
                    });
                });
            })(jQuery);
        </script>
        <style type="text/css">
            .accordion dt, .accordion dd {
                padding: 10px;
                border: 1px solid black;
                border-bottom: 0;
                margin: 0;
            }

            .accordion dt:last-of-type, .accordion dd:last-of-type {
                border-bottom: 1px solid black;
            }

            .accordion dt a, .accordion dd a {
                display: block;
                color: black;
                font-weight: bold;
            }

            .accordion dd {
                border-top: 0;
                font-size: 12px;
            }

            .accordion dd:last-of-type {
                border-top: 1px solid white;
                position: relative;
                top: -1px;
            }
        </style>
        <h2>Post Types</h2>
        <b>Registration For Passengers:</b><br/>
        <label><?php echo get_site_url().'/webservice/get_posts/?post_type=post&utype=register&uemail=admin@admin.com&fname=Admin&lname=admin2&uphone=987765&upass=admin12'; ?></label>
        <br/><br/>
       
        <b>Registration For Drivers:</b><br/>
        <label><?php echo get_site_url().'/webservice/get_posts/?post_type=post&utype=driver&demail=nishant@gmail.com&dfname=Nishant&dlname=Sharma&dphone=987765&dpass=nishant&dtype=rdiver&dmodel=1234&dyear=2014&dnumber=1234'; ?></label>
        <br/><br/>
       
        <b>Login:</b><br/>
        <label><?php echo get_site_url().'/webservice/get_posts/?post_type=post&utype=login&uname=admin@admin.com&upass=admin12'; ?></label>
        <br/><br/>
       
        <b>GetDriverDetails:</b><br/>
        <label><?php echo get_site_url().'/webservice/get_posts/?post_type=post&utype=detail&driverID=1'; ?></label>
        <br/><br/>
       
        <dl class="accordion">

            <?php

            // Global options
            $options = WP_Simple_Web_Service::get()->get_options();

            // Get 'get_posts' options
            $gp_options = array();
            if ( isset( $options['get_posts'] ) ) {
                $gp_options = $options['get_posts'];
            }

            // Get post types
            $post_types = get_post_types( array( 'public' => true ), 'objects' );

            if ( count( $post_types ) > 0 ) {

                foreach ( $post_types as $key => $post_type ) {

                    // Post type options
                    $pt_options = WPSWS_Webservice_get_posts::get()->get_default_settings();
                    if ( isset( $gp_options[$key] ) ) {
                        $pt_options = wp_parse_args( $gp_options[$key], $pt_options );
                    }

                    // Default post type fields
                    $post_type_supports = array(
                        'ID'            => 'ID',
                        'post_date'     => __( 'Post Date', 'wpw' ),
                        'post_status'   => __( 'Post Status', 'wpw' ),
                        'post_modified' => __( 'Post Modified', 'wpw' ),
                        'post_parent'   => __( 'Post Parent', 'wpw' ),
                        'menu_order'    => __( 'Menu Order', 'wpw' ),
                        'post_type'     => __( 'Post Type', 'wpw' )
                    );

                    // Default post type fields that might be supported
                    $post_type_maybe_supports = array(
                        'title'     => array( array( 'key' => 'post_title', 'value' => __( 'Post Title', 'wpw' ) ) ),
                        'editor'    => array( array( 'key' => 'post_content', 'value' => __( 'Post Content', 'wpw' ) ) ),
                        'author'    => array( array( 'key' => 'post_author', 'value' => __( 'Post Author', 'wpw' ) ) ),
                        'thumbnail' => array( array( 'key' => 'thumbnail', 'value' => __( 'Thumbnail', 'wpw' ) ) ),
                        'excerpt'   => array( array( 'key' => 'post_excerpt', 'value' => __( 'Post Excerpt', 'wpw' ) ) ),
                        'comments'  => array( array( 'key' => 'comment_status', 'value' => __( 'Comment Status', 'wpw' ) ), array( 'key' => 'comment_count', 'value' => __( 'Comment Count', 'wpw' ) ) ),
                    );

                    // Check if the current post type supports the optional fields
                    foreach ( $post_type_maybe_supports as $supports_key => $post_type_maybe_support_fields ) {
                        if ( post_type_supports( $key, $supports_key ) ) {
                            foreach ( $post_type_maybe_support_fields as $post_type_maybe_support_field ) {
                                $post_type_supports[$post_type_maybe_support_field['key']] = $post_type_maybe_support_field['value'];
                            }
                        }
                    }

                    // Custom fields
                    $custom_fields = array();
                    $dummy_post    = get_posts( array( 'post_type' => $key, 'posts_per_page' => 1 ) );
                    if ( is_array( $dummy_post ) && count( $dummy_post ) > 0 ) {
                        $dummy_post = array_shift( $dummy_post );

                        $post_custom_fields = get_post_custom( $dummy_post->ID );

                        if ( is_array( $post_custom_fields ) && count( $post_custom_fields ) > 0 ) {
                            foreach ( $post_custom_fields as $custom_field => $custom_value ) {
                                if ( substr( $custom_field, 0, 1 ) != '_' ) {
                                    $custom_fields[$custom_field] = $custom_field;
                                }
                            }
                        }

                    }

                    echo "<dt><a href=''>{$post_type->labels->name}</a></dt>\n";
                    echo "<dd id='wpw_pt_{$key}'>";

                    echo "<input type='hidden' class='ajax_nonce' value='" . wp_create_nonce( 'wpw-ajax-security' ) . "' />\n";
                    echo "<input type='hidden' class='post_type' value='" . $key . "' />\n";

                    echo "<label for='enable_{$key}'><input type='checkbox' name='enabled' class='wpw_enabled' id='enable_{$key}' " . ( ( 'true' == $pt_options['enabled'] ) ? "checked='checked' " : "" ) . "/> " . __( 'Enable post type', 'wpw' ) . "</label><br/><br/>\n";

                    echo "<b>Web Service URL:</b><br/>";
                    echo '<input type="text" name="webservice_url" value="' . get_site_url() . '/webservice/get_posts/?post_type=' . $key . '" disabled="disabled" style="width:100%;" />';
                    echo "<br/><br/>";

                    // Default fields
                    echo "<b>" . __( 'Enable fields', 'wpw' ) . ":</b><br/>\n";
                    foreach ( $post_type_supports as $post_type_field => $post_type_label ) {
                        echo "<label for='post_type_{$key}_field_{$post_type_field}'><input type='checkbox' name='field[]' value='{$post_type_field}' class='wpw_fields' id='post_type_{$key}_field_{$post_type_field}' " . ( ( false !== array_search( $post_type_field, $pt_options['fields'] ) ) ? "checked='checked' " : "" ) . "/> {$post_type_label}</label><br/>\n";
                    }

                    echo "<br />";

                    // Custom fields
                    echo "<b>" . __( 'Custom fields', 'wpw' ) . ":</b><br/>\n";
                    foreach ( $custom_fields as $post_type_field => $post_type_label ) {
                        echo "<label for='post_type_{$key}_field_{$post_type_field}'><input type='checkbox' name='custom[]' value='{$post_type_field}' class='wpw_custom' id='post_type_{$key}_field_{$post_type_field}' " . ( ( false !== array_search( $post_type_field, $pt_options['custom'] ) ) ? "checked='checked' " : "" ) . "/> {$post_type_label}</label><br/>\n";
                    }

                    echo submit_button( __( 'Save', 'wpw' ) );

                    echo "</dd>\n";

                }

            }

            ?>

        </dl>
    <?php
    }

    /**
     * Function to get the default settings
     *
     * @return array
     */
    public function get_default_settings() {
        return array( 'enabled' => 'false', 'fields' => array(), 'custom' => array() );
    }

    /**
     * This is the default included 'get_posts' webservice
     * This webservice will fetch all posts of set post type
     *
     * @todo
     * - All sorts of security checks
     * - Allow custom query variables in webservice (e.g. custom sorting, posts_per_page, etc.)
     */
    public function get_posts() {

        // Check if post type is set
        if ( ! isset( $_GET['post_type'] ) ) {
            WP_Simple_Web_Service::get()->throw_error( 'No post type set.' );
        }

        // Set post type
        $post_type = esc_sql( $_GET['post_type'] );
       
        // Set post type
        $usertype = esc_sql( $_GET['utype'] );
   
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Chekc User is Registered or Not +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////       
       
        if($usertype == 'isexits'){
            global $wpdb;
            $return_data = array();
           
            $email = $_GET['email'];
           
            $IsSocialUser = $_GET['IsSocialUser'];
           
            $querystr = "SELECT * FROM `taxi_users` WHERE `user_email` = '".$email."' AND `IsSocialUser` = '".$IsSocialUser."' ";
                   
           
            $uinfo = $wpdb->get_results($querystr, OBJECT);
            foreach($uinfo as $info){
                $userId = $info->ID;
            }
           
            if( $userId ) {
                $return_data['Message'] = 'Success';
                $return_data['userId'] = (string)$userId;
            }else{
                $return_data['Message'] = 'Failure';
            }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ User SMS Registration +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'sms'){
            include("api/SendSMS.php");
            include("api/IncomingFormat.php");
            include("api/ClientPolled.php"); $upload_dir = wp_upload_dir();
            //$upload_dir = wp_upload_dir(); echo "<pre>"; print_r($upload_dir); echo $upload_dir['baseurl'];
            global $wpdb;
           
            global $sms_username;
           
            global $sms_password;
           
            global $errstr;
           
            $return_data = array();
           
            $data = array();
           
            $sms_username = "XXXXX";

            $sms_password = "XXXXX";
           
        //    if( !email_exists( $_POST['email'] ) ) {
            if (isset($_POST['phone'])) {
                    $posted_firstname = $_POST['fname'];
                    $posted_lastname = $_POST['lname'];
                    $posted_email = $_POST['email'];
                    $posted_phone = $_POST['phone'];
                    $deviceId = $_POST['did'];
                   
                    if( $_POST['cnumber'] ){
                        $posted_carnumber = $_POST['cnumber'];
                    }else{
                        $posted_carnumber = '';
                    }
                   
                    $posted_password = $_POST['pass'];
                    $posted_usertype = 'P';
                    $posted_socialuser = $_POST['IsSocialUser'];
                   
                    $upload_dir = wp_upload_dir();
                    //$upload_dir['baseurl'];
                    if (isset($_POST['pimg']) && !empty($_POST['pimg'])) {
                            $iimg = $_POST['pimg'];
                           
                            $data1 = base64_decode($iimg);
                            $imgId = rand(1000000,9999999);
                            $dir = $upload_dir['basedir'].'/customers/'.$posted_firstname.'-'.$imgId.'-'.$posted_phone.'.png';
                            file_put_contents( $dir, $data1);
                           
                            $image = $upload_dir['baseurl'].'/customers/'.$posted_firstname.'-'.$imgId.'-'.$posted_phone.'.png';
                        } else {
                            $image = $upload_dir['baseurl'].'/customers/no_image.jpg';
                        }
                   
                   

            //$user_name = htmlspecialchars($posted_username,ENT_QUOTES);
           
            $user_name = htmlspecialchars($posted_email,ENT_QUOTES);
           
            $pass_word = wp_hash_password($posted_password);
               
            //$phone_no = '+917355169901';
            $digits_needed=4;

            $source_addr=''; // set up a blank string

            $count=0;

            while ( $count < $digits_needed ) {
                $random_digit = mt_rand(0, 9);
               
                $source_addr .= $random_digit;
                $count++;
            }
            //echo "Phone No. ".$posted_phone; echo "Source Code".$source_addr;
            $replies = send_sms($posted_phone,(int)$source_addr, "Your secure code is ".$source_addr) or die ("Error: " . $errstr . "\n");
           
            if($replies){

                $wpdb->query( $wpdb->prepare("INSERT INTO `taxi_sms_register`(`firstname`, `lastname`, `password`, `image`, `email`, `phoneno`, `scode`, `carnumber`, `status`, `usertype`, `issocialuser`, `deviceId`) VALUES ( '".$posted_firstname."', '".$posted_lastname."', '".$pass_word."', '".$image."', '".$posted_email."', ".$posted_phone.", ".$source_addr.", '".$posted_carnumber."', 0,'".$posted_usertype."', '".$posted_socialuser."', '".$deviceId."' )"));
               
                    if($wpdb->insert_id){
                        $response = array(
                            'Message' => 'Success',
                            'SecureCode' => $source_addr,
                            'regId' => (string)$wpdb->insert_id
                        );
                    }else{
                        $response = array(
                            'Message' => 'Failure'
                        );
                    }
            }else{
                $response = array(
                    'Message' => 'Failure'
                );
            }
        }else{
            $response['Message'] = 'Failure';
        }
//    }else{
//            $response['Message'] = 'Failure email exits';
//        }
    $return_data = $response;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////+++++++ Verify SMS Registered +++++//////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////       
}    else if($usertype == 'chksms'){
            global $wpdb;
           
            $return_data = array();
            $data = array();
           
            $date = date('Y-m-d H:i:s');
            $posted_regId = $_GET['regId'];
            $posted_scode = $_GET['scode'];
           
            if(isset($posted_regId) && isset($posted_scode)){
           
                $querystr = "SELECT * FROM `taxi_sms_register` WHERE `regId`=".$posted_regId." AND `scode` = ".$posted_scode;

                $userInfo = $wpdb->get_results($querystr, OBJECT);
   
                foreach($userInfo as $uInfo){    
                   
                        $querystr = "SELECT * FROM `taxi_users` WHERE `user_email` = '".$uInfo->email."' AND `IsSocialUser` = '".$uInfo->issocialuser."' ";
                               
                        $uinfo1 = $wpdb->get_results($querystr, OBJECT);
                        foreach($uinfo1 as $info){
                            $userId = $info->regId;
                        }
                   
                        if( !$userId ) {
           
                            $wpdb->query( $wpdb->prepare("INSERT INTO `taxi_users`( `user_login`, `user_pass`, `user_nicename`, `user_email`,  `user_image`, `user_phone`, `user_carnumber`, `user_registered`, `display_name`, `IsSocialUser`, `deviceId`) VALUES ( '".$uInfo->email."', '".$uInfo->password."', '".$uInfo->firstname .' '. $uInfo->lastname."', '".$uInfo->email."', '".$uInfo->image."', '".$uInfo->phoneno."', '".$uInfo->carnumber."', '".$date."', '".$uInfo->firstname."', '".$uInfo->issocialuser."', '".$uInfo->deviceId."' )"));
                           
                            if($wpdb->insert_id){
                                    $data['userId'] = (string)$wpdb->insert_id;
                                    $data['IsSocialMedia'] = $uInfo->issocialuser;
                                    $data['Message'] = 'Success';
                                } else{
                                $data['userId'] = "0";
                                $data['Message'] = 'Failure';
                            }
                        } else{
                            $data['userId'] = "0";
                            $data['Message'] = 'Failure';
                        }
                }
            } else{
                            $data['userId'] = "0";
                            $data['Message'] = 'Failure';
            }

            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ My Chat +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
            }    else if($usertype == 'mychat'){
            global $wpdb;
           
            $return_data = array();
            $data = array();
           
            $sellerId = $_GET['sid'];
           
            $userId = $_GET['uid'];
           
            $sendingUserId = $_GET['suid'];
           
            $message = $_GET['msg'];
           
            if(isset($sellerId) && isset($userId)){
           
                $wpdb->query( $wpdb->prepare("INSERT INTO `taxi_my_chat`( `userId`, `sellerId`, `sendingUserId`, `message`, `readStatus`) VALUES ( '".$userId."', '".$sellerId."', '".$sendingUserId."', '".$message."', 'N' )"));
               
                if($wpdb->insert_id){
                        $data['Message'] = 'Success';
                    } else{
                    $data['Message'] = 'Failure';
                }
            } else{
                $data['Message'] = 'Failure';
            }

            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////+++++++ Get Unread message +++++//////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////               
            }    else if($usertype == 'getUnread'){
            global $wpdb;
           
            $return_data = array();
            $data = array();
           
            $sellerId = $_GET['sid'];
           
            $userId = $_GET['uid'];
           
            if(isset($sellerId) && isset($userId)){
           
                $querystr = "SELECT * FROM `taxi_my_chat` WHERE `userId` = '".$userId."' AND `sellerId` = '".$sellerId."' AND `readStatus` = 'N' ORDER BY `chatId` DESC";
                   
                $chatInfo = $wpdb->get_results($querystr, OBJECT);
               
                if($chatInfo){
                    foreach($chatInfo as $cInfo){
                   
                        //$wpdb->query( $wpdb->prepare("UPDATE `taxi_my_chat` SET `readStatus`='Y' WHERE `chatId` = ".$cInfo->chatId));
                       
                        $info[] = array(
                                'Id' => $cInfo->sendingUserId,
                                'message' =>$cInfo->message,
                                'read' => $cInfo->readStatus,
                                'date' => $cInfo->date
                            );
                       
                    }
                   
                    $user = get_userdata( $userId ); //echo "<pre>"; print_r($user);
                   
                    $url = 'https://android.googleapis.com/gcm/send';
                    //echo $user->data->deviceId;
                    $data123 = array( 'message' => 'You got a notification message.' );
                    $registration_ids123 = array( $user->data->deviceId );
                   
                    $fields = array(
                        'registration_ids' => $registration_ids123,
                        'data' => $data123
                    );
//echo "<pre>"; print_r($fields);
                    $headers = array(
                        'Authorization: key =AIzaSyA2XVNk-m80h8D7jIm4liPGcl-wOSiEwhg',
                        'Content-Type: application/json'
                    );
                    // Open connection
                                            $ch = curl_init();

                                            // Set the url, number of POST vars, POST data
                                            curl_setopt($ch, CURLOPT_URL, $url);

                                            curl_setopt($ch, CURLOPT_POST, true);
                                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                                            // Disabling SSL Certificate support temporarly
                                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

                                            // Execute post
                                            $result = curl_exec($ch);
                                            if ($result === FALSE) {
                                                die('Curl failed: ' . curl_error($ch));
                                            }

                                            // Close connection
                                            curl_close($ch);
                   
                    //echo "<pre>"; print_r($result);
                        $data['Message'] = 'Success';
                        $data['info'] = $info;
                        //$data['notification'] = $result;
                    } else{
                    $data['Message'] = 'Failure';
                }
            } else{
                $data['Message'] = 'Failure';
            }

            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////+++++++ Facebook User Registered +++++//////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'editUser'){
             global $wpdb;
           
            $posted_userid = $_GET['uid'];
            $posted_usertype = $_GET['ut'];
           
            $return_data = array();
            $data = array();
           
            if( !empty($posted_userid) && !empty($posted_usertype) ){

                $wpdb->query( $wpdb->prepare("UPDATE taxi_users SET usertype = '".$posted_usertype."' WHERE ID = ".$posted_userid));
           
                $data['Message'] = 'Success';
            }else{
                $data['Message'] = 'Failure';
            }
            $return_data = $data;
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////+++++++ Facebook User Registered +++++//////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'upProf'){
             global $wpdb;
           
            $return_data = array();
            $data = array();
           
            $user_id = $_POST['uid'];
            $isSocial = $_POST['isSocial'];
            $userPhone = $_POST['ph'];
            if($user_id){
            if( !empty($user_id) && !empty($isSocial) && ( $isSocial == 'F' || $isSocial == 'G' )){
               
                $wpdb->query( $wpdb->prepare("UPDATE taxi_users SET user_phone = '".$userPhone."' WHERE ID = ".$user_id));
           
            } else{
               
                $userName = $_POST['uname'];
               
                $userEmail = $_POST['email'];
               
                $upload_dir = wp_upload_dir();
               
                if (isset($_POST['img']) && !empty($_POST['img'])) {
                            $iimg = $_POST['img'];
                           
                            $data1 = base64_decode($iimg);
                            $imgId = rand(1000000,9999999);
                            $dir = $upload_dir['basedir'].'/customers/'.$posted_firstname.'-'.$imgId.'-'.$posted_phone.'.png';
                            file_put_contents( $dir, $data1);
                           
                            $image = $upload_dir['baseurl'].'/customers/'.$posted_firstname.'-'.$imgId.'-'.$posted_phone.'.png';
                        } else {
                            $image = $upload_dir['baseurl'].'/customers/no_image.jpg';
                        }
                       
               
               
                $wpdb->query( $wpdb->prepare("UPDATE `taxi_users` SET `user_nicename`= '".$userName."',`user_image`= '".$image."',`user_email`= '".$userEmail."',`user_phone`= '".$userPhone."' WHERE `ID` = ".$user_id));
               
            }

                $data['Message'] = 'Success';
            }else{
                $data['Message'] = 'Failure';
            }
            $return_data = $data;        
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////+++++++ Get User Seller Chat +++++//////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////               
            }    else if($usertype == 'getchat'){
            global $wpdb;
           
            $return_data = array();
            $data = array();
           
            $sellerId = $_GET['sid'];
           
            $userId = $_GET['uid'];
           
            if(isset($sellerId) && isset($userId)){
           
                $querystr = "SELECT * FROM `taxi_my_chat` WHERE `userId` = '".$userId."' AND `sellerId` = '".$sellerId."' ORDER BY `chatId` DESC";
                   
                $chatInfo = $wpdb->get_results($querystr, OBJECT);
               
                if($chatInfo){
                    foreach($chatInfo as $cInfo){
                   
                        $wpdb->query( $wpdb->prepare("UPDATE `taxi_my_chat` SET `readStatus`='Y' WHERE `chatId` = ".$cInfo->chatId));
                       
                        $info[] = array(
                                'Id' => $cInfo->sendingUserId,
                                'message' =>$cInfo->message,
                                'read' => $cInfo->readStatus,
                                'date' => $cInfo->date
                            );
                       
                    }
                        $data['Message'] = 'Success';
                        $data['info'] = $info;
                    } else{
                    $data['Message'] = 'Failure';
                }
            } else{
                $data['Message'] = 'Failure';
            }

            $return_data = $data;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////+++++++ Get My Buddy+++++//////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////               
            }    else if($usertype == 'mybuddy'){
            global $wpdb;
           
            $return_data = array();
            $data = array();
           
            $userId = $_GET['uid'];
           
            if( isset($userId) ){
           
                $querystr = "SELECT * FROM `taxi_my_chat` WHERE `userId` = '".$userId."' ORDER BY `chatId` DESC";
                   
                $chatInfo = $wpdb->get_results($querystr, OBJECT);
               
                if($chatInfo){
                    foreach($chatInfo as $cInfo){
                   
                        $uquerystr = "SELECT * FROM `taxi_my_chat` WHERE `sellerId` = '".$cInfo->sellerId."' AND `userId` = '".$cInfo->userId."' ORDER BY `chatId` DESC LIMIT 1";
                   
                        $userInfo = $wpdb->get_results($uquerystr, OBJECT);
                       
                        foreach($userInfo as $uInfo){
                       
                            $user = get_userdata( $uInfo->sellerId );
                           
                            $info[] = array(
                                'userId' =>$user->data->ID,
                                'userName' =>$user->data->user_nicename,
                                'userImage' =>$user->data->user_image,
                                'message' =>$uInfo->message,
                                'read' => $uInfo->readStatus,
                                'date' => $uInfo->date
                            );
                        }
                    }
                        $data['Message'] = 'Success';
                        $data['info'] = $info;
                    } else{
                    $data['Message'] = 'Failure';
                }
            } else{
                $data['Message'] = 'Failure';
            }

            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ User Registered +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        }/* else if($usertype == 'regis'){
            global $wpdb;
           
            $date = date('Y-m-d H:i:s');
            $posted_useremail = $_GET['uemail'];
            $posted_username = $_GET['uname'];
            $posted_phone = $_GET['ph'];
            $posted_issocial = $_GET['issocial'];
           
            $return_data = array();
            $data = array();
            if( email_exists( $posted_useremail ) ) {
                    $data['Message'] = 'Failure';
            }else{
           
                $wpdb->query( $wpdb->prepare("INSERT INTO taxi_users ( user_login, user_email, user_status, display_name, IsSocialUser, user_registered) VALUES ( %s, %s, %s, %s, %s, %s )", array( $posted_username, $posted_useremail, 1, $posted_username,$posted_issocial, $date ) ));   
           
                if($wpdb->insert_id){
                    $data['userId'] = (string)$wpdb->insert_id;
                    $data['Message'] = 'Success';
                }else{
                    $data['Message'] = 'Failure';
                }
            }   
            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ User Registered +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else    if($usertype == 'register'){
            global $wpdb;
           
            $return_data = array();
           
            $date = date('Y-m-d H:i:s');
            $posted_useremail = $_GET['uemail'];
            $posted_firstname = $_GET['fname'];
            $posted_lastname = $_GET['lname'];
            $posted_phone = $_GET['uphone'];
            $posted_password = $_GET['upass'];
            //$posted_usertype = $_GET['utype'];
   

            //$user_name = htmlspecialchars($posted_username,ENT_QUOTES);
           
            //$user_name = base64_encode(htmlspecialchars($posted_username,ENT_QUOTES));
           
            $pass_word = wp_hash_password($posted_password);

            $pass_md5 = md5($posted_password);

            $pass = $pass_word;

            $userinfo = $user = get_user_by('user_email', $posted_useremail );

                if ( $posted_useremail != $userinfo->user_email ){

                    $return_data = array();
               
                    $userdata = array(
                            'user_login'  =>  $posted_useremail,
                            'user_pass'   =>  $posted_password,
                            'user_firstname' => $posted_firstname,
                            'user_lastname' => $posted_lastname,
                            'user_email' => $posted_useremail,
                            'user_registered' => $date,
                            //'user_type' => $posted_usertype,
                            'display_name' => $posted_firstname
                        );
                   
                    $user_id = wp_insert_user( $userdata );
                    if($user_id){
                        //$data = array();
                        //echo "<pre>"; print_r($user_id);
                        if($user_id->errors){
                            $data['userId'] = "0";
                            $data['Message'] = 'Failure';
                        }else{
                            $data['userId'] = (string)$user_id;
                            $data['Message'] = 'Success';
                        }
                       
                        $return_data = $data;
                    }
                }*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Driver Registered +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
         elseif($usertype == 'fnduser'){
            global $wpdb;
               
            $return_data = array();
           
            $data = array();
           
            $info = array();
           
            $starting_add = $_GET['sadd'];
           
            $ending_add = $_GET['eadd'];
           
            $user_id = $_GET['uid'];
           
           
           
                    $starting_add = str_replace(' ', '+', $starting_add);
                    $url = "http://maps.google.com/maps/api/geocode/json?address=".$starting_add."&sensor=false";
                    $response = file_get_contents($url);
                    $response = json_decode($response, true);
                   
                    $start_latitude = $response['results'][0]['geometry']['location']['lat'];
                    $start_longitude = $response['results'][0]['geometry']['location']['lng'];
                   
                    $ending_add = str_replace(' ', '+', $ending_add);
                    $url = "http://maps.google.com/maps/api/geocode/json?address=".$ending_add."&sensor=false";
                    $response = file_get_contents($url);
                    $response = json_decode($response, true);
                   
                    $end_latitude = $response['results'][0]['geometry']['location']['lat'];
                    $end_longitude = $response['results'][0]['geometry']['location']['lng'];
                   
                    $radius = 3;

                if ( !empty($start_latitude) && !empty($start_longitude) && !empty($end_latitude) && !empty($end_longitude) ){
                   
                    $user = get_userdata( $user_id );
                   
                    $querystr = "SELECT driverId FROM taxi_routes WHERE driverId = ".$user_id;

                    $userInfo = $wpdb->get_results($querystr, OBJECT);
                   
                    foreach($userInfo as $uinfo){
                        $din = $uinfo;
                    }
                   
                    if($din){
                   
                        $wpdb->query( $wpdb->prepare("UPDATE taxi_routes SET saddress = '".$starting_add."',  daddress = '".$ending_add."', driver_start_lag = ".$start_longitude.", driver_start_lat = ".$start_latitude.", driver_desti_lag = ".$end_longitude.", driver_desti_lat = ".$end_latitude.", userType = ".$user->usertype."  WHERE driverId = ".$din->driverId));
                       
                    }else{

                        $wpdb->query( $wpdb->prepare("INSERT INTO taxi_routes ( driverId, saddress, daddress, driver_start_lag, driver_start_lat, driver_desti_lag, driver_desti_lat, userType ) VALUES ( %d, %s, %s, %s, %s, %s, %s, %s )", array( $user_id, $starting_add, $ending_add, $start_longitude, $start_latitude, $end_longitude,  $end_latitude,  $user->usertype ) ));
                       
                    } //echo $user->usertype;
////----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
////----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   
                if( $user->usertype == 'P' ){
                   
                        $startquerystr = "SELECT *,( 3959 * acos( cos( radians('".$start_latitude."') ) * cos( radians( driver_start_lat ) ) * cos( radians( driver_start_lag ) - radians('".$start_longitude."') ) + sin( radians('".$start_latitude."') ) * sin( radians( driver_start_lat ) ) ) ) AS distance FROM taxi_routes WHERE  userType = 'D' HAVING distance < '".$radius."' ORDER BY distance";
   
                        $startInfo = $wpdb->get_results($startquerystr, OBJECT);                 //echo "startquerystr<pre>"; print_r($startInfo);
                   
                         foreach( $startInfo as $sinfo ) {
                            $info['startInfo'][] = array(
                                'ID' => $sinfo->driverId,
                                'langitude' =>$sinfo->driver_start_lag,
                                'latitude' => $sinfo->driver_start_lat
                            );
                         }
                   
                        $endquerystr = "SELECT *,( 3959 * acos( cos( radians('".$end_latitude."') ) * cos( radians( driver_desti_lat ) ) * cos( radians( driver_desti_lag ) - radians('".$end_longitude."') ) + sin( radians('".$end_latitude."') ) * sin( radians( driver_desti_lat ) ) ) ) AS distance FROM taxi_routes  WHERE  userType = 'D' HAVING distance < '".$radius."' ORDER BY distance";
                   
                         $endInfo = $wpdb->get_results($endquerystr, OBJECT);
                        //echo "endquerystr<pre>"; print_r($endInfo);
                        foreach( $endInfo as $einfo ) {
                            $info['endInfo'][] = array(
                                'ID' => $einfo->driverId,
                                'langitude' =>$einfo->driver_desti_lag,
                                'latitude' => $einfo->driver_desti_lat
                            );
                         }
                       
                    }else{
                   
                        $startquerystr = "SELECT *,( 3959 * acos( cos( radians('".$start_latitude."') ) * cos( radians( driver_start_lat ) ) * cos( radians( driver_start_lag ) - radians('".$start_longitude."') ) + sin( radians('".$start_latitude."') ) * sin( radians( driver_start_lat ) ) ) ) AS distance FROM taxi_routes WHERE  userType = 'P' HAVING distance < '".$radius."' ORDER BY distance";
                   
                        $startInfo = $wpdb->get_results($startquerystr, OBJECT); //echo "startInfo<pre>"; print_r($startInfo);
                   
                         foreach( $startInfo as $sinfo ) {
                            $info['startInfo'][] = array(
                                'ID' => $sinfo->driverId,
                                'langitude' =>$sinfo->driver_start_lag,
                                'latitude' => $sinfo->driver_start_lat
                            );
                         }
                   
                        $endquerystr = "SELECT *,( 3959 * acos( cos( radians('".$end_latitude."') ) * cos( radians( driver_desti_lat ) ) * cos( radians( driver_desti_lag ) - radians('".$end_longitude."') ) + sin( radians('".$end_latitude."') ) * sin( radians( driver_desti_lat ) ) ) ) AS distance FROM taxi_routes WHERE  userType = 'P' HAVING distance < '".$radius."' ORDER BY distance";
                   
                         $endInfo = $wpdb->get_results($endquerystr, OBJECT); //echo "endInfo<pre>"; print_r($endInfo);
                       
                        foreach( $endInfo as $einfo ) {
                            $info['endInfo'][] = array(
                                'ID' => $einfo->driverId,
                                'langitude' =>$einfo->driver_desti_lag,
                                'latitude' => $einfo->driver_desti_lat
                            );
                         }
                       
                    }
                   
                if($info){
                    $data['Message'] = 'Success';
                    $data['userType'] = $user->usertype;
                    $data['info'] = $info;
                }else{
                            $data['Message'] = 'Failure';
                }
                   
                }else{
                            $data['Message'] = 'Failure';
                }
                $return_data = $data;
            }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ User Login +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
            else if($usertype == 'login'){
            global $wpdb;
                   
                    $data = array();
                   
                    $return_data = array();
                   
                    $credentials = array();
                   
                    $posted_username = $_GET['uname'];
                   
                    $posted_password = $_GET['upass'];
                   
                    $deviceId = $_GET['did'];
                   
                    $user = get_user_by( 'email', $posted_username );
                   
                    $authenticate = wp_authenticate( $user->data->user_login, $posted_password );
                   
                if($authenticate->data){
               
                    $user = $authenticate->data;
                   
                        $wpdb->query( $wpdb->prepare("UPDATE `taxi_users` SET `deviceId`= ".$deviceId." WHERE `ID` = ".$user->ID));
                       
                        if($user){
                            $data['Message'] = 'Success';
                            $data['userId'] = (string)$user->ID;
                        }else{
                            $data['Message'] = 'Failure';
                            $data['userId'] = "0";
                        }
                       
                    }else{
                        $data['Message'] = 'Failure';
                        $data['userId'] = "0";
                    }
                   
                    $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ User Details +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'detail'){
                global $wpdb;
               
                $return_data = array();
               
                $posted_driverID = $_GET['driverID'];
               
                $user = get_userdata( $posted_driverID );
               
                $querystr = mysql_query("SELECT * FROM `taxi_routes` WHERE `driverId` = ".$user->ID);
                $driverInfo = mysql_fetch_assoc($querystr);
               
                    if($user){
                   
                        $data['Message'] = 'Success';
                        $data['userId'] = (string)$user->ID;
                        $data['Email'] = $user->user_email;
                        $data['DriverName'] = $user->display_name;
                        $data['CarNumber'] =  $user->user_carnumber;
                        $data['ContactNo'] =  $user->user_phone;
                        $data['userType'] =  $user->usertype;
                        $data['userImage'] =  $user->user_image;
                        $data['Staringadd'] =  $driverInfo['saddress'];
                        $data['Destinationadd'] =  $driverInfo['daddress'];
                    }else{
                        $data['Message'] = 'Failure';
                        $data['userId'] = "0";
                    }
                $return_data = $data;
               
               
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ User Details +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'udetail'){
                global $wpdb;
               
                $return_data = array();
               
                $posted_driverID = $_GET['uid'];
               
                $user = get_userdata( $posted_driverID );
                //echo "<pre>"; print_r($user);

                    if($user){
                   
                $querystr = mysql_query("SELECT * FROM `taxi_routes` WHERE `driverId` = ".$user->ID);
                $driverInfo = mysql_fetch_assoc($querystr);

                //$driverInfo = $wpdb->get_results($querystr, OBJECT);
                //echo "<pre>"; print_r($driverInfo);
               
               
                        $data['Message'] = 'Success';
                        $data['userId'] = (string)$user->ID;
                        $data['email'] = $user->user_email;
                        $data['userName'] = $user->user_nicename;
                        $data['userImage'] =  $user->user_image;
                        $data['contactNo'] =  $user->user_phone;
                        $data['sociaUser'] =  $user->IsSocialUser;
                        $data['userType'] =  $user->usertype;
                        $data['StaringLat'] =  $driverInfo['driver_start_lat'];
                        $data['StaringLog'] =  $driverInfo['driver_start_lag'];
                        $data['DestinationLat'] =  $driverInfo['driver_desti_lat'];
                        $data['DestinationLog'] =  $driverInfo['driver_desti_lag'];
                    }else{
                        $data['Message'] = 'Failure';
                        $data['userId'] = "0";
                    }
                $return_data = $data;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Check Location +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'cloc'){
            global $wpdb;
           
            $return_data = array();
           
            $posted_driverID = $_GET['driverID'];
            $longitude = $_GET['lag'];
            $latitude = $_GET['lat'];
           
            if( $posted_driverID <> '' && $longitude <> '' && $latitude <> '' ){
           
                $querystr = "SELECT driverId FROM taxi_current_location WHERE driverId = ".$posted_driverID;

                $driverInfo = $wpdb->get_results($querystr, OBJECT);
               
                foreach($driverInfo as $dinfo){
                    $din = $dinfo;
                }
               
                if($din){
                    $wpdb->query( $wpdb->prepare("UPDATE taxi_current_location SET current_lag = ".$longitude.", current_lat = ".$latitude." WHERE driverId = ".$din->driverId));
                    $data['Message'] = 'Success';
                }else{
                    $wpdb->query( $wpdb->prepare("INSERT INTO taxi_current_location ( driverId, current_lag, current_lat) VALUES ( %d, %s, %s )", array( $posted_driverID, $longitude, $latitude ) ));
               
                    if($wpdb->insert_id){
                        $data['Message'] = 'Success';
                    }else{
                        $data['Message'] = 'Failure';
                    }
                }
               
               
            }else{
                $data['Message'] = 'Failure';
            }
            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Perticular  Location +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'ploc'){
            global $wpdb;
           
            $return_data = array();
           
            $posted_driverID = $_GET['driverID'];
           
            $start_longitude = $_GET['slag'];
           
            $start_latitude = $_GET['slat'];
           
            $destination = $_GET['des'];
           
           
            if( $posted_driverID <> '' && $start_longitude <> '' && $start_latitude <> ''  && $destination <> '' ){
           
                    $address = str_replace(' ', '+', $destination);
                    $url = "http://maps.google.com/maps/api/geocode/json?address=".$address."&sensor=false";
                    $response = file_get_contents($url);
                    $response = json_decode($response, true);
                   
                    $end_latitude = $response['results'][0]['geometry']['location']['lat'];
                    $end_longitude = $response['results'][0]['geometry']['location']['lng'];
               
                $querystr = "SELECT driverId FROM taxi_routes WHERE driverId = ".$posted_driverID;

                $driverInfo = $wpdb->get_results($querystr, OBJECT);
               
                foreach($driverInfo as $dinfo){
                    $din = $dinfo;
                }
                if($din){
                    $wpdb->query( $wpdb->prepare("UPDATE taxi_routes SET address = '".$destination."', driver_start_lag = ".$start_longitude.", driver_start_lat = ".$start_latitude.", driver_desti_lag = ".$end_longitude.", driver_desti_lat = ".$end_latitude." WHERE driverId = ".$din->driverId));
                   
                    $data['Message'] = 'Success';
                }else{
                    $wpdb->query( $wpdb->prepare("INSERT INTO taxi_routes ( driverId, address, driver_start_lag, driver_start_lat, driver_desti_lag, driver_desti_lat ) VALUES ( %d, %s, %s, %s, %s, %s )", array( $posted_driverID, $destination, $start_longitude, $start_latitude, $end_longitude,  $end_latitude ) ));
                   
                    if($wpdb->insert_id){
                        $data['Message'] = 'Success';
                    }else{
                        $data['Message'] = 'Failure';
                    }
                }
            }else{
                $data['Message'] = 'Failure';
            }
            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Check Current Location +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'gcloc'){
            global $wpdb;
           
            $return_data = array();
           
            $driverID = $_GET['driverID'];
           
           
            if( $driverID <> '' ){
           
                    $querystr = "SELECT r.*, cl.* FROM taxi_routes r LEFT JOIN taxi_current_location cl ON (r.driverId =  cl.driverId) WHERE r.driverId = $driverID ORDER BY r.addedDate  DESC";

                     $driverInfo = $wpdb->get_results($querystr, OBJECT);
                   
                    $info = array();
                   
                    foreach($driverInfo as $dinfo){
                        $info = array(
                            'userId' => (string)$dinfo->driverId,
                            'driverAddress' => $dinfo->address,
                            'driverStartLag' => $dinfo->driver_start_lag,
                            'driverStartLat' => $dinfo->driver_start_lat,
                            'driverEndLag' => $dinfo->driver_desti_lag,
                            'driverEndLat' => $dinfo->driver_desti_lat
                        //    'driverCurrLocLag' => $dinfo->current_lag,
                        //    'driverCurrLocLat' => $dinfo->current_lat
                        );
                    }
               
                    $data['Message'] = 'Success';
                    $data['driverInfo'] = $info;
            }else{
                $data['Message'] = 'Failure';
            }
            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Find Driver +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        } else if($usertype == 'fdriver'){
            global $wpdb;
           
            $return_data = array();
           
            $longitude = $_GET['clag'];
            $latitude = $_GET['clot'];
            $radius = 3;//$_GET['rad'];
           
           
            if( $longitude <> '' && $latitude <> '' && $radius <> '' ){
           
                $querystr = "SELECT *,( 3959 * acos( cos( radians('".$latitude."') ) * cos( radians( current_lat ) ) * cos( radians( current_lag ) - radians('".$longitude."') ) + sin( radians('".$latitude."') ) * sin( radians( current_lat ) ) ) ) AS distance FROM taxi_current_location HAVING distance < '".$radius."' ORDER BY distance";
                   
                     $driverInfo = $wpdb->get_results($querystr, OBJECT);
                    if($driverInfo){
                        $info = array();
                       
                        foreach($driverInfo as $dinfo){
                            $info[] = array(
                                'userId' => (string)$dinfo->driverId,
                                'current_lag' => (string)$dinfo->current_lag,
                                'current_lat' => (string)$dinfo->current_lat
                                //'addedDate' => $dinfo->addedDate
                            );
                        }
                   
                        $data['Message'] = 'Success';
                        $data['driverInfo'] = $info;
                    }else{
                $data['Message'] = 'Failure';
            }
            }else{
                $data['Message'] = 'Failure';
            }
            $return_data = $data;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////+++++++ Post Return +++++/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////   
        }else{

        // Global options
        $options = WP_Simple_Web_Service::get()->get_options();

        // Get 'get_posts' options
        $gp_options = array();
        if ( isset( $options['get_posts'] ) ) {
            $gp_options = $options['get_posts'];
        }

        // Fix scenario where there are no settings for given post type
        if ( ! isset( $gp_options[$post_type] ) ) {
            $gp_options[$post_type] = array();
        }

        // Setup options
        $pt_options = wp_parse_args( $gp_options[$post_type], $this->get_default_settings() );

        // Check if post type is enabled
        if ( 'false' == $pt_options['enabled'] ) {
            WP_Simple_Web_Service::get()->throw_error( 'Post Type not supported.' );
        }

        // Setup default query vars
        $default_query_arguments = array(
            'posts_per_page' => - 1,
            'order'          => 'ASC',
            'orderby'        => 'title',
        );

        // Get query vars
        $query_vars = array();
        if ( isset( $_GET['qv'] ) ) {
            $query_vars = $_GET['qv'];
        }

        // Merge query vars
        $query_vars = wp_parse_args( $query_vars, $default_query_arguments );

        // Set post type
        $query_vars['post_type'] = $post_type;

        // Get posts
        $posts = get_posts( $query_vars );

        // Post data to show - this will be manageble at some point
        $show_post_data_fields = array( 'ID', 'post_title', 'post_content', 'post_date' );

        // Post meta data to show - this will be manageble at some point
        $show_post_meta_data_fields = array( 'ssm_supermarkt', 'ssm_adres' );

        // Data array
        $return_data = array();

        // Loop through posts
        foreach ( $posts as $post ) {

            $post_custom = get_post_custom( $post->ID );

            $data = array();

            // Add regular post fields data array
            foreach ( $pt_options['fields'] as $show_post_data_field ) {

                $post_field_value = $post->$show_post_data_field;

                // Fetch thumbnail
                if ( 'thumbnail' == $show_post_data_field ) {
                    $post_field_value = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
                }

                // Set post field value
                $data[ $show_post_data_field ] = $post_field_value;
            }

            // Add post meta fields to data array
            foreach ( $pt_options['custom'] as $show_post_meta_data_field ) {

                $meta_field_value = get_post_meta( $post->ID, $show_post_meta_data_field, true );

                if ( $meta_field_value != '' ) {
                    $data[ $show_post_meta_data_field ] = $meta_field_value;
                }

            }

            $return_data = $data;

        }
}
        WPSWS_Output::get()->output( $return_data );
    }

}

Featured post

A23 Rummy - Safe Secure Gaming Platform

A23 Rummy is a popular online rummy platform in India. It is owned and operated by Head Digital Works Private Limited. The platform offers...