Example #1
0
 public function selectCampus($id)
 {
     $campusid = $id;
     $ipadress = $this->getIPAdress();
     /*store the institutions id alongside the specific ip adress in the devices table
      * and redirect user to the specific homepage
      */
     $exists = Device::where('ip', '=', $ipadress);
     if ($exists->count()) {
         $device = $exists->first();
         $device->branch_id = $campusid;
         if ($device->save()) {
             if (Auth::user()) {
                 return Redirect::route('member-home');
             } else {
                 return Redirect::route('home');
             }
         }
     } else {
         $devicecreate = Device::create(array('ip' => $ipadress, 'branch_id' => $campusid));
         if ($devicecreate) {
             if (Auth::user()) {
                 return Redirect::route('member-home');
             } else {
                 return Redirect::route('home');
             }
         }
     }
     return Redirect::route('selectcampus-get')->withInput()->with('global', 'Sorry!! Campus details were not loaded, please retry.');
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $key = Input::get('key');
     $deliverydate = Input::get('date');
     $dev = \Device::where('key', '=', $key)->first();
     $model = $this->model;
     $merchants = $model->where('group_id', '=', 4)->get();
     //print_r($merchants);
     //die();
     for ($n = 0; $n < count($merchants); $n++) {
         $or = new \stdClass();
         foreach ($merchants[$n] as $k => $v) {
             $nk = $this->underscoreToCamelCase($k);
             $or->{$nk} = is_null($v) ? '' : $v;
         }
         $or->extId = $or->id;
         unset($or->id);
         //$or->boxList = $this->boxList('delivery_id',$or->deliveryId,$key);
         //$or->boxObjects = $this->boxList('delivery_id',$or->deliveryId, $key , true);
         $merchants[$n] = $or;
     }
     $actor = $key;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'logged out'));
     return $merchants;
     //
 }
Example #3
0
 private function getDevice()
 {
     /*require_once(app_path().'/includes/ip.codehelper.io.php');
     		require_once(app_path().'/includes/php_fast_cache.php');
     		
     		$_ip = new ip_codehelper();
     		$campusid = 0;
     		
     		$real_client_ip_address = $_ip->getRealIP();
     		$visitor_location       = $_ip->getLocation($real_client_ip_address);
     		
     		$guest_ip   = $visitor_location['IP'];
     		$guest_country = $visitor_location['CountryName'];*/
     $guest_ip = '0.0.0.0';
     //get the ip address of the remote machine
     if (Session::has('my_ip')) {
         $guest_ip = Session::get('my_ip');
     } else {
         $guest_ip = str_random(60);
         Session::put('my_ip', $guest_ip);
     }
     //check if the ip adress is in the devices table
     $device = Device::where('ip', '=', $guest_ip);
     if ($device->count()) {
         //redirect to the previous page
         $device = $device->first();
         $campusid = $device->branch_id;
         return $campusid;
     } else {
         //redirect to country selection page and save it on selection
         return 0;
     }
 }
 public function testRegisterSucess()
 {
     $response = $this->_getResponse();
     $device = Device::where('auth_key', $this->_params['auth_key'])->where('device_id', $this->_params['device_id'])->where('platform', $this->_params['platform'])->first();
     $this->assertNotNull($device);
     $this->assertTrue($this->client->getResponse()->isOk());
     $this->assertEquals(json_encode(array("code" => ApiResponse::OK, "data" => ApiResponse::getErrorContent(ApiResponse::OK))), $response->getContent());
 }
Example #5
0
 private function getDevice()
 {
     $header = Request::header('Authorization');
     preg_match('#^Bearer\\s+(.*?)$#', $header, $matches);
     $authToken = $matches[1];
     $device = Device::where('auth_token', $authToken)->first();
     return $device;
 }
Example #6
0
 public static function checkSessionId($input)
 {
     $device = Device::where('device_id', $input['device_id'])->where('session_id', $input['session_id'])->where('user_id', $input['user_id'])->first();
     if (!empty($device)) {
         return $input['session_id'];
     }
     return false;
 }
Example #7
0
 private function getUserTokens($userId)
 {
     $tokens = array();
     Device::where('user_id', $userId)->get()->each(function ($device) use(&$tokens) {
         $this->info("Tokens {$device->auth_token}");
         $tokens[] = $device->auth_token;
     });
     return $tokens;
 }
Example #8
0
 public function getOwnerToken()
 {
     $token = null;
     if (isset($this->user_id) && (int) $this->user_id > 0) {
         $device = Device::where('user_id', $this->user_id)->get()->first();
         if ($device) {
             $token = $device->auth_token;
         }
     }
     return $token;
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function logout()
 {
     $input = Input::all();
     $device = Device::where('device_id', $input['device_id'])->where('user_id', $input['user_id'])->first();
     if ($device) {
         if ($device->session_id == $input['session_id']) {
             Device::find($device->id)->update(['session_id' => null]);
             return Common::returnData(200, SUCCESS, $input['user_id'], '');
         } else {
             throw new Prototype\Exceptions\UserSessionErrorException();
         }
     }
     throw new Prototype\Exceptions\DeviceErrorException();
 }
 public function getRedirect($username, $id)
 {
     $link = Link::where('id', '=', $id)->first();
     /*Get user ip address*/
     $ip_address = $_SERVER['REMOTE_ADDR'];
     $device = Device::where('ip', '=', $ip_address);
     if (!$device->count()) {
         //record the device
         $user = Device::create(array('ip' => $ip_address));
         $link->clicks = $link->clicks + 1;
         $link_save = $link->save();
     }
     return Redirect::away($link->link_name);
 }
Example #11
0
 /**
  * Api function for get listing notifications by device id.
  *
  * @return mixed
  */
 public function getNotificationByDeviceId()
 {
     $data = Input::all();
     $valids = Validator::make($data, ['device_id' => 'required|alpha_dash']);
     // Check validator.
     if ($valids->fails()) {
         return Response::json(array('status' => 'error', 'data' => $valids->messages()));
     }
     // Find device id.
     $record = Device::where('device_id', $data['device_id'])->first();
     if (!$record) {
         return Response::json(array('status' => 'error', 'data' => Lang::get('dlnlab.aloexrates::message.device_not_exist')));
     }
     $records = Notification::where('device_id', $record->id)->get()->toArray();
     return Response::json(array('status' => 'successs', 'data' => $records));
 }
Example #12
0
 private function storeOrGet($type, $id)
 {
     $user = Auth::user();
     $like = $this->get($type, $id, $user->id);
     if (!$like) {
         $like = Like::create(['likeable_id' => $id, 'likeable_type' => $type, 'user_id' => $user->id, 'created_at' => Carbon\Carbon::now()]);
         if (in_array($type, array('Post', 'Comment'))) {
             $object = $type::find($id);
             if ($object) {
                 if ($user->id != $object->user_id && ($device = Device::where('user_id', $object->user_id)->get()->first())) {
                     $method = "set{$type}AsLiked";
                     $state = new StateSender($device->auth_token);
                     $state->{$method}($object, Auth::user());
                 }
             }
         }
     }
     return $like;
 }
Example #13
0
 public static function push_notification($input)
 {
     $error_code = ApiResponse::OK;
     $validator = Validator::make($input, array('auth_key' => 'required', 'device_id' => 'required', 'platform' => 'required'));
     //validate params
     if ($validator->fails()) {
         $error_code = ApiResponse::MISSING_PARAMS;
         $data = $input;
     } else {
         //check device existed
         if (Device::where('auth_key', $input['auth_key'])->first() != null) {
             $error_code = ApiResponse::EXISTED_DEVICE;
             $data = ApiResponse::getErrorContent(ApiResponse::EXISTED_DEVICE);
         } else {
             $device = Device::create($input);
             if ($device) {
                 $data = "ok";
             }
         }
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #14
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $key = Input::get('key');
     $deliverydate = Input::get('date');
     /*
                         ->join('members as m','d.merchant_id=m.id','left')
                         ->where('assignment_date',$indate)
                         ->where('device_id',$dev->id)
                         ->and_()
                         ->group_start()
                             ->where('status',$this->config->item('trans_status_admin_courierassigned'))
                             ->or_()
                             ->group_start()
                                 ->where('status',$this->config->item('trans_status_new'))
                                 ->where('pending_count >', 0)
                             ->group_end()
                         ->group_end()
     */
     $dev = \Device::where('key', '=', $key)->first();
     //print_r($dev);
     $txtab = \Config::get('jayon.incoming_delivery_table');
     /*
     $orders = $this->model
                 ->select(
                         \DB::raw(
                             \Config::get('jayon.incoming_delivery_table').'.* ,'.
                             \Config::get('jayon.jayon_members_table').'.merchantname as merchant_name ,'.
                             \Config::get('jayon.applications_table').'.application_name as app_name ,'.
                             '('.$txtab.'.width * '.$txtab.'.height * '.$txtab.'.length ) as volume'
                         )
                 )
                 ->leftJoin(\Config::get('jayon.jayon_members_table'), \Config::get('jayon.incoming_delivery_table').'.merchant_id', '=', \Config::get('jayon.jayon_members_table').'.id' )
                 ->leftJoin(\Config::get('jayon.applications_table'), \Config::get('jayon.incoming_delivery_table').'.application_id', '=', \Config::get('jayon.applications_table').'.id' )
     
                 ->where('device_id','=',$dev->id)
                 ->where('assignment_date','=',$deliverydate)
     
                 ->where(function($q){
                     $q->where('status','=', \Config::get('jayon.trans_status_new') )
                         ->orWhere(function($ql){
                             $ql->where('status','=', \Config::get('jayon.trans_status_new') )
                                 ->where('pending_count','>',0);
                         });
                 })
                 ->orderBy('ordertime','desc')
                 ->get();
     */
     $orders = $this->model->select(\DB::raw(\Config::get('jayon.incoming_delivery_table') . '.* ,' . \Config::get('jayon.jayon_couriers_table') . '.fullname as courier ,' . \Config::get('jayon.jayon_devices_table') . '.identifier as device ,' . \Config::get('jayon.jayon_members_table') . '.merchantname as merchant_name ,' . \Config::get('jayon.applications_table') . '.application_name as app_name ,' . '(' . $txtab . '.width * ' . $txtab . '.height * ' . $txtab . '.length ) as volume'))->leftJoin(\Config::get('jayon.jayon_couriers_table'), \Config::get('jayon.incoming_delivery_table') . '.courier_id', '=', \Config::get('jayon.jayon_couriers_table') . '.id')->leftJoin(\Config::get('jayon.jayon_devices_table'), \Config::get('jayon.incoming_delivery_table') . '.device_id', '=', \Config::get('jayon.jayon_devices_table') . '.id')->leftJoin(\Config::get('jayon.jayon_members_table'), \Config::get('jayon.incoming_delivery_table') . '.merchant_id', '=', \Config::get('jayon.jayon_members_table') . '.id')->leftJoin(\Config::get('jayon.applications_table'), \Config::get('jayon.incoming_delivery_table') . '.application_id', '=', \Config::get('jayon.applications_table') . '.id')->where(function ($query) use($deliverydate) {
         /*
         ->where('warehouse_status','=', \Config::get('jayon.trans_status_atmerchant') )
         */
         $query->where('pickup_status', '=', \Config::get('jayon.trans_status_pickup'))->where('status', '!=', \Config::get('jayon.trans_status_canceled'))->where('status', '!=', \Config::get('jayon.trans_status_mobile_delivered'))->where('ordertime', '>=', $deliverydate);
         /*
                             ->orWhere('status','=', \Config::get('jayon.trans_status_mobile_pickedup') )
                             ->orWhere('status','=', \Config::get('jayon.trans_status_mobile_enroute') )
                             ->orWhere(function($q){
                                     $q->where('status', \Config::get('jayon.trans_status_new'))
                                         ->where(\Config::get('jayon.incoming_delivery_table').'.pending_count', '>', 0);
                             })*/
     })->orderBy('ordertime', 'desc')->get();
     $norders = array();
     for ($n = 0; $n < count($orders); $n++) {
         $or = new \stdClass();
         foreach ($orders[$n] as $k => $v) {
             $nk = $this->underscoreToCamelCase($k);
             if (in_array($nk, $this->order_unset)) {
             } else {
                 $or->{$nk} = is_null($v) ? '' : $v;
             }
         }
         $or->extId = $or->id;
         unset($or->id);
         $bc = \Box::where('delivery_id', '=', $or->deliveryId)->count();
         if ($bc == 0) {
             $this->createBox($or->deliveryId, $or->merchantTransId, $or->fulfillmentCode, $or->boxCount);
         }
         $or->boxList = $this->boxList('delivery_id', $or->deliveryId, $key, $or->merchantId);
         $or->boxObjects = $this->boxList('delivery_id', $or->deliveryId, $key, $or->merchantId, true);
         $or->merchantObject = $this->merchantObject($or->merchantId);
         $orders[$n] = $or;
         //$norders[] = $or;
     }
     $actor = $key;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'logged out'));
     return $orders;
     //
 }
Example #15
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $key = Input::get('key');
     $deliverydate = Input::get('date');
     $until = Input::get('until');
     if (is_null($until) || $until == '') {
         $until = date('Y-m-d', time());
     }
     /*
                         ->join('members as m','d.merchant_id=m.id','left')
                         ->where('assignment_date',$indate)
                         ->where('device_id',$dev->id)
                         ->and_()
                         ->group_start()
                             ->where('status',$this->config->item('trans_status_admin_courierassigned'))
                             ->or_()
                             ->group_start()
                                 ->where('status',$this->config->item('trans_status_new'))
                                 ->where('pending_count >', 0)
                             ->group_end()
                         ->group_end()
     */
     $dev = \Device::where('key', '=', $key)->first();
     //print_r($dev);
     $txtab = \Config::get('jayon.incoming_delivery_table');
     /*
     $orders = $this->model
                 ->select(
                         \DB::raw(
                             \Config::get('jayon.incoming_delivery_table').'.* ,'.
                             \Config::get('jayon.jayon_members_table').'.merchantname as merchant_name ,'.
                             \Config::get('jayon.applications_table').'.application_name as app_name ,'.
                             '('.$txtab.'.width * '.$txtab.'.height * '.$txtab.'.length ) as volume'
                         )
                 )
                 ->leftJoin(\Config::get('jayon.jayon_members_table'), \Config::get('jayon.incoming_delivery_table').'.merchant_id', '=', \Config::get('jayon.jayon_members_table').'.id' )
                 ->leftJoin(\Config::get('jayon.applications_table'), \Config::get('jayon.incoming_delivery_table').'.application_id', '=', \Config::get('jayon.applications_table').'.id' )
     
                 ->where('device_id','=',$dev->id)
                 ->where('assignment_date','=',$deliverydate)
     
                 ->where(function($q){
                     $q->where('status','=', \Config::get('jayon.trans_status_new') )
                         ->orWhere(function($ql){
                             $ql->where('status','=', \Config::get('jayon.trans_status_new') )
                                 ->where('pending_count','>',0);
                         });
                 })
                 ->orderBy('ordertime','desc')
                 ->get();
     */
     $orders = $this->model->select(\DB::raw(\Config::get('jayon.incoming_delivery_table') . '.* ,' . \Config::get('jayon.jayon_couriers_table') . '.fullname as courier ,' . \Config::get('jayon.jayon_devices_table') . '.identifier as device ,' . \Config::get('jayon.jayon_members_table') . '.merchantname as merchant_name ,' . \Config::get('jayon.applications_table') . '.application_name as app_name ,' . '(' . $txtab . '.width * ' . $txtab . '.height * ' . $txtab . '.length ) as volume'))->leftJoin(\Config::get('jayon.jayon_couriers_table'), \Config::get('jayon.incoming_delivery_table') . '.courier_id', '=', \Config::get('jayon.jayon_couriers_table') . '.id')->leftJoin(\Config::get('jayon.jayon_devices_table'), \Config::get('jayon.incoming_delivery_table') . '.device_id', '=', \Config::get('jayon.jayon_devices_table') . '.id')->leftJoin(\Config::get('jayon.jayon_members_table'), \Config::get('jayon.incoming_delivery_table') . '.merchant_id', '=', \Config::get('jayon.jayon_members_table') . '.id')->leftJoin(\Config::get('jayon.applications_table'), \Config::get('jayon.incoming_delivery_table') . '.application_id', '=', \Config::get('jayon.applications_table') . '.id')->where(function ($query) use($deliverydate, $until) {
         $query->where('pickup_status', '=', \Config::get('jayon.trans_status_tobepickup'))->where('status', '!=', \Config::get('jayon.trans_status_canceled'))->where('status', '!=', \Config::get('jayon.trans_status_mobile_delivered'))->whereBetween('ordertime', array($deliverydate . ' 00:00:00', $until . ' 23:59:59'));
         //->where('ordertime','>=',$deliverydate.' 00:00:00');
         /*
                             ->orWhere('status','=', \Config::get('jayon.trans_status_mobile_pickedup') )
                             ->orWhere('status','=', \Config::get('jayon.trans_status_mobile_enroute') )
                             ->orWhere(function($q){
                                     $q->where('status', \Config::get('jayon.trans_status_new'))
                                         ->where(\Config::get('jayon.incoming_delivery_table').'.pending_count', '>', 0);
                             })*/
     })->orderBy('ordertime', 'desc')->get();
     $total_billing = 0;
     $total_delivery = 0;
     $total_cod = 0;
     $norders = array();
     for ($n = 0; $n < count($orders); $n++) {
         $or = new \stdClass();
         foreach ($orders[$n] as $k => $v) {
             $nk = $this->underscoreToCamelCase($k);
             if (in_array($nk, $this->order_unset)) {
             } else {
                 $or->{$nk} = is_null($v) ? '' : $v;
             }
         }
         $or->extId = $or->id;
         unset($or->id);
         $bc = \Box::where('delivery_id', '=', $or->deliveryId)->count();
         if ($bc == 0) {
             $this->createBox($or->deliveryId, $or->merchantTransId, $or->fulfillmentCode, $or->boxCount);
         }
         $or->boxList = $this->boxList('delivery_id', $or->deliveryId, $key, $or->merchantId);
         $or->boxObjects = $this->boxList('delivery_id', $or->deliveryId, $key, $or->merchantId, true);
         $or->merchantObject = $this->merchantObject($or->merchantId);
         /* chargeable */
         $total = doubleval($or->totalPrice);
         $dsc = doubleval($or->totalDiscount);
         $tax = doubleval($or->totalTax);
         $dc = doubleval($or->deliveryCost);
         $cod = doubleval($or->codCost);
         $total = is_nan($total) ? 0 : $total;
         $dsc = is_nan($dsc) ? 0 : $dsc;
         $tax = is_nan($tax) ? 0 : $tax;
         $dc = is_nan($dc) ? 0 : $dc;
         $cod = is_nan($cod) ? 0 : $cod;
         //print $total.' '.$dsc.' '.$tax.' '.$dc.' '.$cod."\r\n";
         $payable = 0;
         $details = \Deliverydetail::where('delivery_id', '=', $or->deliveryId)->orderBy('unit_sequence', 'asc')->get();
         $details = $details->toArray();
         $d = 0;
         $gt = 0;
         foreach ($details as $value => $key) {
             $u_total = doubleval($key['unit_total']);
             $u_discount = doubleval($key['unit_discount']);
             $gt += is_nan($u_total) ? 0 : $u_total;
             $d += is_nan($u_discount) ? 0 : $u_discount;
         }
         if ($gt == 0) {
             if ($total > 0 && $payable) {
                 $gt = $total;
             }
         }
         //print $gt.' '.$dsc.' '.$tax.' '.$dc.' '.$cod."\r\n";
         $payable = $gt;
         $db = '';
         if ($or->deliveryBearer == 'merchant') {
             $dc = 0;
         }
         //force all DO to zero
         $cb = '';
         if ($or->codBearer == 'merchant') {
             $cod = 0;
         }
         $codclass = '';
         if ($or->deliveryType == 'COD' || $or->deliveryType == 'CCOD') {
             $chg = $gt - $dsc + $tax + $dc + $cod;
         } else {
             $dc = 0;
             $cod = 0;
             $chg = $dc;
         }
         $or->totalPrice = strval($payable);
         $or->deliveryCost = strval($dc);
         $or->codCost = strval($cod);
         $or->chargeableAmount = strval($chg);
         $orders[$n] = $or;
         //$norders[] = $or;
     }
     $actor = $key;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'logged out'));
     return $orders;
     //
 }
 public function postAssigndevice()
 {
     $in = Input::get();
     $device = Device::where('key', '=', $in['device'])->first();
     $shipments = Shipment::whereIn('delivery_id', $in['ship_ids'])->get();
     //print_r($shipments->toArray());
     $ts = new MongoDate();
     foreach ($shipments as $sh) {
         $pre = clone $sh;
         $sh->status = Config::get('jayon.trans_status_admin_zoned');
         $sh->device_key = $device->key;
         $sh->device_name = $device->identifier;
         $sh->device_id = $device->_id;
         $sh->save();
         $hdata = array();
         $hdata['historyTimestamp'] = $ts;
         $hdata['historyAction'] = 'assign_device';
         $hdata['historySequence'] = 1;
         $hdata['historyObjectType'] = 'shipment';
         $hdata['historyObject'] = $sh->toArray();
         $hdata['actor'] = Auth::user()->fullname;
         $hdata['actor_id'] = Auth::user()->_id;
         History::insert($hdata);
         $sdata = array();
         $sdata['timestamp'] = $ts;
         $sdata['action'] = 'assign_device';
         $sdata['reason'] = 'initial';
         $sdata['objectType'] = 'shipment';
         $sdata['object'] = $sh->toArray();
         $sdata['preObject'] = $pre->toArray();
         $sdata['actor'] = Auth::user()->fullname;
         $sdata['actor_id'] = Auth::user()->_id;
         Shipmentlog::insert($sdata);
     }
     return Response::json(array('result' => 'OK', 'shipment' => $shipments));
 }
Example #17
0
 /**
  * Store a newly created resource in storage.
  * POST posts/{id}/comments
  *
  * @param int $id
  * @return Response
  */
 public function store($id)
 {
     $user = Auth::user();
     //		$validator = Comment::validate(Input::all());
     //
     //		if ($validator->fails())
     //			return $this->respondInsufficientPrivileges($validator->messages()->all());
     if (Input::get('text') == '' & !Input::has('attachments')) {
         return $this->respondInsufficientPrivileges('Send some text');
     }
     if (strlen(Input::get('text')) > 2500) {
         return $this->respondInsufficientPrivileges('Слишком длинный текст');
     }
     $post = Post::find($id);
     if (!$post) {
         return $this->respondNotFound('Post not found');
     }
     $comment = new Comment(Input::all());
     $comment->user()->associate(Auth::user());
     $category = $post->category;
     if ($category && $post->comments()->save($comment)) {
         if ($post->user_id != $comment->user_id && ($device = Device::where('user_id', $comment->user_id)->first())) {
             $token = $device->auth_token;
             $state = new StateSender($token);
             $state->setPostAsCommented($post, $comment, Auth::user());
         }
         //			$category->updateCount('comments');
         if (Input::has('attachments')) {
             $attachments = Input::get('attachments');
             foreach ($attachments as $attachment) {
                 $carHelper = new Helpers\carHelper();
                 if ($attachment['type'] == 'Geo') {
                     $geo = Geo::create(['long' => $attachment['long'], 'lat' => $attachment['lat'], 'location' => $attachment['location']]);
                     $comment->geos()->save($geo);
                 }
                 if ($attachment['type'] == 'Car') {
                     $car = $carHelper::fetchCar($user, $attachment['id']);
                     if ($car) {
                         $comment->cars()->attach($car->id);
                     }
                 }
                 if ($attachment['type'] == 'CarNumber') {
                     $car = $carHelper::fetchCar($user, $attachment['id']);
                     if ($car) {
                         $comment->carsWithNumbers()->attach($car->id);
                     }
                 }
                 if ($attachment['type'] == 'Image') {
                     $image = Image::find($attachment['id']);
                     if ($image) {
                         $comment->images()->save($image);
                     }
                 }
             }
         }
         $comment->load('cars', 'geos', 'images');
         return $this->respond($this->collectionTransformer->transformComment($comment));
     }
     return $this->respondServerError();
 }
Example #18
0
 public static function getDevice($key = null, $val = null)
 {
     if (is_null($key)) {
         $c = Device::get();
         self::$device = $c;
         return new self();
     } else {
         $c = Device::where($key, '=', $val)->first();
         self::$device = $c;
         return $c;
     }
 }
Example #19
0
 public function send()
 {
     $this->data['new']['chats'] = array_values(array_unique($this->data['new']['chats']));
     $this->data['new']['posts'] = array_values(array_unique($this->data['new']['posts']));
     $this->data['new']['comments'] = array_values(array_unique($this->data['new']['comments']));
     $this->data['new']['carChats'] = array_values(array_unique($this->data['new']['carChats']));
     $this->data['new']['emergencies'] = array_values(array_unique($this->data['new']['emergencies']));
     if (isset($this->data['posts'])) {
         $posts = array();
         foreach ($this->data['posts'] as $post) {
             if (isset($post['comments'])) {
                 $comments = array();
                 foreach ($post['comments'] as $comment) {
                     $comments[] = $comment;
                 }
                 $post['comments'] = $comments;
             }
             $posts[] = $post;
         }
         $this->data['posts'] = $posts;
     }
     if (isset($this->data['comments'])) {
         $comments = array();
         foreach ($this->data['commented'] as $comment) {
             $comments[] = $comment;
         }
         $this->data['comments'] = $comments;
     }
     $this->redis->set($this->token, json_encode(array('new' => $this->data['new'])));
     $json = json_encode($this->data);
     $this->redis->publish($this->token, $json);
     $device = Device::where('auth_token', $this->token)->first();
     $pushToken = PushToken::find((int) $device->id);
     if ($pushToken) {
         Push::send($pushToken->platform, $pushToken->token, $json);
     }
     return $this;
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function postNote()
 {
     $key = \Input::get('key');
     //$user = \Apiauth::user($key);
     $user = \Device::where('key', '=', $key)->first();
     if (!$user) {
         $actor = 'no id : no name';
         \Event::fire('log.api', array($this->controller_name, 'post', $actor, 'device not found, upload image failed'));
         return \Response::json(array('status' => 'ERR:NODEVICE', 'timestamp' => time(), 'message' => 'Device Unregistered'));
     }
     $json = \Input::all();
     $batch = \Input::get('batch');
     $result = array();
     foreach ($json as $j) {
         if (isset($j['logId'])) {
             if (isset($j['datetimestamp'])) {
                 $j['mtimestamp'] = new \MongoDate(strtotime($j['datetimestamp']));
             }
             $log = \Deliverynote::where('logId', $j['logId'])->first();
             if ($log) {
                 $result[] = array('status' => 'OK', 'timestamp' => time(), 'message' => $j['logId']);
             } else {
                 \Deliverynote::insert($j);
                 $result[] = array('status' => 'OK', 'timestamp' => time(), 'message' => $j['logId']);
             }
         }
     }
     //print_r($result);
     //die();
     $actor = $user->identifier . ' : ' . $user->devname;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'sync note'));
     return Response::json($result);
 }
Example #21
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function postNote()
 {
     date_default_timezone_set('Asia/Jakarta');
     $key = \Input::get('key');
     $appname = \Input::has('app') ? \Input::get('app') : 'app.name';
     //$user = \Apiauth::user($key);
     $user = \Device::where('key', '=', $key)->first();
     if (!$user) {
         $actor = 'no id : no name';
         \Event::fire('log.api', array($this->controller_name, 'post', $actor, 'device not found, upload image failed'));
         return \Response::json(array('status' => 'ERR:NODEVICE', 'timestamp' => time(), 'message' => $image_id));
     }
     $json = \Input::all();
     $batch = \Input::get('batch');
     $result = array();
     foreach ($json as $j) {
         if (isset($j['logId'])) {
             $j['appname'] = $appname;
             if (isset($j['datetimestamp'])) {
                 $j['mtimestamp'] = new \MongoDate(strtotime($j['datetimestamp']));
             }
             $log = \Deliverynote::where('logId', $j['logId'])->first();
             if ($log) {
                 $result[] = array('status' => 'OK', 'timestamp' => time(), 'message' => $j['logId']);
             } else {
                 \Deliverynote::insert($j);
                 $result[] = array('status' => 'OK', 'timestamp' => time(), 'message' => $j['logId']);
             }
             $pending = \Deliverynote::where('deliveryId', '=', $j['deliveryId'])->where('status', '=', 'pending')->count();
             if ($pending > 0) {
                 $ord = \Shipment::where('delivery_id', '=', $j['deliveryId'])->first();
                 $ord->pending_count = $pending;
                 $ord->save();
             }
         }
     }
     //print_r($result);
     //die();
     $actor = $user->identifier . ' : ' . $user->devname;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'sync note'));
     return Response::json($result);
 }
Example #22
0
 /**
  * @return \Illuminate\Http\JsonResponse
  */
 public function auth()
 {
     //TODO rate limit
     //TODO Validation
     $udid = Input::get('udid');
     $phone = Input::get('phone');
     if (strlen($phone) < 9) {
         return $this->respondInsufficientPrivileges('Номер телефона слишком короткий');
     }
     if (intval($phone[2]) == 0) {
         return $this->respondInsufficientPrivileges('Вы пытаетесь зарегистрировать несуществующий номер.');
     }
     $providerCode = intval($phone[0] . $phone[1]);
     if (!in_array($providerCode, [99, 50, 51, 55, 70, 77])) {
         return $this->respondInsufficientPrivileges('Таких операторов не существует.');
     }
     $type = Input::has('type') ? Input::get('type') : 'verify';
     $phoneModel = Phone::withTrashed()->where('number', $phone)->first();
     if ($phoneModel && $type != 'reset') {
         if (!$phoneModel->deleted_at) {
             return $this->respondInsufficientPrivileges("Номер занят");
         }
         if (Carbon::now()->lte(Carbon::parse($phoneModel->deleted_at)->addDays(30))) {
             $allowedTime = Carbon::parse($phoneModel->deleted_at)->addDays(30);
             return $this->respondInsufficientPrivileges("Данный номер телефона не доступен для регистрации до {$allowedTime}");
         }
     }
     if ($type == 'changePhone') {
         if ($phoneModel) {
             return $this->respondInsufficientPrivileges("Number is already occupied");
         }
         $header = Request::header('Authorization');
         if (is_null($header)) {
             return $this->respondInvalidApi('Unauthorized');
         }
         if (!isset(explode(' ', $header)[1])) {
             return $this->respondInvalidApi('Unauthorized');
         }
         $token = explode(' ', $header)[1];
         if ($token) {
             $device = Device::where('auth_token', $token)->orderBy('id', 'desc')->first();
             $user = $device->user;
             if (!$user->checkPasswordAttribute(Input::get('password'))) {
                 return $this->respondInsufficientPrivileges('Wrong password');
             }
         }
     }
     if (!$phoneModel && $type == 'reset') {
         return $this->respondInsufficientPrivileges('Number not found');
     }
     $tempSMS = SMS::where('device', $udid)->where('phone', $phone)->orderBy('id')->first();
     if ($tempSMS) {
         $minTime = Carbon::parse($tempSMS->sent_at)->addMinutes(3);
         $maxTime = Carbon::parse($tempSMS->sent_at)->addHour();
         if ($tempSMS->verified) {
             if (Carbon::now()->lte($maxTime)) {
                 return $this->respond(['status' => 3, 'token' => $tempSMS->token]);
             }
         }
         if (Carbon::now()->lte($minTime)) {
             return $this->respond(['message' => 'Please wait ' . Carbon::now()->diffInSeconds($minTime) . ' seconds', 'timeout' => Carbon::now()->diffInSeconds($minTime), 'token' => $tempSMS->token, 'status' => 2]);
         }
         $tempSMS->code = rand(1000, 10000);
         $tempSMS->sent_at = Carbon::now()->toDateTimeString();
         // TODO Send sms
         $smsSender = new smsSender(fetchNumber($phone), $tempSMS->code);
         $smsSender->send(function ($res) {
             //				dd($res->xml());
         });
         $tempSMS->save();
         return $this->respond(['timeout' => 180, 'token' => $tempSMS->token, 'status' => 2]);
     } else {
         $code = rand(1000, 10000);
         $newSMSEntry = SMS::create(['phone' => $phone, 'code' => $code, 'token' => base64_encode(openssl_random_pseudo_bytes(32)), 'device' => $udid, 'sent_at' => Carbon::now()->toDateTimeString()]);
     }
     //TODO Send an SMS
     $smsSender = new smsSender(fetchNumber($phone), $code);
     $smsSender->send(function ($res) {
         //			dd($res->xml());
     });
     //SMS Logic
     if (isset($newSMSEntry)) {
         return $this->respond(['timeout' => 180, 'token' => $newSMSEntry->token, 'status' => 2]);
     }
     return $this->respondServerError('Something went wrong');
 }
Example #23
0
 public function getTokens()
 {
     $tokens = array();
     if (isset($this->id) && (int) $this->id > 0) {
         Device::where('user_id', $this->id)->get()->each(function ($device) use(&$tokens) {
             $tokens[] = $device->auth_token;
         });
     }
     return $tokens;
 }
 public function postShipmentlist()
 {
     $in = Input::get();
     $currentdate = $in['currentdate'];
     $pick_up_date = new MongoDate(strtotime($currentdate));
     $shipments = Shipment::where('device_key', '=', $in['device'])->where('pick_up_date', '=', $pick_up_date)->get();
     $shipments = $shipments->toArray();
     $caps = array();
     for ($i = 0; $i < count($shipments); $i++) {
         $pick_up_date = $shipments[$i]['pick_up_date'];
         $shipments[$i]['pick_up_date'] = date('Y-m-d', $shipments[$i]['pick_up_date']->sec);
         $city = $shipments[$i]['consignee_olshop_city'];
         $devices = Device::where('city', 'regex', new MongoRegex('/' . $city . '/i'))->get();
         foreach ($devices as $d) {
             $caps[$d->key]['identifier'] = $d->identifier;
             $caps[$d->key]['key'] = $d->key;
             $caps[$d->key]['city'] = $d->city;
             $caps[$d->key]['count'] = Shipment::where('device_key', $d->key)->where('pick_up_date', $pick_up_date)->count();
         }
     }
     return Response::json(array('result' => 'OK', 'shipment' => $shipments, 'device' => $caps));
     //print_r($caps);
 }
Example #25
0
        return Response::json(array('status' => 'Unauthorized'));
    }
});
Route::filter('auth', function () {
    if (Auth::onceBasic()) {
        return Response::json(['error' => ['message' => 'Invalid credentials', 'status_code' => 401]], 401);
    }
});
Route::filter('bearer', function () {
    $header = Request::header('Authorization');
    if (!$header) {
        return Response::json(['error' => ['message' => 'Unauthorized', 'status_code' => 401]], 401);
    }
    $token = explode(' ', $header)[1];
    if ($token) {
        $device = Device::where('auth_token', $token)->orderBy('id', 'desc')->first();
        if (!is_null($device)) {
            try {
                Auth::onceUsingId($device->user_id);
            } catch (Exception $e) {
                return Response::json(['error' => ['message' => $e->getMessage(), 'status_code' => 500]], 500);
            }
        } else {
            return Response::json(['error' => ['message' => 'Invalid token', 'status_code' => 401]], 401);
        }
    } else {
        return Response::json(['error' => ['message' => 'Unauthorized', 'status_code' => 401]], 401);
    }
    // TODO User is online logic
});
/*
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function postFile()
 {
     $key = Input::get('key');
     //$user = \Apiauth::user($key);
     $user = \Device::where('key', '=', $key)->first();
     if (!$user) {
         $actor = 'no id : no name';
         \Event::fire('log.api', array($this->controller_name, 'post', $actor, 'device not found, upload image failed'));
         return \Response::json(array('status' => 'ERR:NODEVICE', 'timestamp' => time(), 'message' => $image_id));
     }
     $parent_id = Input::get('parid');
     $parent_class = Input::get('parclass');
     $file_id = Input::get('fid');
     $image_id = Input::get('img');
     $ns = Input::get('ns');
     $isSignature = Input::get('signature');
     $lat = Input::get('lat');
     $lon = Input::get('lon');
     if (isset($file_id) && $file_id != '') {
         $rstring = $file_id;
     } else {
         $rstring = str_random(15);
     }
     $result = '';
     //$destinationPath = realpath('storage/media').'/'.$rstring;
     if (Input::hasFile('imagefile')) {
         $file = Input::file('imagefile');
         $destinationPath = realpath('storage/media') . '/' . $rstring;
         $filename = $file->getClientOriginalName();
         $filemime = $file->getMimeType();
         $filesize = $file->getSize();
         $extension = $file->getClientOriginalExtension();
         //if you need extension of the file
         $filename = str_replace(\Config::get('kickstart.invalidchars'), '-', $filename);
         $uploadSuccess = $file->move($destinationPath, $filename);
         $is_image = true;
         $is_audio = false;
         $is_video = false;
         $is_pdf = false;
         $is_doc = false;
         $is_image = $this->isImage($filemime);
         $is_audio = $this->isAudio($filemime);
         $is_video = $this->isVideo($filemime);
         $is_pdf = $this->isPdf($filemime);
         if (!($is_image || $is_audio || $is_video || $is_pdf)) {
             $is_doc = true;
         } else {
             $is_doc = false;
         }
         $exif = array();
         if ($is_image) {
             $ps = \Config::get('picture.sizes');
             $thumbnail = \Image::make($destinationPath . '/' . $filename)->fit($ps['thumbnail']['width'], $ps['thumbnail']['height'])->save($destinationPath . '/th_' . $filename);
             $medium = \Image::make($destinationPath . '/' . $filename)->fit($ps['medium']['width'], $ps['medium']['height'])->save($destinationPath . '/med_' . $filename);
             $large = \Image::make($destinationPath . '/' . $filename)->fit($ps['large']['width'], $ps['large']['height'])->save($destinationPath . '/lrg_' . $filename);
             $full = \Image::make($destinationPath . '/' . $filename)->save($destinationPath . '/full_' . $filename);
             $image_size_array = array('thumbnail_url' => \URL::to('storage/media/' . $rstring . '/' . $ps['thumbnail']['prefix'] . $filename), 'large_url' => \URL::to('storage/media/' . $rstring . '/' . $ps['large']['prefix'] . $filename), 'medium_url' => \URL::to('storage/media/' . $rstring . '/' . $ps['medium']['prefix'] . $filename), 'full_url' => \URL::to('storage/media/' . $rstring . '/' . $ps['full']['prefix'] . $filename));
             $exif = \Image::make($destinationPath . '/' . $filename)->exif();
         } else {
             if ($is_audio) {
                 $thumbnail_url = \URL::to('images/audio.png');
             } elseif ($is_video) {
                 $thumbnail_url = \URL::to('images/video.png');
             } else {
                 $thumbnail_url = \URL::to('images/media.png');
             }
             $image_size_array = array('thumbnail_url' => $thumbnail_url, 'large_url' => '', 'medium_url' => '', 'full_url' => '');
         }
         $item = array('ns' => $ns, 'parent_id' => $parent_id, 'parent_class' => $parent_class, 'url' => \URL::to('storage/media/' . $rstring . '/' . $filename), 'temp_dir' => $destinationPath, 'file_id' => $rstring, 'is_image' => $is_image, 'is_audio' => $is_audio, 'is_video' => $is_video, 'is_signature' => $isSignature, 'is_pdf' => $is_pdf, 'is_doc' => $is_doc, 'latitude' => $lat, 'longitude' => $lon, 'name' => $filename, 'type' => $filemime, 'size' => $filesize, 'deleted' => 0, 'createdDate' => new \MongoDate(), 'lastUpdate' => new \MongoDate());
         foreach ($image_size_array as $k => $v) {
             $item[$k] = $v;
         }
         $item['_id'] = new \MongoId($image_id);
         $im = \Uploaded::find($image_id);
         if ($im) {
             foreach ($item as $k => $v) {
                 if ($k != '_id') {
                     $im->{$k} = $v;
                 }
             }
             $im->save();
         } else {
             \Uploaded::insertGetId($item);
         }
         $actor = $user->identifier . ' : ' . $user->devname;
         \Event::fire('log.api', array($this->controller_name, 'post', $actor, 'upload image'));
         return \Response::json(array('status' => 'OK', 'timestamp' => time(), 'message' => $image_id));
     }
     $actor = $user->identifier . ' : ' . $user->devname;
     \Event::fire('log.api', array($this->controller_name, 'post', $actor, 'upload image failed'));
     return \Response::json(array('status' => 'ERR:NOFILE', 'timestamp' => time(), 'message' => $image_id));
 }
Example #27
0
 public function getDevice()
 {
     $q = Input::get('term');
     $q = '%' . $q . '%';
     $devices = Device::where('identifier', 'like', $q)->get();
     $result = array();
     foreach ($devices as $d) {
         $result[] = array('id' => $d->key, 'value' => $d->identifier, 'name' => $d->identifier, 'label' => $d->identifier . ' ( ' . $d->key . ' )');
     }
     return Response::json($result);
 }
Example #28
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     date_default_timezone_set('Asia/Jakarta');
     $key = Input::get('key');
     $deliverydate = Input::get('date');
     /*
                         ->join('members as m','d.merchant_id=m.id','left')
                         ->where('assignment_date',$indate)
                         ->where('device_id',$dev->id)
                         ->and_()
                         ->group_start()
                             ->where('status',$this->config->item('trans_status_admin_courierassigned'))
                             ->or_()
                             ->group_start()
                                 ->where('status',$this->config->item('trans_status_new'))
                                 ->where('pending_count >', 0)
                             ->group_end()
                         ->group_end()
     */
     $dev = \Device::where('key', '=', $key)->first();
     //print_r($dev);
     $txtab = \Config::get('jayon.incoming_delivery_table');
     /*
     $orders = $this->model->where(function($qz) use($key, $deliverydate){
                 $qz->where('pick_up_date', '=', new \MongoDate( strtotime($deliverydate) ) )
                     ->where('device_key', '=', $key);
             })
             ->where(function($qw){
     
                 $qw->where('bucket','=',\Config::get('jayon.bucket_tracker'))
                     ->orWhere(function($qx){
                             $qx->where('logistic_type','=','internal')
                                 ->where(function($qz){
                                     $qz->where('status','=', \Config::get('jayon.trans_status_admin_courierassigned') )
                                         ->orWhere('status','=', \Config::get('jayon.trans_status_mobile_pickedup') )
                                         ->orWhere('status','=', \Config::get('jayon.trans_status_mobile_enroute') )
                                         ->orWhere(function($qx){
                                             $qx->where('status', \Config::get('jayon.trans_status_new'))
                                                 ->where(\Config::get('jayon.incoming_delivery_table').'.pending_count', '>', 0);
                                         });
                                 });
     
                     });
     
             })
     
             ->orderBy('pick_up_date')
             ->get();
     */
     $orders = $this->model->where('pick_up_date', '=', new \MongoDate(strtotime($deliverydate)))->where('device_key', '=', $key)->where('logistic_type', '=', 'internal')->where(function ($qi) {
         $qi->whereNull('cod')->orWhere('cod', '=', 0);
     })->where(function ($qz) use($key, $deliverydate) {
         $qz->where('status', '=', \Config::get('jayon.trans_status_admin_courierassigned'))->orWhere('status', '=', \Config::get('jayon.trans_status_mobile_pickedup'))->orWhere('status', '=', \Config::get('jayon.trans_status_mobile_enroute'))->orWhere(function ($qx) {
             $qx->where('status', \Config::get('jayon.trans_status_new'))->where('pending_count', '>', 0);
         });
     })->orderBy('pick_up_date')->get();
     $orders = $orders->toArray();
     //print_r($orders->toArray());
     for ($n = 0; $n < count($orders); $n++) {
         $or = new \stdClass();
         foreach ($orders[$n] as $k => $v) {
             if ($k != '_id' && $k != 'id') {
                 $nk = $this->underscoreToCamelCase($k);
             } else {
                 $nk = $k;
             }
             $or->{$nk} = is_null($v) ? '' : $v;
         }
         //print_r($or);
         $or->extId = $or->_id;
         unset($or->_id);
         $or->cod = 0;
         $or->deliveryType = isset($or->deliveryType) && $or->deliveryType > 0 ? $or->deliveryType : 'REG';
         $or->boxList = $this->boxList('delivery_id', $or->deliveryId, $key);
         $or->boxObjects = $this->boxList('delivery_id', $or->deliveryId, $key, true);
         $or->boxCount = $or->numberOfPackage;
         $or->pickUpDate = date('Y-m-d H:i:s', $or->pickUpDate->sec);
         $or->createdDate = date('Y-m-d H:i:s', $or->createdDate->sec);
         $or->lastUpdate = date('Y-m-d H:i:s', $or->lastUpdate->sec);
         $orders[$n] = $or;
     }
     $actor = $key;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'logged out'));
     return $orders;
     //
 }
Example #29
0
 public static function get_device_color($identifier)
 {
     $col = Device::where('identifier', '=', $identifier)->first();
     if ($col) {
         return $col->color;
     } else {
         return '#FF0000';
     }
 }