Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Need help in this php script

Posted on 2016-04-26
4
Medium Priority
?
140 Views
Last Modified: 2016-05-08
Hello , if someone can comment and explain for me this technically what is code is doing what behind logic and more importantly the once i did comment on top in this code below and about mongo db how can be treated, thanks

<?php

error_reporting(1);

ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
$date = date("Y-m-d H:i:s");
error_log("$date: Hello! Running script /roadyo_base.php" . PHP_EOL);

require('../Models/config.php');
require('../Models/Pubnub.php');

$pubnub = new Pubnub(PUBNUB_PUBLISH_KEY, PUBNUB_SUBSCRIBE_KEY);
//can anyone explain for me technically what is going on with MONGO DB
$con = new MongoClient("mongodb://" . MONGODB_HOST . ":" . MONGODB_PORT . "");
$db = $con->selectDB(MONGODB_DB);
if (MONGODB_USER != '' && MONGODB_PASS != '')
    $db->authenticate(MONGODB_USER, MONGODB_PASS);

$favourite = $db->selectCollection('favourite');
$booking_route = $db->selectCollection('booking_route');

$location = $db->selectCollection('location');

$location->ensureIndex(array("location" => "2d"));

$use = array('pubnub' => $pubnub, 'location' => $location, 'favourite' => $favourite, 'booking_route' => $booking_route, 'db' => $db);

$pubnub->subscribe(array(
    "channel" => APP_PUBNUB_CHANNEL,
    "callback" => function($message) use($use) {
        //what (int) means
        $a = (int) $message['message']['a'];

        $args = $message['message'];

        if ($a == 4) { //update driver location
            if ($args['devId'] == '')
                $cond =
                        array("email" => strtolower($args['e_id']));
            else
                $cond =
                        array("email" => strtolower($args['e_id']));
            //what (double) means 
            $newdata = array('$set' => array("location" => array("longitude" => (double) $args['lg'], "latitude" => (double) $args['lt']), 'lastTs' => time()));

            $use['location']->update($cond, $newdata);
            if (isset($args['bid']) && (int) $args ['bid'] > 0) {
                $data = array("longitude" => (double) $args['lg'], "latitude" => (double) $args['lt']);
                if (is_array($use['booking_route']->findOne(array('bid' => (int) $args['bid'])))) {
                    $use['booking_route']->update(
                            array('bid' => (int) $args['bid'], 'route' => array('$ne' => $data))
                            , array('$push' => array('route' => $data))
                            , array("upsert" => false)
                    );
                } else {
                    $use['booking_route']->insert(array('bid' => (int) $args['bid'], 'route' => array($data)));
                }
            }
        } else if ($a == 2) {//update driver about his status
            $cond = array("email" => strtolower($args['e_id']));

            $master = $use['location']->findOne($cond);

            if ($master['chn'] == 'qd_' . $args ['d_id'])
                $return =
                        array('a' => 2, 's' => $master['status']);
            else
                $return =
                        array('a' => 2, 's' => 0);

            $pubRes[] = $use['pubnub']->publish(array(
                'channel' => $args["chn"],
                'message' => $return
            ));
        } else if ($a == 3) {//Acknowledge message from passenger to driver
            $cond = array("email" => strtolower($args['e_id']));

            $master = $use['location']->findOne($cond);

            $pubRes[] = $use['pubnub']->publish(array(
                'channel' => $master["listner"],
                'message' => $args
            ));
        } else if ($a == 11) {
            $cond = array("pasEmail" => strtolower($args['pid']));

            $favouritesData = $use['favourite']->find($cond);

            $driversArr = array();

            foreach ($favouritesData as $fav) {
                $driversArr[] = $fav['driver'];
            }

            if (count($driversArr) <= 0)
                $pubRes[] =
                        $use['pubnub']->publish(array(
                    'channel' => $master["chn"],
                    'message' => array('a' => 11, 'flag' => 1)
                ));
             //need more explanation on this 
            $resultArr = $use['db']->selectCollection('$cmd')->findOne(array(
                'geoNear' => 'location',
                'near' => array(
                    (double) $args['ent_longitude'], (double) $args['ent_latitude']
                ), 'spherical' => true, 'maxDistance' => 50000 / 6378137, 'distanceMultiplier' => 6378137,
                'query' => array('user' => array('$in' => $driversArr)))
            );

            $md_arr = $es = array();
//                    
            foreach ($resultArr['results'] as $res) {

                $doc = $res['obj'];
                $es[] = $doc['email'];
                $md_arr[] = array('chn' => $doc['chn'], 'e' => $doc['email'], 'lt' => $doc ['location']['latitude'], 'lg' => $doc ['location']['longitude'], 'd' => ($res ['dis']));
            }

            if (count($md_arr) > 0)
                $pubRes[] =
                        $use['pubnub']->publish(array(
                    'channel' => $master["chn"],
                    'message' => array('a' => 11, 'flag' => 0, 'masArr' => $md_arr, 'es' => $es)
                ));
            else
                $pubRes[] =
                        $use['pubnub']->publish(array(
                    'channel' => $master["chn"],
                    'message' => array('a' => 11, 'flag' => 1)
                ));
        } else if ($a == 1) { // send passenger all the drivers in a specific radius
            $found = $foundEmails = $types = $foundEs = $typesData = $foundNew = array();

            if ($args['st'] == '3') { // getting data for live drivers
                $cond = array(
                    'geoNear' => 'vehicleTypes',
                    'near' => array(
                        (double) $args['lg'], (double) $args['lt']
                    ), 'spherical' => true, 'maxDistance' => 50000 / 6378137, 'distanceMultiplier' => 6378137);

                $resultArr1 = $use['db']->selectCollection('$cmd')->findOne($cond);

                foreach ($resultArr1['results'] as $res) {

                    $doc = $res['obj'];

                    $types[] = (int) $doc['type'];

                    $typesData[$doc['type']] = array(
                        'type_id' => (int) $doc['type'],
                        'type_name' => $doc['type_name'],
                        'max_size' => (int) $doc['max_size'],
                        'basefare' => (float) $doc['basefare'],
                        'min_fare' => (float) $doc['min_fare'],
                        'price_per_min' => (float) $doc['price_per_min'],
                        'price_per_km' => (float) $doc['price_per_km'],
                        'type_desc' => $doc['type_desc']
                    );
                }

                $typesDataNew = array();

                $types = array_filter(array_unique($types));
                sort($types);

                foreach ($types as $t) {
                    $typesDataNew[] = $typesData[$t];
                }

                $resultArr = $use['db']->selectCollection('$cmd')->findOne(array(
                    'geoNear' => 'location',
                    'near' => array(
                        (double) $args['lg'], (double) $args['lt']
                    ), 'spherical' => true, 'maxDistance' => 50000 / 6378137, 'distanceMultiplier' => 6378137,
                    'query' => array('status' => 3))
                );

                foreach ($resultArr['results'] as $res) {

                    $doc = $res['obj'];

//                        $types[] = (int) $doc['type'];

                    if (count($foundEs[$doc['type']]) < 5)
                        $foundEs[
                                $doc['type']][] = $doc['email'];

                    $found[$doc['type']][] = array('chn' => $doc['chn'], 'e' => $doc['email'], 'lt' => $doc ['location']['latitude'], 'lg' => $doc ['location']['longitude'], 'd' => ($res ['dis']));
                }
            } else { // scope for later booking 
            }

            $typesFiltered = array_unique(array_filter($types));

            foreach ($typesFiltered as $type) {

                $es[] = array('tid' => $type, 'em' => (is_array($foundEs[$type])) ? $foundEs
                            [$type] : array());
                $masArr[] = array('tid' => $type, 'mas' => (is_array($found[$type])) ? $found[$type] : array());
            }

            if (count($typesDataNew) > 0)
                $return = array('a' => 2, 'masArr' => $masArr, "tp" => $args['tp'], 'st' => $args['st'], 'flag' => 0, 'es' => $es, 'types' => $typesDataNew);
            else
                $return = array('a' => 2, 'flag' => 1, 'types' => $typesDataNew);

            if ($args["chn"] != '')
                $pubRes[] = $use['pubnub']->publish(array(
                    'channel' => $args["chn"],
                    'message' => $return
                ));

     //echo json_encode($args)."\n";
               //echo json_encode($return)."\n\n";
        }
//            echo $a;

        $keepListening = true;
        return $keepListening;
    }
));
?>

Open in new window

0
Comment
Question by:Jaylab
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 41566533
With hundreds of lines of code in play here, it will take too long to try to discern and explain everything the code is doing, so I'll just post some learning resources.  When you write PHP code you can put in comments that describe the objectives of the code blocks.  The comments can include things like URL links to the documentation pages for the APIs you're using, etc.  For specific questions, the SSCCE teaches us a great way to ask a question.

New to PHP?
http://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html

Unsure what works and what doesn't?  Here's what doesn't:
http://www.experts-exchange.com/articles/12293/AntiPHPatterns-and-AntiPHPractices.html

How should you think about application design patterns?
https://www.experts-exchange.com/articles/18329/SOLID-Design-in-PHP-Applications.html

New to SQL and RDBMS?
http://www.w3schools.com/sql/sql_intro.asp

New to MongoDB?
http://www.tutorialspoint.com/mongodb/

Want to learn about GeoCoding?
http://schoolofdata.org/2013/02/19/geocoding-part-i-introduction-to-geocoding/

Want an intro to PHP proximity calculations?
http://www.experts-exchange.com/articles/4276/What-is-near-me-Proximity-calculations-using-PHP-and-MySQL.html

Want to learn about Pubnub Software Developer Kits?
https://www.pubnub.com/docs
0
 

Author Comment

by:Jaylab
ID: 41567388
Hello Ray , wonderful resources links but i was looking to comment same as you are reading the code and put some and not on every single line about the logic writen and what could be corrected and most importantly related to what i comment in this code this could he useful for me and answer directly to question if this can not be done to go and close the question.
Thanks.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 41572460
This is a good item to post in E-E Gigs, where you can hire a knowledgeable professional developer to dig into the details and work with you.  It's not really a question with an answer; it's a requirement for application development, and that's why we have the Gigs link.
0
 

Author Comment

by:Jaylab
ID: 41572493
How this could be done ?
0

Featured Post

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
In this article, I’ll look at how you can use a backup to start a secondary instance for MongoDB.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question