Inheritance: extends Illuminate\Support\Facades\Queue
Esempio n. 1
1
function queueGetter($conn, $condition)
{
    try {
        if (empty($condition)) {
            $tsql = "SELECT [id],[Name],[Location] FROM dbo.Queue";
        } else {
            $tsql = "SELECT [id],[Name],[Location] FROM dbo.Queue WHERE {$condition}";
        }
        $conn = OpenConnection();
        $getQueues = sqlsrv_query($conn, $tsql);
        if ($getQueues == FALSE) {
            echo "Error!!<br>";
            die(print_r(sqlsrv_errors(), true));
        }
        while ($row = sqlsrv_fetch_array($getQueues, SQLSRV_FETCH_ASSOC)) {
            $queue = new Queue($row['Name'], $row['Location']);
            $queue->setId($row['id']);
            $queues[] = $queue;
        }
        sqlsrv_free_stmt($getQueues);
        sqlsrv_close($conn);
        if (!empty($queues)) {
            return $queues;
        } else {
            return null;
        }
    } catch (Exception $e) {
        echo "Get Queue Error!";
    }
}
Esempio n. 2
1
 /**
  * @param callable $callback A task to start processing in the background
  * @return Task
  */
 public function async(callable $callback) : Task
 {
     $id = TaskIdFactory::new();
     $task = new Task($this->subscriber, $id);
     $this->queue->push($id, $callback);
     return $task;
 }
Esempio n. 3
0
 /**
  * @param int $limit
  */
 public function actionIndex($limit = 5)
 {
     $limit = (int) $limit;
     $this->log("Try process {$limit} mail tasks...");
     $queue = new Queue();
     $models = $queue->getTasksForWorker(self::MAIL_WORKER_ID, $limit);
     $this->log("Find " . count($models) . " new mail task");
     foreach ($models as $model) {
         $this->log("Process mail task id = {$model->id}");
         $data = $model->decodeJson();
         if (!$data) {
             $model->completeWithError('Error json_decode', CLogger::LEVEL_ERROR);
             $this->log("Error json_decode");
             continue;
         }
         if (!isset($data['from'], $data['to'], $data['theme'], $data['body'])) {
             $model->completeWithError('Wrong data...');
             $this->log('Wrong data...', CLogger::LEVEL_ERROR);
             continue;
         }
         $from = $this->from ? $this->from : $data['from'];
         $replyTo = isset($data['replyTo']) ? $data['replyTo'] : [];
         $sender = Yii::app()->getComponent($this->sender);
         if ($sender->send($from, $data['to'], $data['theme'], $data['body'], false, $replyTo)) {
             $model->complete();
             $this->log("Success send mail");
             continue;
         }
         $this->log('Error sending email', CLogger::LEVEL_ERROR);
     }
 }
 /**
  * Converts the response in JSON format to the value object i.e Queue
  *
  * @param json
  *            - response in JSON format
  *
  * @return Queue object filled with json data
  *
  */
 function buildResponse($json)
 {
     $queuesJSONObj = $this->getServiceJSONObject("queues", $json);
     $queueJSONObj = $queuesJSONObj->__get("queue");
     $queue = new Queue();
     $queue->setStrResponse($json);
     $queue->setResponseSuccess($this->isRespponseSuccess($json));
     $this->buildObjectFromJSONTree($queue, $queueJSONObj);
     if (!$queueJSONObj->has("messages")) {
         return $queue;
     }
     if (!$queueJSONObj->__get("messages")->has("message")) {
         return $queue;
     }
     if ($queueJSONObj->__get("messages")->__get("message") instanceof JSONObject) {
         // Single Entry
         $messageObj = new QueueMessage($queue);
         $this->buildObjectFromJSONTree($messageObj, $queueJSONObj->__get("messages")->__get("message"));
     } else {
         // Multiple Entry
         $messagesJSONArray = $queueJSONObj->getJSONObject("messages")->getJSONArray("message");
         for ($i = 0; $i < count($messagesJSONArray); $i++) {
             $messageJSONObj = $messagesJSONArray[$i];
             $messageObj = new QueueMessage($queue);
             $messageJSONObj = new JSONObject($messageJSONObj);
             $this->buildObjectFromJSONTree($messageObj, $messageJSONObj);
         }
     }
     return $queue;
 }
 public static function work(&$controllerContext, &$viewContext)
 {
     $queue = new Queue(Config::$userQueuePath);
     $queueItem = new QueueItem(strtolower($controllerContext->userName));
     $j['user'] = $controllerContext->userName;
     $j['pos'] = $queue->seek($queueItem);
     $viewContext->layoutName = 'layout-json';
     $viewContext->json = $j;
 }
Esempio n. 6
0
 public function testConsumeViaQueue()
 {
     $this->markTestSkipped('Consuming via queue does not work');
     $this->consumerTopic->consumeQueueStart(self::PARTITION, RD_KAFKA_OFFSET_BEGINNING, $this->queue);
     $this->consumerTopic->consume(self::PARTITION, 100);
     $this->consumerTopic->consumeStop(self::PARTITION);
     $message = $this->queue->consume(200);
     $this->assertInstanceOf(Message::class, $message);
 }
Esempio n. 7
0
function getMqsLength($queuename)
{
    include SERVER_ROOT . "libs/alimqs.class.php";
    $QueueObj = new Queue('84KTqRKsyBIYnVJt', 'u72cpnMTt2mykMMluafimbhv5QD3uC', 'crok2mdpqp', 'mqs-cn-hangzhou.aliyuncs.com');
    $info = $QueueObj->Getqueueattributes($queuename);
    if ($info['state'] == 'ok') {
        return $info['msg']['ActiveMessages'];
    }
    return false;
}
Esempio n. 8
0
 /**
  * Constructor
  *
  * @param string $worker function name
  * @param mixed $chanData
  */
 public function __construct($worker, $chanData = null)
 {
     if ($chanData && is_array($chanData)) {
         foreach ($chanData as $chanId => $jobs) {
             $Q = new Queue($worker);
             $Q->addJobs($jobs);
             $this->chan[$chanId] = $Q;
         }
     }
 }
Esempio n. 9
0
 public static function preWork(&$controllerContext, &$viewContext)
 {
     $controllerContext->cache->setPrefix($controllerContext->userName);
     if (BanHelper::getUserBanState($controllerContext->userName) == BanHelper::USER_BAN_TOTAL) {
         $controllerContext->cache->bypass(true);
         $viewContext->userName = $controllerContext->userName;
         $viewContext->viewName = 'error-user-blocked';
         $viewContext->meta->title = 'User blocked &#8212; ' . Config::$title;
         return;
     }
     $module = $controllerContext->module;
     HttpHeadersHelper::setCurrentHeader('Content-Type', $module::getContentType());
     $viewContext->media = $controllerContext->media;
     $viewContext->module = $controllerContext->module;
     $viewContext->meta->noIndex = true;
     $viewContext->contentType = $module::getContentType();
     if ($viewContext->contentType != 'text/html') {
         $viewContext->layoutName = 'layout-raw';
     }
     Database::selectUser($controllerContext->userName);
     $user = R::findOne('user', 'LOWER(name) = LOWER(?)', [$controllerContext->userName]);
     if (empty($user)) {
         if (!isset($_GET['referral']) || $_GET['referral'] !== 'search') {
             $controllerContext->cache->bypass(true);
             $viewContext->userName = $controllerContext->userName;
             $viewContext->viewName = 'error-user-not-found';
             $viewContext->meta->title = 'User not found &#8212; ' . Config::$title;
             return;
         }
         $queue = new Queue(Config::$userQueuePath);
         $queueItem = new QueueItem(strtolower($controllerContext->userName));
         $queue->enqueue($queueItem);
         $viewContext->queuePosition = $queue->seek($queueItem);
         $controllerContext->cache->bypass(true);
         //try to load cache, if it exists
         $url = $controllerContext->url;
         if ($controllerContext->cache->exists($url)) {
             $controllerContext->cache->load($url);
             flush();
             $viewContext->layoutName = null;
             $viewContext->viewName = null;
             return;
         }
         $viewContext->userName = $controllerContext->userName;
         $viewContext->viewName = 'error-user-enqueued';
         $viewContext->meta->title = 'User enqueued &#8212; ' . Config::$title;
         return;
     }
     $viewContext->user = $user;
     $viewContext->meta->styles[] = '/media/css/menu.css';
     $viewContext->updateWait = Config::$userQueueMinWait;
     $module = $controllerContext->module;
     $module::preWork($controllerContext, $viewContext);
 }
Esempio n. 10
0
 /**
  * @dataProvider providerAddItemsEmpty
  */
 public function testAddItemEmpty($invalidItem = null)
 {
     $queue = new Queue($this->redis, 'test');
     $queue->addItem(1);
     try {
         $queue->addItem($invalidItem);
         $this->fail('Expected \\PhpRQ\\Exception\\InvalidArgument to be thrown');
     } catch (Exception\InvalidArgument $e) {
     }
     $this->assertSame(['1'], $this->redis->lrange('test', 0, 5));
     $this->assertKeys(['test']);
 }
Esempio n. 11
0
function load_view($id)
{
    global $cp;
    $objQueue = new Queue();
    $objQueue->setUid($id);
    if ($objQueue->load()) {
        $cp->set_data(nl2br($objQueue->getBbs('description')));
    } else {
        $cp->set_data('item not found!');
    }
    return;
}
Esempio n. 12
0
 /**
  * Index action.
  * Processes message queue in endless loop.
  */
 public function actionIndex()
 {
     $this->log(get_class($this) . ' have been started.', CLogger::LEVEL_WARNING, 'command');
     while ($this->loop()) {
         try {
             $this->queue->process();
         } catch (Exception $e) {
             $this->log(get_class($e) . ': ' . $e->getMessage(), CLogger::LEVEL_ERROR, 'command');
             $this->terminate();
         }
     }
     $this->log(get_class($this) . ' have been finished.', CLogger::LEVEL_WARNING, 'command');
 }
Esempio n. 13
0
 public function enqueueOnce(Job $job, $trackStatus = false)
 {
     $queue = new Queue($job->queue);
     $jobs = $queue->getJobs();
     foreach ($jobs as $j) {
         if ($j->job->payload['class'] == get_class($job)) {
             if (count(array_intersect($j->args, $job->args)) == count($job->args)) {
                 return $trackStatus ? $j->job->payload['id'] : null;
             }
         }
     }
     return $this->enqueue($job, $trackStatus);
 }
 public static function work(&$controllerContext, &$viewContext)
 {
     $queue = new Queue(Config::$userQueuePath);
     $queueItem = new QueueItem(strtolower($controllerContext->userName));
     $user = R::findOne('user', 'LOWER(name) = LOWER(?)', [$controllerContext->userName]);
     $profileAge = time() - strtotime($user->processed);
     $banned = BanHelper::getUserBanState($controllerContext->userName) != BanHelper::USER_BAN_NONE;
     if ($profileAge > Config::$userQueueMinWait and !$banned && Config::$enqueueEnabled) {
         $queue->enqueue($queueItem);
     }
     $j['user'] = $controllerContext->userName;
     $j['pos'] = $queue->seek($queueItem);
     $viewContext->layoutName = 'layout-json';
     $viewContext->json = $j;
 }
 public function byQueue($qid)
 {
     if (is_array($qid)) {
         $obj = new Queue($qid);
         $obj->setTimePeriod($this->startEpoch, $this->endEpoch);
         $obj->setAgent($this->agent);
         return $obj;
     } else {
         if (@is_object($this->qobjects[$qid])) {
             return $this->qobjects[$qid];
         } else {
             return false;
         }
     }
 }
Esempio n. 16
0
 /**
  * 
  * @param string $type
  * @param string $description
  * @param string $function
  * @param array $args
  * @param int $priority
  * @return type
  */
 static function addToQueque($type, $description, $function, $args, $priority = 0)
 {
     $queue = new Queue();
     $queue->setCreatedAt(time());
     $queue->setStatus(self::STATUS_QUEUED);
     $queue->setArguments(serialize($args));
     $queue->setFunction($function);
     $queue->setType($type);
     $queue->setDescription($description);
     $queue->setPriority($priority);
     return $queue->save();
 }
Esempio n. 17
0
 public static function addToQueue($queue, $ownerID, $vCode, $api, $scope)
 {
     // Prepare the auth array
     if ($vCode != null) {
         $auth = array('keyID' => $ownerID, 'vCode' => $vCode);
     } else {
         $auth = array();
     }
     // Check the databse if there are jobs outstanding ie. they have the status
     // Queued or Working. If not, we will queue a new job, else just capture the
     // jobID and return that
     $jobID = \SeatQueueInformation::where('ownerID', '=', $ownerID)->where('api', '=', $api)->whereIn('status', array('Queued', 'Working'))->first();
     // Check if the $jobID was found, else, queue a new job
     if (!$jobID) {
         $jobID = \Queue::push($queue, $auth);
         \SeatQueueInformation::create(array('jobID' => $jobID, 'ownerID' => $ownerID, 'api' => $api, 'scope' => $scope, 'status' => 'Queued'));
     } else {
         // To aid in potential capacity debugging, lets write a warning log entry so that a user
         // is able to see that a new job was not submitted
         \Log::warning('A new job was not submitted due a similar one still being outstanding. Details: ' . $jobID, array('src' => __CLASS__));
         // Set the jobID to the ID from the database
         $jobID = $jobID->jobID;
     }
     return $jobID;
 }
 public function boot()
 {
     $this->package('orlissenberg/laravel-zendserver-pushqueue');
     // 1. Need a route to marshal requests.
     \Route::any("/queue/zendserver", function () {
         /** @var ZendJobQueue $connection */
         $connection = \Queue::connection("zendjobqueue");
         $connection->marshal();
     });
     // 2. Add the connector to the Queue facade.
     \Queue::addConnector("zendserver", function () {
         return app()->make("\\Orlissenberg\\Queue\\Connectors\\ZendJobQueueConnector");
     });
     // 3. Add configuration to the app/config/queue.php
     /*
     'zendjob' => [
         'driver' => 'zendserver',
         'options' => [],
         'callback-url' => '/queue/zendserver',
     ],
     */
     // 4. Enable the test route (optional for testing only)
     /*
     \Route::get(
         "/queue/zendtest",
         function () {
             $connection = \Queue::connection("zendjobqueue");
             $connection->push("\\Orlissenberg\\Queue\\Handlers\\TestHandler@handle", ["laravel4" => "rocks"]);
     
             return "Job queued.";
         }
     );
     */
 }
Esempio n. 19
0
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     // message
     $data = array('type' => $this->argument('type'), 'id' => $this->argument('id'), 'date' => $this->argument('date'));
     // add message to queue
     Queue::push("Scraper", $data);
 }
 public function dispatch(Queue $queue)
 {
     $snippets = $this->prepareForDispatch($queue->flush());
     if (count($snippets) > 0) {
         $this->log('Snippets found in the queue, preparing POST request');
         try {
             $payload = array('type' => Phpconsole::TYPE, 'version' => Phpconsole::VERSION, 'snippets' => $snippets);
             $this->client->send($payload);
             $this->log('Request successfully sent to the API endpoint');
         } catch (\Exception $e) {
             $this->log('Request failed. Exception message: ' . $e->getMessage(), true);
         }
     } else {
         $this->log('No snippets found in the queue, dispatcher exits', true);
     }
 }
 public function postEdit($id)
 {
     if (!$this->checkRoute()) {
         return Redirect::route('index');
     }
     $title = 'Edit A Modpack Code - ' . $this->site_name;
     $input = Input::only('name', 'deck', 'description', 'slug');
     $modpacktag = ModpackTag::find($id);
     $messages = ['unique' => 'This modpack tag already exists in the database!'];
     $validator = Validator::make($input, ['name' => 'required|unique:modpack_tags,name,' . $modpacktag->id, 'deck' => 'required'], $messages);
     if ($validator->fails()) {
         return Redirect::action('ModpackTagController@getEdit', [$id])->withErrors($validator)->withInput();
     }
     $modpacktag->name = $input['name'];
     $modpacktag->deck = $input['deck'];
     $modpacktag->description = $input['description'];
     $modpacktag->last_ip = Request::getClientIp();
     if ($input['slug'] == '' || $input['slug'] == $modpacktag->slug) {
         $slug = Str::slug($input['name']);
     } else {
         $slug = $input['slug'];
     }
     $modpacktag->slug = $slug;
     $success = $modpacktag->save();
     if ($success) {
         Cache::tags('modpacks')->flush();
         Queue::push('BuildCache');
         return View::make('tags.modpacks.edit', ['title' => $title, 'success' => true, 'modpacktag' => $modpacktag]);
     }
     return Redirect::action('ModpackTagController@getEdit', [$id])->withErrors(['message' => 'Unable to edit modpack code.'])->withInput();
 }
Esempio n. 22
0
 public function placeNodeInLimbo($node_id, $integration_id)
 {
     $node = Node::find($node_id);
     $node->limbo = true;
     Queue::push('DeployAgentToNode', array('message' => array('node_id' => $node_id, 'integration_id' => $integration_id)));
     $node->save();
 }
Esempio n. 23
0
 public function save($flag = false, $index = true)
 {
     $id = parent::save($flag);
     if ($index) {
         \Queue::create('ExtendPostQueue')->push(array($id, get_called_class()));
     }
 }
Esempio n. 24
0
 /**
  * Store a newly created upload in storage.
  *
  * @return Response
  */
 public function store()
 {
     Upload::setRules('store');
     if (!Upload::canCreate()) {
         return $this->_access_denied();
     }
     $file = Input::file('file');
     $hash = md5(microtime() . time());
     $data = [];
     $data['path'] = public_path() . '/uploads/' . $hash . '/';
     mkdir($data['path']);
     $data['url'] = url('uploads/' . $hash);
     $data['name'] = preg_replace('/[^a-zA-Z0-9_.-]/', '_', $file->getClientOriginalName());
     $data['type'] = $file->getMimeType();
     $data['size'] = $file->getSize();
     $data['uploadable_type'] = Request::header('X-Uploader-Class');
     $data['uploadable_id'] = Request::header('X-Uploader-Id') ? Request::header('X-Uploader-Id') : 0;
     $data['token'] = Request::header('X-CSRF-Token');
     $file->move($data['path'], $data['name']);
     if (property_exists($data['uploadable_type'], 'generate_image_thumbnails')) {
         Queue::push('ThumbnailService', array('path' => $data['path'] . '/' . $data['name']));
     }
     $upload = new Upload();
     $upload->fill($data);
     if (!$upload->save()) {
         return $this->_validation_error($upload);
     }
     if (Request::ajax()) {
         return Response::json($upload, 201);
     }
     return Redirect::back()->with('notification:success', $this->created_message);
 }
Esempio n. 25
0
 function show(Pilot $pilot)
 {
     $active = Flight::with('departure', 'departure.country', 'arrival', 'arrival.country')->whereVatsimId($pilot->vatsim_id)->whereIn('state', array(0, 1, 3, 4))->first();
     $flights = Flight::with('departure', 'departure.country', 'arrival', 'arrival.country')->whereVatsimId($pilot->vatsim_id)->whereState(2)->orderBy('arrival_time', 'desc')->take(15)->get();
     $flightCount = Flight::whereVatsimId($pilot->vatsim_id)->whereState(2)->count();
     $stats = new FlightStat(Flight::whereVatsimId($pilot->vatsim_id));
     if ($pilot->processing == 0) {
         Queue::push('LegacyUpdate', $pilot->vatsim_id, 'legacy');
         $pilot->processing = 2;
         $pilot->save();
     }
     if ($pilot->processing == 2) {
         Messages::success('The data for this pilot is currently being processed. In a couple of minutes, all statistics will be available.')->one();
     }
     $distances = $stats->distances($pilot->distance);
     $citypair = $stats->citypair();
     if ($flights->count() > 0) {
         $durations = $stats->durations($pilot->duration);
         extract($durations);
     }
     // Charts: popular airlines, airports and aircraft
     $airlines = $stats->topAirlines();
     $airports = $stats->topAirports();
     $aircraft = $stats->topAircraft();
     $this->javascript('assets/javascript/jquery.flot.min.js');
     $this->javascript('assets/javascript/jquery.flot.pie.min.js');
     $this->autoRender(compact('pilot', 'flights', 'active', 'distances', 'airlines', 'aircraft', 'airports', 'longest', 'shortest', 'citypair', 'hours', 'minutes'), $pilot->name);
 }
Esempio n. 26
0
 public function fire()
 {
     $hosts = Host::where('state', '!=', 'disabled')->where('cron', '=', 'yes')->get(array('id'));
     foreach ($hosts as $host) {
         Queue::push('BackupController@dailyBackup', array('id' => $host->id));
     }
 }
 public function put($uid)
 {
     $token = Input::get('token');
     $result = $this->contextIO->getConnectToken(null, $token);
     if (!$result) {
         return ['success' => 'false', 'error_message' => 'Failed to retrieve a connect token from context.io'];
     }
     $response = $result->getData();
     $responseJSON = json_encode($response);
     $response = json_decode($responseJSON);
     $data = $response->account;
     $serviceMap = ['imap.googlemail.com' => 'gmail', 'imap-mail.outlook.com:993' => 'outlook'];
     $desired_data = ['email_address' => $data->email_addresses[0], 'mailbox_id' => $data->id, 'service' => isset($serviceMap[$data->sources[0]->server]) ? $serviceMap[$data->sources[0]->server] : 'other'];
     $account = new Mailbox();
     $account->id = $uid;
     $account->mailbox_id = $desired_data['mailbox_id'];
     $account->email_address = $desired_data['email_address'];
     $account->service = $desired_data['service'];
     if (!$account->save()) {
         return ['success' => false, 'error_message' => 'Failed to save account details'];
     }
     // TODO: Start sync process
     // Queue Mailbox crawl
     try {
         Queue::push('ContextIOCrawlerController@dequeue', ['id' => $uid], 'contextio.sync.' . Config::get('queue.postfix'));
     } catch (Exception $e) {
         return ['success' => false, 'error_message' => $e->getMessage()];
     }
     return ['success' => true];
 }
Esempio n. 28
0
 public static function autoLogin($rememberme = true)
 {
     if (isset($_SESSION["userId"])) {
         $userId = $_SESSION["userId"];
         $user = GameUsers::getGameUserById($userId);
         if (!empty($user)) {
             UtilFunctions::storeSessionUser($user, $rememberme);
             return $user;
         }
     }
     if (isset($_COOKIE["auth"]) && false) {
         $cookie = $_COOKIE["auth"];
         $arr = explode('&', $cookie);
         $userName = substr($arr[0], 4);
         $hash = substr($arr[1], 5);
         $user = GameUsers::getGameUserByUserName($userName);
         if (!empty($user)) {
             if ($hash == md5($user->getPassword())) {
                 $user->setLastLoginDate(time());
                 $user->setLoginCount($user->getLoginCount() + 1);
                 $user->updateToDatabase(DBUtils::getConnection());
                 Queue::checkUserFriends($user->userId);
                 UtilFunctions::storeSessionUser($user, $rememberme);
                 return $user;
             } else {
                 UtilFunctions::forgetMe();
             }
         }
     }
     return false;
 }
Esempio n. 29
0
 public function toDBResult()
 {
     foreach ($this->items as $item) {
         $result_id = $item->toDBResult();
         \Queue::push(new \App\Commands\ProcessResult($result_id));
     }
 }
 public function put($uid)
 {
     $this->callbackURL = Input::get('callback');
     $subscription_data = ['code' => Input::get('code'), 'state' => Input::get('state')];
     $authorization_data = [];
     try {
         list($authorization_data['dropbox_access_token'], $authorization_data['dropbox_user_id'], $authorization_data['url_state']) = $this->getWebAuth()->finish($subscription_data);
     } catch (Dropbox\Exception_BadRequest $e) {
         return ['success' => false, 'error_message' => $e->getMessage()];
     }
     assert($authorization_data['url_state'] === null);
     // Store this as a new Dropbox
     try {
         $dropbox = new Dropbox();
         $dropbox->id = $uid;
         $dropbox->dropbox_authorized_id = $authorization_data['dropbox_user_id'];
         $dropbox->dropbox_token = $authorization_data['dropbox_access_token'];
         $dropbox->save();
     } catch (Illuminate\Database\QueryException $e) {
         return ['success' => false, 'error_message' => $e->getMessage()];
     }
     // Queue Dropbox crawl
     try {
         Queue::push('DropboxCrawlerController@dequeue', ['id' => $dropbox->id], $this->sync_queue_id);
     } catch (Exception $e) {
         return ['success' => false, 'error_message' => $e->getMessage()];
     }
     return ['success' => true];
 }