public function __construct()
 {
     $this->dc = new drealtyConnection();
     $this->dm = new drealtyMetaData();
     $this->queue = DrupalQueue::get('drealty');
     $this->queue->deleteQueue();
 }
Example #2
0
function libya_cron()
{
    $queue = DrupalQueue::get('subscription_mail');
    $mails = array();
    $mq = db_query("select * from libya_subscriptions");
    while ($dat = $mq->fetchAssoc()) {
        if ($dat['confirm'] == 1) {
            $mails[] = $dat;
        }
    }
    $yesterday = mktime() - 24 * 3600;
    $nids = array();
    $r = db_query("select node.nid from node\n\twhere type in ('article','page','product')\n\tand status = 1 AND promote = 1\n\tand created > :yesterday", array(":yesterday" => $yesterday));
    while ($obj = $r->fetchObject()) {
        $nids[] = $obj->nid;
    }
    if (count($nids)) {
        foreach ($mails as $mail) {
            $data = array($mail, $nids);
            $queue->createItem($data);
        }
    }
}
Example #3
0
 /**
  * Send an e-mail message, using Drupal variables and default settings.
  *
  * @see http://pear.php.net/package/Mail/docs
  *
  * @param $message
  *   A message array, as described in hook_mail_alter().
  * @return
  *   TRUE if the mail was successfully accepted, otherwise FALSE.
  */
 public function mail(array $message)
 {
     $php_binary = variable_get(CVWOBASE_D7_PHP_BINARY, FALSE);
     // Send asynchronously, and PHP binary path known
     if ($php_binary && variable_get(CVWOBASE_D7_MAIL_SEND_ASYNC, CVWOBASE_D7_MAIL_SEND_ASYNC_DEFAULT)) {
         DrupalQueue::get(CVWOBASE_MAIL_QUEUE)->createItem($message);
         $execstring = $php_binary . ' ' . DRUPAL_ROOT . '/' . drupal_get_path('module', CVWOBASE_MODULE) . '/cvwobase_d7_email_process.php ' . DRUPAL_ROOT;
         cvwobase_exec($execstring);
         return TRUE;
         // Send inline
     } else {
         $error_queue = new MemoryQueue(CVWOBASE_MAIL_ERROR_QUEUE);
         // name irrelevant
         _cvwobase_d7_send_mail($message, $error_queue);
         if ($error_queue->numberOfItems() > 0) {
             while ($error = $error_queue->claimItem()) {
                 drupal_set_message(t('Unable to send message: PEAR Mail reports error "%error"', array('%error' => $error->data)), 'error');
                 $error_queue->deleteItem($item);
             }
             return FALSE;
         }
         return TRUE;
     }
 }
Example #4
0
/**
 * Perform periodic actions.
 *
 * Modules that require some commands to be executed periodically can
 * implement hook_cron(). The engine will then call the hook whenever a cron
 * run happens, as defined by the administrator. Typical tasks managed by
 * hook_cron() are database maintenance, backups, recalculation of settings
 * or parameters, automated mailing, and retrieving remote data.
 *
 * Short-running or non-resource-intensive tasks can be executed directly in
 * the hook_cron() implementation.
 *
 * Long-running tasks and tasks that could time out, such as retrieving remote
 * data, sending email, and intensive file tasks, should use the queue API
 * instead of executing the tasks directly. To do this, first define one or
 * more queues via hook_cron_queue_info(). Then, add items that need to be
 * processed to the defined queues.
 */
function hook_cron()
{
    // Short-running operation example, not using a queue:
    // Delete all expired records since the last cron run.
    $expires = variable_get('mymodule_cron_last_run', REQUEST_TIME);
    db_delete('mymodule_table')->condition('expires', $expires, '>=')->execute();
    variable_set('mymodule_cron_last_run', REQUEST_TIME);
    // Long-running operation example, leveraging a queue:
    // Fetch feeds from other sites.
    $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < :time AND refresh <> :never', array(':time' => REQUEST_TIME, ':never' => AGGREGATOR_CLEAR_NEVER));
    $queue = DrupalQueue::get('aggregator_feeds');
    foreach ($result as $feed) {
        $queue->createItem($feed);
    }
}
Example #5
0
 public function queue($callback, $args = array())
 {
     if (!$this->lock(BACKGROUND_PROCESS_STATUS_QUEUED)) {
         return FALSE;
     }
     $this->callback = $callback;
     $this->args = $args;
     if (!background_process_set_process($this->handle, $this->callback, $this->uid, $this->args, $this->token)) {
         // Could not update process
         return NULL;
     }
     module_invoke_all('background_process_pre_execute', $this->handle, $this->callback, $this->args, $this->token);
     // Initialize progress stats
     $old_db = db_set_active('background_process');
     progress_remove_progress($this->handle);
     db_set_active($old_db);
     $queues = variable_get('background_process_queues', array());
     $queue_name = isset($queues[$this->callback]) ? 'bgp:' . $queues[$this->callback] : 'background_process';
     $queue = DrupalQueue::get($queue_name);
     $queue->createItem(array(rawurlencode($this->handle), rawurlencode($this->token)));
     _background_process_ensure_cleanup($this->handle, TRUE);
 }
Example #6
0
 /**
  * Throttle queues.
  *
  * Enables or disables queue threads depending on remaining items in queue.
  */
 public function throttle($job)
 {
     if (!empty($job->hook['settings']['queue']['master'])) {
         // We always base the threads on the master.
         $master_job = _ultimate_cron_job_load($job->hook['settings']['queue']['master']);
         $settings = $master_job->getSettings('settings');
     } else {
         return;
     }
     if ($settings['queue']['throttle']) {
         $queue = DrupalQueue::get($settings['queue']['name']);
         $items = $queue->numberOfItems();
         $thread = $job->hook['settings']['queue']['thread'];
         $name = $master_job->name . '_' . $thread;
         $status = empty($master_job->disabled) && $items >= ($thread - 1) * $settings['queue']['threshold'];
         $new_status = !$status ? TRUE : FALSE;
         $old_status = ultimate_cron_job_get_status($name) ? TRUE : FALSE;
         if ($old_status !== $new_status) {
             $log_entry = $job->startLog(uniqid($job->name, TRUE), 'throttling', ULTIMATE_CRON_LOG_TYPE_ADMIN);
             $log_entry->log($job->name, 'Job @status by queue throttling (items:@items, boundary:@boundary, threshold:@threshold)', array('@status' => $new_status ? t('disabled') : t('enabled'), '@items' => $items, '@boundary' => ($thread - 1) * $settings['queue']['threshold'], '@threshold' => $settings['queue']['threshold']), WATCHDOG_DEBUG);
             $log_entry->finish();
             $job->dont_log = TRUE;
             $job->setStatus($new_status);
         }
     }
 }
 /**
  * Changes the default branch. Note that this is an async operation.
  *
  * @param $branch_name
  *   The name of the branch that should be checked out by default, when the
  *   repository is closed.
  *
  * @throws Exception
  *   If the branch doesn't exist.
  */
 public function setDefaultBranch($branch_name)
 {
     // Ensure the branch exists.
     if (!$this->loadBranches(NULL, array('name' => $branch_name))) {
         throw new Exception(t('The branch %branch_name doesn\'t exist.', array('%branch_name' => $branch_name)));
     }
     // The job to be queued.
     $job = array('operation' => array('setDefaultBranch' => array($branch_name), 'save' => array()), 'repository' => $this);
     // Queue the write operation on the database an the repository.
     $queue = DrupalQueue::get('versioncontrol_repomgr');
     if (!$queue->createItem($job)) {
         watchdog('versioncontrol_git', t('Failed to enqueue a default branch change for the Git repository at %root.', array('%root' => $this->root)));
         throw new Exception(t('An error occured while attempting to enqueue switching the default branch.'), 'error');
     }
 }
Example #8
0
require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
// We use the queue API to store the impression.
require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
// In my tests, including system.queue.inc directly is a lot faster than
// module_load_include(); this also makes sure that module_implements() does not
// exist, and therefore if watchdog() (or any other function that calls
// module_implements()) is called, the cache of module_implements() is not
// saved.
//require_once DRUPAL_ROOT . '/includes/module.inc';
//module_load_include('inc', 'system', 'system.queue');
// This looks like the cache_backends setting, but it's not in core.
foreach (variable_get('queue_backends', array()) as $include) {
    require_once DRUPAL_ROOT . '/' . $include;
}
if (variable_get('ad_queue_impressions')) {
    $queue = DrupalQueue::get('ad');
    // Using the DB queue backend may still make sense, for sites with a very
    // long full bootstrap.
    if ($queue instanceof SystemQueue) {
        drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
        drupal_add_http_header('X-Ad-bootstrap-phase', 'database');
    }
}
require_once DRUPAL_ROOT . '/' . variable_get('ad_module_path') . '/ad.module';
ad_get_ads();
if (function_exists('xhprof_enable') && $xhprof_enabled) {
    $namespace = 'Site-Install';
    $xhprof_data = xhprof_disable();
    $xhprof_runs = new XHProfRuns_Default();
    $devel_run_id = $xhprof_runs->save_run($xhprof_data, $namespace);
    drupal_add_http_header('X-Ad-xhprof', $devel_run_id);
  2. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// $Id$
/**
 * @file
 * Script to send the queued emails, called directly from the command prompt.
 * Parameter passed in (from command prompt) should be DRUPAL_ROOT.
 * Should also be in the same directory as cvwobase_d7_constants.php and cvwobase_d7_mail_functions.php
 */
require_once 'cvwobase_d7_constants.php';
require_once 'cvwobase_d7_mail_functions.php';
// check for command line arguments
if ($argc != 2 || defined(DRUPAL_ROOT)) {
    die('Invalid arguments');
}
// Load Drupal up to database and system variables
define('DRUPAL_ROOT', $argv[1]);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
$mail_queue = DrupalQueue::get(CVWOBASE_MAIL_QUEUE);
$error_queue = DrupalQueue::get(CVWOBASE_MAIL_ERROR_QUEUE);
// iterate between email batches
while ($item = $mail_queue->claimItem()) {
    $message = $item->data;
    $mail_queue->deleteItem($item);
    _cvwobase_d7_send_mail($message, $error_queue);
}
 function sendQueued($to, $queue = null, $cc = "", $bcc = "", $attachment = array(), $uid = 0)
 {
     if ($queue == null) {
         if ($this->queue_r == null) {
             // generate new queue id if required
             //***$this->queue_r = new CVWOQueue('mail_'.rand(0,999).'_'.rand(0,999).'_'.time());
             $this->queue_r = DrupalQueue::get('mail_' . rand(0, 999) . '_' . rand(0, 999) . '_' . time(), TRUE);
             //
         }
     } else {
         $this->queue_r = $queue;
     }
     $mail_temp = array('content' => $this->getContent(), 'extraHeaders' => $this->getExtraHeaders(), 'to' => $to, 'cc' => $cc, 'bcc' => $bcc, 'attachment' => $attachment, 'by_uid' => $uid);
     //***$this->queue_r->push($mail_temp);
     $this->queue_r->createItem($mail_temp);
     //
     return $this->queue_r;
 }
 /**
  * Queues a git clone entity.
  *
  * @return GitClone
  *   The current GitClone entity instance.
  *
  * @see git_clone_cron_queue_info()
  * @see _git_clone_dequeue_callback()
  * @see GitClone::dequeue()
  *
  * @chainable
  */
 public function queue()
 {
     // Only continue if not already queued and fetch threshold has expired.
     if (!$this->isQueued() && $this->isExpired()) {
         /** @var \DrupalQueueInterface $queue */
         $queue = \DrupalQueue::get(GIT_CLONE_QUEUE, TRUE);
         $queue->createQueue();
         $queue->createItem($this);
         drupal_set_message(t('Queued the "@label" git clone to fetch on next cron run.', array('@label' => $this->label())));
     }
     return $this;
 }
<?php

/**
 * @file
 * os2web_esdh_provider.queue.php
 *
 * Let the meetings importer run via CLI instead of HTTP
 *
 * Run with Drush php-script
 * "drush scr os2web_esdh_provider.queue.php"
 */
require_once 'os2web_esdh_provider.mmapi.inc';
os2web_esdh_provider_queue_meetings();
if (lock_acquire('os2web_esdh_provider_queue', 10000)) {
    $queue = DrupalQueue::get('acadre_mm_import');
    while ($item = $queue->claimItem()) {
        _os2web_esdh_provider_cron_queue_worker($item->data);
        $queue->deleteItem($item);
    }
}
lock_release('os2web_esdh_provider_queue');
Example #13
0
 public static function send_buffer_salida()
 {
     //Vamos a recorrer los conectores activos
     $serversNames = BbiConector::getServerNameActivos();
     foreach ($serversNames as $uid => $serverName) {
         $queue = DrupalQueue::get('bufferSalida' . $serverName);
         $remote = new CodeServer($serverName);
         $remote->config->request_timeout = 20;
         //Tiempo de espera de lectura en segundos, especificado por un float (p.ej. 10.5).Por omisión se utiliza el valor del ajuste default_socket_timeout de php.ini.
         $time = microtime(TRUE);
         watchdog('pruebatiempo', 'inicio total ' . $time);
         $max = (int) BbiConector::getMaxTimeExecution(bbiLab_getUserById($uid));
         while (($item = BbiBuffer::get_item_from_buffer($queue)) && microtime(TRUE) - $time < $max) {
             watchdog('pruebatiempo', 'inicio una prueba ' . (microtime(TRUE) - $time));
             if ($item) {
                 if ($remote->write_element_from_buffer(serialize($item))) {
                     BbiBuffer::remove_item_from_buffer($queue, $item);
                     //Lo ha metido, lo borramos del buffer de salida
                 } else {
                     $item = $item ? $item : 'no hay elemento';
                     BbiBuffer::insert_item_error_buffer($serverName, $item);
                     // Ha fallado lo metemos en el buffer de errores de salida específico.
                 }
             }
         }
     }
 }
Example #14
0
 /**
  * Returns the approximate number of items in the API parse queue.
  */
 function countParseQueue()
 {
     $queue = DrupalQueue::get('api_parse');
     return $queue->numberOfItems();
 }
 /**
  * Perform a history synchronization that processes an incoming event.
  *
  * @param VersioncontrolEvent $event
  *   A VersioncontrolEvent object containing repository state change
  *   information. It should already have been written to the database (it
  *   should have an elid).
  *
  * @return bool
  *   Returns TRUE on a successful synchronization, FALSE on a failure.
  */
 public function syncEvent(VersioncontrolEvent $event)
 {
     // Prepare and insert the initial log object.
     $log = new stdClass();
     $log->repo_id = $this->repo_id;
     $log->elid = $event->elid;
     $log->plugin = $this->getPluginName('reposync');
     $log->start = microtime(TRUE);
     $ret = drupal_write_record('versioncontrol_sync_log', $log);
     $sync_options = $this->getSynchronizerOptions();
     // Disable object cache on parsing.
     $this->getBackend()->disableControllerCaching();
     // Try to sync the event.
     try {
         $sync = $this->getSynchronizer();
         $sync_status = $sync->syncEvent($event, $sync_options);
         // No excepctions. Log it and finish up.
         $log->end = microtime(TRUE);
         $log->successful = (int) $sync_status;
         $log->fullsync_failover = 0;
     } catch (VersioncontrolLockedRepositoryException $locked_exception) {
         // Locked repository. Prepare the log and enqueue the sync again if
         // needed.
         $log->end = microtime(TRUE);
         $log->successful = 0;
         $log->errors = $sync::SYNC_ERROR_LOCKED;
         $log->message = 'Locked repository: ' . $locked_exception->getMessage() . PHP_EOL;
         $attempts = db_query('SELECT COUNT(slid) FROM {versioncontrol_sync_log} WHERE elid = :elid', array(':elid' => $event->elid))->fetchField();
         // @todo Maybe add configuration to override retry limit per reposync
         // plugin or other criteria.
         if ($attempts < variable_get('versioncontrol_reposync_max_syncevent_retries', 5)) {
             // If we do not enqueue it again, the event is not processed, unless a
             // full sync happen.
             $payload = array('uid' => $event->uid, 'repo_id' => $this->repo_id, 'data' => $this->generateRawData($event), 'timestamp' => $event->timestamp, 'elid' => $event->elid);
             $queue = DrupalQueue::get('versioncontrol_reposync', TRUE);
             $queue->createItem($payload);
         } else {
             // @todo Maybe we should include a flag on repository table to indicate
             // that a full syncronization is needed?
             $msg = 'Event with elid = @elid from repository @name (@id) reached the limit of retries. Please perform a full syncronization on it.';
             $vars = array('@elid' => $event->elid, '@name' => $this->name, '@id' => $this->repo_id);
             watchdog('versioncontrol', $msg, $vars, WATCHDOG_WARNING);
         }
     } catch (VersioncontrolNeedsFullSynchronizationException $e) {
         // It is needed to switch over and perform a full sync, then finish the
         // evented logic. First, ensure the repository is unlocked.
         $this->unlock();
         // Then, flip over to the full sync logic and hope that works.
         try {
             $sync_status = $sync->syncFull($sync_options);
             // No exceptions, great. Finalize the event, log the situation, then
             // finish.
             $log->end = microtime(TRUE);
             $log->successful = (int) $sync_status;
             $log->fullsync_failover = 1;
             $log->message = 'Event sync failure exception message: ' . $e->getMessage();
         } catch (VersioncontrolSynchronizationException $e2) {
             // Nothing we can do. Log the problem, then bail out.
             $this->unlock();
             $log->end = microtime(TRUE);
             $log->successful = 0;
             $log->fullsync_failover = 1;
             $log->message = 'Recoverable event sync failure exception message: ' . $e->getMessage() . PHP_EOL . 'Full sync failure exception message: ' . $e2->getMessage();
         }
     } catch (VersioncontrolSynchronizationException $e) {
         // There was a known exception, but one that cannot be solved with a
         // fullsync attempt. Clean up and log the error, doing what we can with
         // the event.
         $this->unlock();
         $log->end = microtime(TRUE);
         $log->successful = 0;
         $log->fullsync_failover = 0;
         $log->message = 'Unrecoverable event sync failure exception message: ' . $e->getMessage() . PHP_EOL;
     } catch (Exception $e) {
         // Some non-sync exception was thrown. Weird situation.
         $this->unlock();
         $log->end = microtime(TRUE);
         $log->successful = 0;
         $log->fullsync_failover = 0;
         $log->message = "Unexpected exception of type '" . get_class($e) . "' with message: " . $e->getMessage() . PHP_EOL;
     }
     $this->finalizeEvent($event);
     // Re-enable object cache after parsing.
     $this->getBackend()->restoreControllerCachingDefaults();
     drupal_write_record('versioncontrol_sync_log', $log, 'slid');
     return (bool) $log->successful;
 }