Пример #1
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     // Check not 'sync'
     if (Config::get('queue.default') == "sync") {
         Artisan::call('down');
         $this->info("Application maintenance mode enabled.");
         return;
     }
     // Push job onto queue
     Queue::push(function ($job) {
         // Take Application down.
         Artisan::call('down');
         // Add Log message
         Log::info("Application is down, pausing queue while maintenance happens.");
         // Loop, waiting for app to come back up
         while (App::isDownForMaintenance()) {
             echo ".";
             sleep(5);
         }
         // App is back online, kill worker to restart daemon.
         Log::info("Application is up, rebooting queue.");
         Artisan::call('queue:restart');
         $job->delete();
     });
     // Wait until Maintenance Mode enabled.
     while (!App::isDownForMaintenance()) {
         sleep(1);
     }
     $this->info("Application maintenance mode enabled.");
 }
Пример #2
0
 /**
  * Test adding to the queue.
  */
 public function testQueueAdd()
 {
     Queue::push(function ($job) {
         factory(App\Models\TestEntity::class)->create();
         $job->delete();
     });
     $job = $this->pheanstalk->watch('default')->reserve();
     $data = $job->getData();
     $decoded = json_decode($data);
     $this->assertEquals('IlluminateQueueClosure', $decoded->job);
 }
Пример #3
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(CreateTransactionRequest $request, TransactionController $controller)
 {
     $message_code = 57;
     // initialize with illegal transaction
     // log activity
     try {
         $payer = User::findOrFail($request->payer_id)->with(['primary_account', 'account_status'])->first();
         // get payer and primary a/c information
         $payee = OAuth_clients::with('user')->with('user.account_status')->whereId($request->payee_id)->first();
         session()->flash('flash_message', 'Found Payee/Payer');
     } catch (Exception $e) {
         session()->flash('flash_message', 'Cannot find payee/payer');
         $message_code = 14;
     }
     $activity_id = Queue::push($this->logActivity($payer, $payee, $request->txn_currencyid, $request->amount_in_txn_currency), '', 'activity_log');
     // authenticate Payee account
     if ($request->amount_in_txn_currency > 0) {
         // Check fraud
         $fraud = Queue::push($controller->checkFraud($payer));
         if ($this->checkPayeeAccount($payee->user)) {
             // authenticate and transact for payer
             if (Hash::check($request->password, $payer->password)) {
                 // check payee
                 $message_code = $this->checkPayerAccount($payer, $request);
                 if ($message_code = 0) {
                     session()->flash('flash_message', 'Transaction approved');
                 }
             } else {
                 session()->flash('flash_message', 'Payer Kudotsu account/PIN wrong.');
                 $message_code = 28;
             }
         } else {
             session()->flash('flash_message', 'Payee Kudotsu account not approved');
             $message_code = 20;
         }
         Queue::push($controller->store($message_code, $payer, $payee), '', 'activity_log');
     } else {
         session()->flash('flash_message', $payee . $request->payer_id . $payer);
         //'Invalid Amount or trying to pay yourself');
         $message_code = 13;
     }
     return view('transaction.response');
 }
Пример #4
0
 /**
  * Model save event handler
  *
  * @param Model $model
  */
 public function saved(Model $model)
 {
     if ($model::$__es_enable && $model->shouldIndex()) {
         Queue::push('Iverberk\\Larasearch\\Jobs\\ReindexJob', $this->findAffectedModels($model));
     }
 }
Пример #5
0
<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
/*
|--------------------------------------------------------------------------
| Database Logging
|--------------------------------------------------------------------------
| 1) Add "require app_path().'/errors.php';" to the end of app/start/global.php
| 2) Uncomment the "Application Error Logger" section in app/start/global.php
| 3) Migrate "create_log_table", or create the table manualy
*/
Log::listen(function ($level, $message, $context) {
    // Save the php sapi and date, because the closure needs to be serialized
    $apiName = php_sapi_name();
    $date = new \DateTime();
    Queue::push(function () use($level, $message, $context, $apiName, $date) {
        DB::insert("INSERT INTO log (php_sapi_name, level, message, context, created_at) VALUES (?, ?, ?, ?, ?)", array($apiName, $level, $message, json_encode($context), $date));
    });
});
Пример #6
0
 /**
  * Run on deleted observer.
  *
  * @param  \Illuminate\Database\Eloquent\Model  $entity
  *
  * @return bool
  */
 public function deleted(Model $entity)
 {
     Queue::push(DeleteTenant::class, ['database' => $this->getConnectionName(), 'driver' => $this->getDriverName(), 'id' => $entity->getKey()]);
     return true;
 }
Пример #7
0
 /**
  * Model save event handler
  *
  * @param Model $model
  */
 public function saved(Model $model)
 {
     if ($model::$__es_enable && $model->shouldIndex()) {
         Queue::push('Menthol\\Flexible\\Jobs\\ReindexJob', $this->findAffectedModels($model));
     }
 }
    if (!empty($route_url)) {
        Route::post($route_url, function () {
            $listener_type = Config::get('aftership-laravel::web_hook.listener.type');
            $handler = Config::get('aftership-laravel::web_hook.listener.handler');
            if (empty($listener_type) || empty($handler)) {
                throw new Exception('Listener Configuration is incomplete.');
            }
            if ($listener_type == "event") {
                Event::fire($handler, array('data' => Input::all()));
            } elseif ($listener_type == "queue") {
                $queue_connection = Config::get('aftership-laravel::web_hook.listener.queue_connection');
                $queue_name = Config::get('aftership-laravel::web_hook.listener.queue_name');
                if (empty($queue_connection)) {
                    if (empty($queue_name)) {
                        Queue::push($handler, array('data' => Input::all()));
                    } else {
                        Queue::push($handler, array('data' => Input::all()), $queue_name);
                    }
                } else {
                    if (empty($queue_name)) {
                        Queue::connection($queue_connection)->push($handler, array('data' => Input::all()));
                    } else {
                        Queue::connection($queue_connection)->push($handler, array('data' => Input::all()), $queue_name);
                    }
                }
            }
        });
    } else {
        throw new Exception('Route URL cannot be empty when Webhook is enabled.');
    }
}
Пример #9
0
 public function run($className)
 {
     Queue::push($className, $this);
 }
Пример #10
0
 public function getIndex()
 {
     Queue::push('Test', array('message' => 'ddddd'));
 }
Пример #11
0
 /**
  *  <h1>Описание</h1>
  *  <pre>
  *    Провести авторизацию и выполнить команду
  *  </pre>
  *  <h1>Что возвращает</h1>
  *  <pre>
  *    - JSON-массив:
  *
  *      [
  *        "status"        // Статус результата выполнения команды
  *        "timestamp"     // Timestamp прихода запроса от клиента
  *        "data"          // Данные
  *      ]
  *  </pre>
  *  <h1>Какие статусы бывают, зависимость data от статуса</h1>
  *  <pre>
  *    0   // Команда выполнена успешно. В data результаты её выполненя.
  *    -1  // Нет доступа. В data строка-сообщение об этом.
  *    -2  // Команда завершилась с ошибкой. В data текст ошибки.
  *  </pre>
  *  <h1>Примеры использования</h1>
  *  <pre>
  *
  *    1. Синхронное выполнение
  *
  *      1.1. Простой синхронный запуск
  *        runcommand('\M1\Commands\C1_parseapp');
  *
  *      1.2. С передачей данных
  *        runcommand('\M1\Commands\C1_parseapp', ['key1'=>'value1','key2'=>'value2']);
  *
  *      1.3. С авторизацией по ID текущего пользователя (ID == "15" в примере)
  *        runcommand('\M1\Commands\C1_parseapp', [], 15);
  *
  *    2. Добавление в очередь задач
  *
  *      2.1. Без дополнительной отсрочки выполнения
  *      runcommand('\M1\Commands\C1_parseapp', [], "", ['on'=>true, 'delaysecs'=>'']);
  *
  *      2.2. С дополнительной отсрочкой выполнения в 10 секунд
  *      runcommand('\M1\Commands\C1_parseapp', [], "", ['on'=>true, 'delaysecs'=>'10']);
  *
  *  </pre>
  *
  * @param  mixed $command
  * @param  array $data
  * @param  mixed $userid
  * @param  mixed $queue
  *
  * @return mixed
  */
 function runcommand($command, $data = [], $userid = 0, $queue = ['on' => false, 'delaysecs' => '', 'name' => 'default'])
 {
     // 1. Провести exec-авторизацию, если она включена
     if (config("M5.authorize_exec_ison") == true) {
         // 1.1. Если $userid == -1
         // - Вернуть ответ со статусом -1 (доступ запрещён)
         if ($userid == -1) {
             return ["status" => -1, "data" => $command];
         } else {
             $validator = r4_validate(['userid' => $userid], ["userid" => ["required", "regex:/^[0-9]+\$/ui"]]);
             if ($validator['status'] == -1) {
                 return ["status" => -1, "data" => $command];
             }
         }
         // 1.3. Если $userid !== 0, то провести exec-авторизацию
         if ($userid !== 0) {
             // 1] Извлечь из сессии значение по ключу "authorize_exec"
             $authorize_exec = session('authorize_exec');
             // 2] Провести валидацию $authorize_exec
             $is_authorize_exec_valid = call_user_func(function () use($authorize_exec) {
                 // 2.1] Если $authorize_exec пусто, вернуть false
                 if (empty($authorize_exec)) {
                     return false;
                 }
                 // 2.2] Если $authorize_exec не массив строк, вернуть false
                 $validator = r4_validate(['authorize_exec' => $authorize_exec], ["authorize_exec" => ["required", "array"], "authorize_exec.*" => ["string"]]);
                 if ($validator['status'] == -1) {
                     return false;
                 }
                 // 2.3] Вернуть true
                 return true;
             });
             // 3] Искать $command в $authorize_exec
             // - Если $authorize_exec не пусто и валидно.
             // - Если права нет, вернуть статус -1 (доступ запрещён).
             if ($is_authorize_exec_valid) {
                 if (!in_array($command, $authorize_exec)) {
                     return ["status" => -1, "data" => $command];
                 }
             } else {
                 // 4.1] Получить коллекцию всех команд, которые $userid может выполнять
                 $commands = call_user_func(function () use($userid) {
                     // 4.1.1] Попробовать найти пользователя $userid
                     // - Если найти его не удастся, вернуть пустую коллекцию.
                     $user = \M5\Models\MD1_users::find($userid);
                     if (empty($user)) {
                         return collect([]);
                     }
                     // 4.1.2] Получить коллекцию всех exec-прав, связанных с $user
                     $privileges = call_user_func(function () use($user) {
                         // 1) Состоит ли $user в любой административной группе?
                         $admingroup = \M5\Models\MD2_groups::where('isadmin', 1)->whereHas('users', function ($query) use($user) {
                             $query->where('id', $user->id);
                         })->first();
                         // 2) Если состоит, вернуть все exec-права
                         if (!empty($admingroup)) {
                             return \M5\Models\MD3_privileges::whereHas('privtypes', function ($query) {
                                 $query->where('name', 'exec');
                             })->get();
                         } else {
                             return \M5\Models\MD3_privileges::whereHas('privtypes', function ($query) {
                                 $query->where('name', 'exec');
                             })->where(function ($query) use($user) {
                                 // Права, прямо связанные с пользователем
                                 $query->whereHas('users', function ($query) use($user) {
                                     $query->where('id', $user->id);
                                 });
                                 // Права, связанные с группами, с которыми связан пользователь
                                 $query->orWhereHas('groups', function ($query) use($user) {
                                     $query->whereHas('users', function ($query) use($user) {
                                         $query->where('id', $user->id);
                                     });
                                 });
                                 // Права, связанные с тегами, с которыми связан пользователь
                                 $query->orWhereHas('tags', function ($query) use($user) {
                                     $query->whereHas('users', function ($query) use($user) {
                                         $query->where('id', $user->id);
                                     });
                                 });
                                 // Права, связанные с тегами, связанные с группами, с которыми связан пользователь.
                                 $query->orWhereHas('tags', function ($query) use($user) {
                                     $query->whereHas('groups', function ($query) use($user) {
                                         $query->whereHas('users', function ($query) use($user) {
                                             $query->where('id', $user->id);
                                         });
                                     });
                                 });
                             })->get();
                         }
                     });
                     // 4.1.3] Если у модели MD5_commands в M1 нет связи m5_privileges
                     // - Вернуть пустую коллекцию.
                     if (!r1_rel_exists("m1", "md5_commands", "m5_privileges")) {
                         return collect([]);
                     }
                     // 4.1.4] В противном случае, вернуть коллекцию соотв.команд
                     $commands = r1_query(function () use($privileges) {
                         return \M1\Models\MD5_commands::with(['packages'])->where(function ($query) use($privileges) {
                             $query->whereHas('m5_privileges', function ($query) use($privileges) {
                                 $query->whereIn('id', $privileges->pluck('id'));
                             });
                         })->get();
                     });
                     if (!$commands) {
                         return collect([]);
                     } else {
                         return $commands;
                     }
                 });
                 // 4.2] Превратить $commands в массив полн.квалиф.команд
                 $commands_final = call_user_func(function () use($commands) {
                     // 4.2.1] Если $commands эта пустая коллекция, вернуть пустой массив
                     if (count($commands) == 0) {
                         return [];
                     }
                     // 4.2.2] Подготовить массив для результата
                     $result = [];
                     // 4.2.3] Пробежаться по $commands и наполнить $result
                     $commands->each(function ($item) use(&$result) {
                         array_push($result, "\\" . $item->packages[0]->id_inner . "\\Commands\\" . $item->name);
                     });
                     // 4.2.n] Вернуть результат
                     return $result;
                 });
                 // 4.3] Перезаписать в сессии кэш authorize_exec
                 session(['authorize_exec' => $commands_final]);
                 // 4.4] Если $command не в $commands_final
                 // - Вернуть статус -1 (нет доступа).
                 if (!in_array($command, $commands_final)) {
                     return ["status" => -1, "data" => $command];
                 }
             }
         }
     }
     // 2. Выполнить команду $command
     // - Передав ей данные $data
     // 2.1. Синхронно, если иное не указано в 4-м аргументе runcommand
     if ($queue['on'] == false) {
         $result = Bus::dispatch(new $command($data));
     } else {
         // 1] Без задержки
         if (empty($queue['delaysecs'])) {
             Queue::push(new $command($data), [], $queue['name']);
         } else {
             Queue::later($queue['delaysecs'], new $command($data), [], $queue['name']);
         }
     }
     // 3. Подготовить массив с ответом, и вернуть
     // 3.1. Если команда выполняется синхронно
     if ($queue['on'] == false) {
         $response = ["status" => $result['status'], "data" => $result['data']];
         if (array_key_exists('timestamp', $data)) {
             $response['timestamp'] = $data['timestamp'];
         }
         return $response;
     }
     // 3.2. Если команда выполняется асинхронно
     if ($queue['on'] == true) {
         $response = ["status" => 0, "data" => ""];
         if (array_key_exists('timestamp', $data)) {
             $response['timestamp'] = $data['timestamp'];
         }
         return $response;
     }
 }
Пример #12
0
 /**
  * Push log to queue.
  *
  * @param int    $userId
  * @param string $title
  * @param string $type
  * @param string $data
  * @param string $sql
  *
  * @return string
  */
 public static function create($userId = 0, $title = '', $type = 'S', $object = '', $object_id = 0, $data = '', $sql = '')
 {
     return Queue::push(new UserLogJob(compact('userId', 'title', 'type', 'object', 'object_id', 'data', 'sql')));
 }
Пример #13
0
 public static function enqueue($url, $method, $payload)
 {
     $callback_data = ['callback_url' => $url, 'callback_method' => $method, 'callback_payload_base64' => base64_encode(serialize($payload)), 'callback_timestamp' => time()];
     //Queue::push('QueuedHttp@dequeue', $callback_data, 'queued_http_requests');
     Queue::push('queuedhttpclient@dequeue', $callback_data, 'queued_http_requests');
 }
Пример #14
0
    if (env('ADMIN_PASSWORD', 'admin') !== $inputs['password']) {
        return Util::errorResponse('incorrect password');
    }
    $start2 = json_decode($inputs['data'], true);
    if (Util::exists('api_start2.json')) {
        $data = Util::load('api_start2.json');
        if (Util::compareJson($data, $start2)) {
            return Util::errorResponse('duplicate start2 data');
        }
    }
    Util::dump('api_start2.json', $start2);
    $datetime = new DateTime();
    $today = $datetime->format('YmdH');
    Util::dump("start2/{$today}.json", $start2);
    Queue::push(function ($job) {
        Artisan::call('parse:start2');
        $job->delete();
    });
    return Util::successResponse();
});
$app->get('/start2', function () {
    try {
        $data = Util::read('api_start2.json');
        return response($data)->header('Content-Type', 'application/json');
    } catch (FileNotFoundException $e) {
        return Util::errorResponse('api_start2.json not found in server');
    }
});
$app->get('/start2/archives', function () {
    $files = Storage::disk('local')->files('start2');
    $list = [];
    $matches = [];
Пример #15
0
 private function sendEmail(stdClass $subscriber, array $posts)
 {
     Queue::push(new SendNewsletter($subscriber, $posts));
 }
Пример #16
0
 protected function pushToQueue(array $hit, DocumentPath $from, DocumentPath $to, $queue, $source = false)
 {
     $from = clone $from;
     $to = clone $to;
     $from->type = $this->extractArgument($from->type, $hit['_type']);
     $from->id = $this->extractArgument($from->id, $hit['_id']);
     $to->type = $this->extractArgument($to->type, $hit['_type']);
     $to->id = $this->extractArgument($to->id, $hit['_id']);
     $job = new JobData();
     $job->pathFrom = $from;
     $job->pathTo = $to;
     $job->source = $source ? $hit['_source'] : [];
     $job->parent = array_get($hit, 'fields._parent');
     if (!$job->pathFrom->isValid() || !$job->pathTo->isValid()) {
         throw new InvalidArgumentException('FROM or TO path is not valid');
     }
     Queue::push(Copier::class, $job->toArray(), $queue);
 }
Пример #17
0
 /**
  * Correctly sets the factions name
  * @return this
  */
 private function playerDBLoop($players, $dbPlayers, $type = 'players')
 {
     foreach ($this->data['teams'] as $teamID => $team) {
         if (array_key_exists($type, $team)) {
             foreach ($team[$type] as $index => $player) {
                 if (is_array($player) && array_key_exists('kills', $player) && array_key_exists('deaths', $player)) {
                     $this->data['teams'][$teamID][$type][$index]['kd'] = BattlefieldHelper::kd($player['kills'], $player['deaths']);
                 }
                 foreach ($dbPlayers as $index2 => $player2) {
                     $guid = !is_string($player) ? $player['guid'] : $player;
                     if ($guid == $player2->EAGUID) {
                         if ($type == 'commander') {
                             $index = 0;
                         }
                         if (is_array($player) && array_key_exists('guid', $player)) {
                             Queue::push(function ($job) use($player, $player2) {
                                 // If player rank doesn't match the database update it
                                 if ($player2->GlobalRank != $player['rank']) {
                                     $player2->GlobalRank = $player['rank'];
                                 }
                                 // If player name doesn't match the database update it
                                 if ($player2->SoldierName != $player['name']) {
                                     $player2->SoldierName = $player['name'];
                                 }
                                 // If player name or rank are changed save changes to database
                                 if ($player2->SoldierName != $player['name'] || $player2->GlobalRank != $player['rank']) {
                                     $player2->save();
                                 }
                             });
                         }
                         $this->data['teams'][$teamID][$type][$index]['_player'] = $player2;
                         break;
                     }
                 }
             }
         }
     }
     return $this;
 }