コード例 #1
1
ファイル: AuthController.php プロジェクト: phelippe/multitest
 /**
  * Create a new authentication controller instance.
  *
  * @return void
  */
 public function __construct(Registrar $registrar)
 {
     //$this->middleware('guest', ['except' => 'getLogout']);
     $this->auth = Auth::admin();
     $this->registrar = $registrar;
     $this->middleware('guest', ['except' => 'getLogout']);
 }
コード例 #2
0
 public static function errors($code = 404, $title = 'Oops! You\'re lost.', $message = '')
 {
     $ajax = Request::ajax();
     if ($code == 404) {
         $title = 'Oops! You\'re lost.';
         $message = 'We can not find the page you\'re looking for.';
         if (!$ajax) {
             $message .= '<br/><a href="' . URL . '/admin">Return home </a>';
         }
     } else {
         if ($code == 403) {
             $title = 'Oops! You are not allowed to go to this page.';
             $message = 'Please check your permission.';
             if (!$ajax) {
                 $message .= '<a href="' . URL . '/admin">
                     Return home </a>';
             }
         } else {
             if (!$code || $code == 500) {
                 $code = 500;
                 if (empty($title)) {
                     $title = 'Internal Server Error';
                 }
                 if (empty($message)) {
                     $message = 'We got problems over here. Please try again later!';
                 }
             }
         }
     }
     if ($ajax) {
         return Response::json(['error' => ['title' => $title, 'message' => $message]], $code);
     }
     return View::make('admin.errors.error')->with(['title' => $title, 'code' => $code, 'message' => $message, 'admin' => Auth::admin()->get(), 'sideMenu' => Menu::getCache(['sidebar' => true]), 'currentTheme' => Cookie::has('theme') ? Cookie::get('theme') : 'default']);
 }
コード例 #3
0
 public function destroy($id)
 {
     Admin::where('id', '=', $id)->delete();
     Activity::log(['contentId' => $id, 'user_id' => Auth::admin()->get()->id, 'contentType' => 'Administrador', 'action' => 'Delete ', 'description' => 'Eliminacion de un administrador', 'details' => 'Usuario: ' . Auth::admin()->get()->name, 'updated' => $id ? true : false]);
     $output['success'] = 'deleted';
     return Response::json($output, 200);
 }
コード例 #4
0
 public function index()
 {
     $arrType = [];
     $arrMenu = Menu::getCache(['active' => 0]);
     if (!empty($arrMenu)) {
         foreach ($arrMenu as $type => $html) {
             if (strpos($type, '-') !== false) {
                 unset($arrMenu[$type]);
                 list($type, $subType) = explode('-', $type);
                 $arrMenu[$type][$subType] = '<ol class="dd-list">' . $html . '</ol>';
                 $arrType[] = $subType;
             } else {
                 $arrMenu[$type] = '<ol class="dd-list">' . $html . '</ol>';
                 $arrType[] = $type;
             }
         }
         arsort($arrMenu);
     } else {
         $arrMenu = [];
     }
     $arrParent = Menu::getCache(['parent' => true]);
     $admin = Auth::admin()->get();
     $permission = new Permission();
     $arrPermission = ['frontend' => ['view' => $permission->can($admin, 'menusfrontend_view_all'), 'create' => $permission->can($admin, 'menusfrontend_create_all'), 'edit' => $permission->can($admin, 'menusfrontend_edit_all'), 'delete' => $permission->can($admin, 'menusfrontend_delete_all')], 'backend' => ['view' => $permission->can($admin, 'menusbackend_view_all'), 'create' => $permission->can($admin, 'menusbackend_create_all'), 'edit' => $permission->can($admin, 'menusbackend_edit_all'), 'delete' => $permission->can($admin, 'menusbackend_delete_all')]];
     $this->layout->title = 'Menu';
     $this->layout->content = View::make('admin.menus-all')->with(['arrMenu' => $arrMenu, 'arrParent' => $arrParent, 'arrType' => $arrType, 'arrPermission' => $arrPermission]);
 }
コード例 #5
0
ファイル: ArticlesController.php プロジェクト: tprifti/Blog
 /**
  * Store a newly created resource in storage.
  * POST /articles
  *
  * @return Response
  */
 public function store()
 {
     $rules = Article::$rules;
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         $messages = $validator->messages();
         // return Response::json(['error' => $messages], 400);
     }
     $image = Input::file('file');
     if (!$image) {
         return Response::json(['error' => $messages], 400);
     } else {
         $admin = Auth::admin();
         $article = new Article();
         $article->admin_id = Auth::admin()->get()->id;
         $article->title = Input::get('title');
         $article->body = Input::get('body');
         $article->category_id = Input::get('category_id');
         $article->save();
         $thumb = new Photo();
         $filename = time() . '-' . $image->getClientOriginalName();
         $destinationPath = public_path('thumbs/' . $filename);
         $a = Image::make($image->getRealPath())->fit(1280, 720)->save($destinationPath, 50);
         // SAVE TO DB
         $thumb->image = 'thumbs/' . $filename;
         $thumb->article_id = $article->id;
         $thumb->save();
     }
 }
コード例 #6
0
    public function index()
    {
        if (!Input::has('page')) {
            $pageNum = 1;
        } else {
            $pageNum = (int) Input::get('page');
        }
        $admin_id = Auth::admin()->get()->id;
        $arrCategories = [];
        $name = '';
        $take = $this->take;
        $skip = floor(($pageNum - 1) * $take);
        $images = VIImage::select('id', 'name', 'short_name', 'description', 'keywords', 'artist', 'model', 'gender', 'age_from', 'age_to', 'number_people', DB::raw('(SELECT COUNT(*)
																							FROM notifications
																				         	WHERE notifications.item_id = images.id
																				         		AND notifications.item_type = "Image"
																								AND notifications.admin_id = ' . $admin_id . '
																								AND notifications.read = 0 ) as new'))->withType('main')->with('categories')->with('collections');
        if (Input::has('categories')) {
            $arrCategories = (array) Input::get('categories');
            $images->whereHas('categories', function ($query) use($arrCategories) {
                $query->whereIn('id', $arrCategories);
            });
        }
        if (Input::has('name')) {
            $name = Input::get('name');
            $nameStr = '*' . $name . '*';
            $images->search($nameStr);
        }
        $images = $images->take($take)->skip($skip)->orderBy('id', 'desc')->get();
        $arrImages = [];
        if (!$images->isempty()) {
            $arrImages = $arrRemoveNew = [];
            foreach ($images as $image) {
                $image->path = URL . '/pic/large-thumb/' . $image->short_name . '-' . $image->id . '.jpg';
                $image->dimension = $image->width . 'x' . $image['height'];
                if ($image->new) {
                    $arrRemoveNew[] = $image->id;
                }
                $arrImages[$image->id] = $image;
                foreach (['arrCategories' => ['name' => 'categories', 'id' => 'id'], 'arrCollections' => ['name' => 'collections', 'id' => 'id']] as $key => $value) {
                    $arr = [];
                    foreach ($image->{$value}['name'] as $v) {
                        $arr[] = $v[$value['id']];
                    }
                    $arrImages[$image->id][$key] = $arr;
                }
                unset($arr);
            }
            if (!empty($arrRemoveNew)) {
                Notification::whereIn('item_id', $arrRemoveNew)->where('item_type', 'Image')->where('admin_id', $admin_id)->update(['read' => 1]);
            }
        }
        if (Request::ajax()) {
            return $arrImages;
        }
        $this->layout->title = 'Images';
        $this->layout->content = View::make('admin.images-all')->with(['images' => $arrImages, 'pageNum' => $pageNum, 'categories' => Category::getSource(), 'name' => $name, 'arrCategories' => $arrCategories, 'collections' => Collection::getSource(), 'apiKey' => Configure::getApiKeys()]);
    }
コード例 #7
0
ファイル: Admin.php プロジェクト: trantung/company
 public static function isSeo()
 {
     if (Auth::admin()->get()->role_id == SEO) {
         return true;
     } else {
         return false;
     }
 }
コード例 #8
0
ファイル: Admin.php プロジェクト: trantung/online_market
 public static function isEditor()
 {
     if (Auth::admin()->get()->role_id == EDITOR) {
         return true;
     } else {
         return false;
     }
 }
コード例 #9
0
 /**
  * Instantiate a new SiteUserController instance.
  */
 public function __construct()
 {
     $this->beforeFilter(function () {
         if (!Auth::admin()) {
             return Redirect::to('/');
         }
     });
 }
コード例 #10
0
ファイル: helpers.php プロジェクト: hlacos/lara-mvcms
function hasPermission($permissionName)
{
    $admin = Auth::admin()->get();
    $permission = Hlacos\LaraMvcms\Models\Permission::where('name', $permissionName)->first();
    if ($admin && $permission) {
        return $admin->hasPermission($permission);
    }
    return false;
}
コード例 #11
0
 public function __construct()
 {
     $this->data['setting'] = Setting::all()->first();
     if (!isset($this->data['setting']) && count($this->data['setting']) == 0) {
         die('Database not uploaded.Please Upload the database');
     }
     if (count($this->data['setting'])) {
     }
     $this->data['loggedAdmin'] = Auth::admin()->get();
     $this->data['pending_applications'] = Attendance::where('application_status', '=', 'pending')->get();
 }
コード例 #12
0
 public function destroy($id)
 {
     if (Request::ajax()) {
         Donacion::destroy($id);
         $output['success'] = 'deleted';
         Activity::log(['contentId' => $id, 'contentType' => 'Donacion', 'user_id' => Auth::admin()->get()->id, 'action' => 'Update', 'description' => 'Eliminacion de Donacion ' . $id, 'details' => 'Usuario: ' . Auth::admin()->get()->name, 'updated' => $id ? true : false]);
         return Response::json($output, 200);
     } else {
         throw new Exception('Wrong request');
     }
 }
コード例 #13
0
 public function index()
 {
     $min_date = '01/01/2015';
     $max_date = date('m/d/Y');
     $data = ['admin_id' => Auth::admin()->get()->id];
     $arrData = [];
     $arrData['notifications'] = ['users' => Notification::getNew('User', $data), 'images' => Notification::getNew('Image', $data), 'orders' => Notification::getNew('Order', $data)];
     $arrData['date'] = ['min_date' => $min_date, 'max_date' => $max_date, 'current_date' => new DateTime(), 'start_date' => new DateTime('7 days ago')];
     $this->layout->title = 'Dashboard';
     $this->layout->content = View::make('admin.dashboard')->with($arrData);
 }
コード例 #14
0
ファイル: AdLoginController.php プロジェクト: jencko/bbk
 public function postUnlock()
 {
     $rules = array('password' => 'required');
     $v = Validator::make(Input::all(), $rules);
     if ($v->fails()) {
         return Redirect::back()->withErrors($v);
     }
     $data = array('email' => Session::get('email'), 'password' => Input::get('password'));
     Auth::admin()->attempt($data);
     if (Auth::admin()->check()) {
         return Redirect::to('admin/dashboard');
     }
     return Redirect::back()->with('failure', 'Invalid Password');
 }
コード例 #15
0
 public static function getNew($type, $data)
 {
     if (!isset($data['admin_id'])) {
         $data['admin_id'] = Auth::admin()->get()->id;
     }
     if (isset($data['get_id'])) {
         $users = self::select('item_id')->where('admin_id', $data['admin_id'])->where('read', 0)->where('item_type', $type)->get();
         $count = $users->count();
         $arrReturn = ['count' => $count, 'id' => []];
         foreach ($users as $user) {
             $arrReturn['id'][] = $user->item_id;
         }
         return $arrReturn;
     }
     return self::where('admin_id', $data['admin_id'])->where('read', 0)->where('item_type', $type)->count();
 }
コード例 #16
0
ファイル: Menu.php プロジェクト: nguyendaivu/imagestock
 public static function getMenu($arr)
 {
     $arrMenu = self::select('id', 'name', 'icon_class', 'link', 'type', 'parent_id', 'group', 'order_no', 'level', 'active');
     if (!isset($arr['active']) || $arr['active']) {
         $arrMenu->where('active', 1);
     }
     $arrMenu = $arrMenu->orderBy('parent_id', 'asc')->orderBy('order_no', 'asc')->orderBy('name', 'asc')->get();
     if ($arrMenu->isEmpty()) {
         return '';
     }
     $arrMenu = self::setMenu($arrMenu->toArray());
     $admin = Auth::admin()->get();
     $permission = new Permission();
     $arrPermission = ['frontend' => ['view' => $permission->can($admin, 'menusfrontend_view_all'), 'edit' => $permission->can($admin, 'menusfrontend_edit_all'), 'delete' => $permission->can($admin, 'menusfrontend_delete_all')], 'backend' => ['view' => $permission->can($admin, 'menusbackend_view_all'), 'edit' => $permission->can($admin, 'menusbackend_edit_all'), 'delete' => $permission->can($admin, 'menusbackend_delete_all')]];
     return self::renderMenu($arrMenu, $arrPermission);
 }
コード例 #17
0
ファイル: OtherAuthenticate.php プロジェクト: marcellorg/auth
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     if (\Auth::admin()->check()) {
         return back();
     }
     if (\Auth::user()->check()) {
         return back();
     }
     if (Auth::other()->guest()) {
         if ($request->ajax()) {
             return response('Unauthorized.', 401);
         } else {
             return redirect()->guest('other/login');
         }
     }
     return $next($request);
 }
コード例 #18
0
ファイル: ProfileController.php プロジェクト: jencko/bbk
 public function postChange()
 {
     $rules = array('old_pass' => 'required', 'new_pass' => 'required', 'cnf_pass' => 'required|same:new_pass');
     $v = Validator::make(Input::all(), $rules);
     if ($v->fails()) {
         return Redirect::to('admin/profile#settings')->withErrors($v);
     }
     $data = Auth::admin()->get();
     $old_password = $data->password;
     if (Hash::check(Input::get('old_pass'), $old_password) == 1) {
         $user_data = User::find($data->id);
         $user_data->password = Hash::make(Input::get('new_pass'));
         $user_data->save();
         return Redirect::to('admin/profile#settings')->with('success2', 'Password Successfully Changed');
     } else {
         return Redirect::to('admin/profile#settings')->with('failure2', 'Old Password is Incorrect');
     }
 }
コード例 #19
0
ファイル: helpers.php プロジェクト: josmel/buen
 function viewcMenu()
 {
     $user = Auth::admin()->user();
     $roles = Role::all();
     foreach ($roles as $value) {
         if ($user->hasRole($value->name)) {
             $dataPermission = Permission::join('permission_role as p', 'permissions.id', '=', 'p.permission_id')->select('permissions.*')->where('p.role_id', '=', $value->id)->get()->toArray();
             foreach ($dataPermission as $value) {
                 if ($user->can($value['name'])) {
                     $menu[] = ['name' => $value['description'], 'modulo' => $value['modulo'], 'controller' => $value['name']];
                 } else {
                     echo "<script language='JavaScript'>history.back(alert('No tienes acceso para esta pagina'));</script>";
                     exit;
                 }
             }
             return $menu;
         }
     }
 }
コード例 #20
0
ファイル: ReportController.php プロジェクト: jencko/bbk
 public function postAddf()
 {
     $input = Input::all();
     $logged_in_data = Auth::admin()->get();
     Session::flash('found', '');
     $rules = array('name' => 'required|alpha_spaces', 'dob' => 'date_format:m/d/Y', 'family_name' => 'alpha_spaces', 'phone_number' => 'numeric', 'police_station_number' => 'numeric', 'enquiry_office_number' => 'numeric', 'found_date' => 'date_format:m/d/Y', 'gender' => 'required');
     $v = Validator::make(Input::all(), $rules);
     if ($v->fails()) {
         return Redirect::back()->withInput(Input::all())->withErrors($v);
     }
     $input = $this->check_images_and_upload($input);
     $input['created_by'] = $logged_in_data->uid;
     $input['dob'] = GlobalFunc::set_date_format(Input::get('dob'));
     $input['found_date'] = GlobalFunc::set_date_format(Input::get('found_date'));
     $uid = strtoupper(Str::random(3)) . '_' . time();
     $input['uid'] = $uid;
     $input['status'] = 1;
     Found::create($input);
     return Redirect::to('admin/found/published')->with('success', 'Record Successfully Inserted');
 }
コード例 #21
0
 /**
  * Update the specified Admin in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function update($id)
 {
     $admin = Admin::findOrFail(Auth::admin()->get()->id);
     //name and email change
     if (Input::get('name')) {
         $validator = Validator::make($data = Input::all(), Admin::$rules);
         if ($validator->fails()) {
             return Redirect::back()->withErrors($validator)->withInput();
         }
         Session::flash('success', 'Nombre y Email Actualizados exitosamente');
     } else {
         $validator = Validator::make($data = Input::all(), Admin::$rules_password);
         if ($validator->fails()) {
             return Redirect::back()->withErrors($validator)->withInput();
         }
         $data['password'] = Hash::make(Input::get('password'));
         Session::flash('success', 'Contraseña cambiada con éxito');
     }
     $admin->update($data);
     return Redirect::route('admin.profile_settings.edit', $id);
 }
コード例 #22
0
ファイル: BaseModel.php プロジェクト: nguyendaivu/imagestock
 public static function boot()
 {
     parent::boot();
     self::creating(function ($model) {
         if (method_exists(new Auth(), 'admin')) {
             $model->created_by = Auth::admin()->get()->id;
             $model->updated_by = Auth::admin()->get()->id;
         }
     });
     self::created(function ($model) {
         $model->afterCreate($model);
     });
     self::updating(function ($model) {
         if (method_exists(new Auth(), 'admin')) {
             $model->updated_by = Auth::admin()->get()->id;
         }
     });
     self::deleting(function ($model) {
         $model->beforeDelete($model);
     });
     self::saved(function ($model) {
         $model->afterSave($model);
     });
 }
コード例 #23
0
ファイル: routes.php プロジェクト: nguyendaivu/imagestock
        $admin['password'] = '******';
    }
    $remember = Input::has('remember');
    if (Auth::admin()->attempt($admin, $remember)) {
        return Redirect::intended('/admin')->with('flash_success', 'Welcome back.<br />You has been login successful!');
    }
    return Redirect::to('/admin/login')->with('flash_error', 'Email / Password is not correct.')->withInput();
}]);
Route::group(['prefix' => '/admin', 'before' => 'auth.admin|csrf|lock'], function () {
    Route::get('/dashboard', ['uses' => 'DashboardsController@index']);
    Route::get('/', ['uses' => 'DashboardsController@index']);
    Route::get('/synchronize', ['uses' => 'AdminController@synchronize']);
    Route::get('/touch', ['uses' => 'AdminController@touch']);
    Route::match(['GET', 'POST'], '/lock', ['as' => 'lock', 'uses' => 'AdminController@lock']);
    Route::get('/logout', ['as' => 'logout', 'uses' => function () {
        Auth::admin()->logout();
        Session::flush();
        return Redirect::to('/admin/login');
    }]);
    /* Dynamic route
     *
     *  controller must be same as controller class without 'Controller' string.
     *  action must be same as method, and should be slug string.
     *   EX: 'pages/show-list' will call PagesController and showList method of PagesController
     *
     */
    Route::match(['GET', 'POST'], '{controller}/{action?}/{args?}', function ($controller, $action = 'index', $args = '') {
        $controller = str_replace('-', ' ', strtolower(preg_replace('/[^A-Za-z0-9\\-]/', '', $controller)));
        $controller = str_replace(' ', '', Str::title($controller));
        $controller = '\\' . $controller . 'Controller';
        if (!class_exists($controller)) {
コード例 #24
0
 public function getLogout()
 {
     Auth::admin()->logout();
     return Redirect::to('/');
 }
コード例 #25
0
 /**
  *
  * Realiza el cierrre de sesión de los usuarios y los envia a la pagina de ingreso
  *
  * @param string $admin
  * @return Response
  */
 public function logout()
 {
     Auth::user()->logout();
     Auth::admin()->logout();
     return Redirect::to('/');
 }
コード例 #26
0
//     '/image/{size}/{file}',
//     'ImageController@getImage'
// );
Route::get('getAll/{site_id}', 'SiteController@getAllCommands');
Route::get('syncServer/{site_id}', 'HomeController@syncServer');
Route::get('remoteToOrigin/{site_id}/{relay_id}/{status}/{rfid}/{access}/{day}/{month}/{year}/{hour}/{min}/{sec}', 'HomeController@remoteToOrigin');
Route::get('closeDoor/{site_id}', 'HomeController@closeDoor');
Route::get('sites', 'HomeController@sites');
Route::get('sites/{rfid}', 'HomeController@sitesForUser');
Route::get('users', 'HomeController@users');
Route::get('zones', 'HomeController@zones');
Route::get('zones/{rfid}', 'HomeController@zonesForUser');
Route::get('relays/{site_id}', 'HomeController@relays');
Route::get('updateSiteRelay/{site_id}/{relay_id}/{status}', 'SiteController@updateSiteRelay');
Route::filter('auth', function () {
    if (Auth::admin()->guest()) {
        return Redirect::guest('/');
    }
});
Route::group(array('before' => 'auth'), function () {
    Route::get('siteZone/{site_id}', 'SiteZoneController@index');
    Route::post('siteZone/update', 'SiteZoneController@update');
    Route::get('siteUser/{site_id}', 'SiteUserController@index');
    Route::post('siteUser/update', 'SiteUserController@update');
    Route::get('zoneSite/{site_id}', 'ZoneSiteController@index');
    Route::post('zoneSite/update', 'ZoneSiteController@update');
    Route::get('zoneUser/{site_id}', 'ZoneUserController@index');
    Route::post('zoneUser/update', 'ZoneUserController@update');
    Route::resource('user', 'UserController');
    Route::post('user/updatePermissions', 'UserController@updatePermissions');
    Route::resource('admin', 'AdminController');
コード例 #27
0
ファイル: filters.php プロジェクト: nguyendaivu/imagestock
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function () {
    $token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
    if ((Request::ajax() || Request::isMethod('post')) && Session::token() !== $token) {
        throw new Illuminate\Session\TokenMismatchException();
    }
});
Route::filter('lock', function () {
    $routeName = Route::currentRouteName();
    $lock = false;
    if (Session::has('lock') && $routeName != 'logout') {
        $lock = true;
    }
    if (Request::ajax() && $routeName == 'lock') {
        $lock = false;
    }
    if ($lock) {
        return View::make('admin.lockscreen')->with(['admin' => Auth::admin()->get()]);
    }
});
Event::listen('auth.login', function ($admin) {
    // if( $admin instanceof Admin ) {
    // 	$admin->previous_login = $admin->last_login;
    // 	$admin->last_login = new DateTime;
    // 	$admin->save();
    // }
});
コード例 #28
0
ファイル: add.php プロジェクト: anchorcms/anchor-cms
<?php

echo $header;
?>

<hgroup class="wrap">
	<h1><?php 
echo __('users.add_user');
?>
</h1>
</hgroup>

<section class="wrap">
	
	<?php 
if (Auth::admin()) {
    ?>

	<form method="post" action="<?php 
    echo Uri::to('admin/users/add');
    ?>
" novalidate autocomplete="off" enctype="multipart/form-data">

		<input name="token" type="hidden" value="<?php 
    echo $token;
    ?>
">

		<fieldset class="half split">
			<p>
				<label for="label-real_name"><?php 
コード例 #29
0
ファイル: edit.php プロジェクト: anchorcms/anchor-cms
			</p>
			<p>
				<label for="label-status"><?php 
    echo __('users.status');
    ?>
:</label>
				<?php 
    echo Form::select('status', $statuses, Input::previous('status', $user->status), array('id' => 'label-status'));
    ?>
				<em><?php 
    echo __('users.status_explain');
    ?>
</em>
			</p>
			<?php 
    if (false && Auth::admin()) {
        ?>
			<p>
				<label for="label-role"><?php 
        echo __('users.role');
        ?>
:</label>
				<?php 
        echo Form::select('role', $roles, Input::previous('role', $user->role), array('id' => 'label-role'));
        ?>
				<em><?php 
        echo __('users.role_explain');
        ?>
</em>
			</p>
			<?php 
コード例 #30
0
    public function listProduct()
    {
        if (!Request::ajax()) {
            return App::abort(404);
        }
        $admin_id = Auth::admin()->get()->id;
        $start = Input::has('start') ? (int) Input::get('start') : 0;
        $length = Input::has('length') ? Input::get('length') : 10;
        $search = Input::has('search') ? Input::get('search') : [];
        $products = Product::with('mainImage')->select(DB::raw('id, name, sku, sell_price, short_description, active,
												(SELECT COUNT(*)
													FROM notifications
										         	WHERE notifications.item_id = products.id
										         		AND notifications.item_type = "Product"
														AND notifications.admin_id = ' . $admin_id . '
														AND notifications.read = 0 ) as new'));
        if (!empty($search)) {
            foreach ($search as $key => $value) {
                if (empty($value)) {
                    continue;
                }
                if ($key == 'active') {
                    if ($value == 'yes') {
                        $value = 1;
                    } else {
                        $value = 0;
                    }
                    $products->where($key, $value);
                } else {
                    if ($key == 'sell_price') {
                        $value = trim($value);
                        if (strpos($value, '-') !== false) {
                            list($from, $to) = explode('-', $value);
                            $products->where($key, '>', (double) $from);
                            $products->where($key, '<', (double) $to);
                        } else {
                            $products->where($key, (double) $value);
                        }
                    } else {
                        if ($key == 'category' && !empty($value)) {
                            if (is_numeric($value)) {
                                $products->whereHas('categories', function ($query) use($value) {
                                    $query->where('categories.id', $value);
                                });
                            } else {
                                if (is_array($value)) {
                                    foreach ($value as $k => $v) {
                                        if (empty($v)) {
                                            unset($value[$k]);
                                        }
                                    }
                                    if (empty($value)) {
                                        continue;
                                    }
                                    $products->whereHas('categories', function ($query) use($value) {
                                        $query->whereIn('categories.id', $value);
                                    });
                                } else {
                                    $products->whereHas('categories', function ($query) use($value) {
                                        $query->where('categories.name', 'like', '%' . $value . '%');
                                    });
                                }
                            }
                        } else {
                            $value = ltrim(rtrim($value));
                            $products->where($key, 'like', '%' . $value . '%');
                        }
                    }
                }
            }
        }
        $order = Input::has('order') ? Input::get('order') : [];
        if (!empty($order)) {
            $columns = Input::has('columns') ? Input::get('columns') : [];
            foreach ($order as $value) {
                $column = $value['column'];
                if (!isset($columns[$column]['name']) || empty($columns[$column]['name'])) {
                    continue;
                }
                $products->orderBy($columns[$column]['name'], $value['dir'] == 'asc' ? 'asc' : 'desc');
            }
        }
        $count = $products->count();
        if ($length > 0) {
            $products = $products->skip($start)->take($length);
        }
        $arrProducts = $products->get();
        $arrReturn = ['draw' => Input::has('draw') ? Input::get('draw') : 1, 'recordsTotal' => Product::count(), 'recordsFiltered' => $count, 'data' => []];
        $arrRemoveNew = [];
        if (!empty($arrProducts)) {
            foreach ($arrProducts as $product) {
                if (isset($product->main_image[0])) {
                    $image = URL . '/' . str_replace('/images/products', '/images/products/thumbs', $product->main_image[0]->path);
                } else {
                    $image = URL . '/assets/images/noimage/110x110.gif';
                }
                $name = $product->name;
                if ($product->new) {
                    $name .= '| <span class="badge badge-danger">new</span>';
                    $arrRemoveNew[] = $product->id;
                }
                if (empty($product->short_description)) {
                    $product->short_description = '(empty)';
                }
                $data = Product::getSmallestPrice($product, true);
                $arrReturn['data'][] = array(++$start, $product->id, $name, $product->sku, "({$data['sizew']}x{$data['sizeh']})|{$data['sell_price']}", $image, $product->short_description, $product->active);
            }
        }
        if (!empty($arrRemoveNew)) {
            Notification::whereIn('item_id', $arrRemoveNew)->where('item_type', 'Product')->where('admin_id', $admin_id)->update(['read' => 1]);
        }
        $response = Response::json($arrReturn);
        $response->header('Content-Type', 'application/json');
        return $response;
    }