/**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     foreach (Element::children($form_state->getValue('stock')) as $sku) {
         $stock = $form_state->getValue(['stock', $sku]);
         db_merge('uc_product_stock')->key(array('sku' => $sku))->updateFields(array('active' => $stock['active'], 'stock' => $stock['stock'], 'threshold' => $stock['threshold']))->insertFields(array('sku' => $sku, 'active' => $stock['active'], 'stock' => $stock['stock'], 'threshold' => $stock['threshold'], 'nid' => $form_state->getValue('nid')))->execute();
     }
     drupal_set_message($this->t('Stock settings saved.'));
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Remove Form API elements from $form_state
     $form_state->cleanValues();
     db_merge('uc_attributes')->key(array('aid' => $form_state->getValue('aid')))->fields($form_state->getValues())->execute();
     $form_state->setRedirect('uc_attribute.overview');
 }
Example #3
0
 public function write($sessionId, $serializedData)
 {
     try {
         // For performance reasons, do not update the sessions table, unless
         // $_SESSION has changed or more than 180 has passed since the last update.
         if ($this->sessionDataHasChanged($sessionId, $serializedData)) {
             // Either ssid or sid or both will be added from $key below.
             $fields = array('uid' => $this->uid, 'cache' => 0, 'hostname' => ip_address(), 'session' => $serializedData, 'timestamp' => REQUEST_TIME);
             $key = array('sid' => $sessionId, 'ssid' => '');
             db_merge('sessions')->key($key)->fields($fields)->execute();
         }
         return TRUE;
     } catch (Exception $exception) {
         // FIXME: This should never be here, a global try/catch should definitely
         // be done upper in the code.
         require_once DRUPAL_ROOT . '/includes/errors.inc';
         // If we are displaying errors, then do so with no possibility of a further
         // uncaught exception being thrown.
         if (error_displayable()) {
             print '<h1>Uncaught exception thrown in session handler.</h1>';
             print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
         }
         return FALSE;
     }
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function orderSave(OrderInterface $order)
 {
     if (empty($order->payment_details['description'])) {
         db_delete('uc_payment_other')->condition('order_id', $order->id())->execute();
     } else {
         db_merge('uc_payment_other')->key(array('order_id' => $order->id()))->fields(array('description' => $order->payment_details['description']))->execute();
     }
 }
Example #5
0
 public function unhandleEntity(array $metadata = array())
 {
     if (!empty($metadata['manualcrop_selections']) && is_array($metadata['manualcrop_selections'])) {
         foreach ($metadata['manualcrop_selections'] as $data) {
             db_merge('manualcrop')->key(array('fid' => $this->original_entity->id(), 'style_name' => $data['style_name']))->fields($data)->execute();
         }
     }
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Remove Form API elements from $form_state
     $form_state->cleanValues();
     db_merge('uc_attribute_options')->key(array('aid' => $form_state->getValue('aid'), 'oid' => $form_state->getValue('oid')))->fields($form_state->getValues())->execute();
     drupal_set_message($this->t('Updated option %option.', ['%option' => $form_state->getValue('name')]));
     $this->logger('uc_attribute')->notice('Updated option %option.', ['%option' => $form_state->getValue('name'), 'link' => 'admin/store/products/attributes/' . $form_state->getValue('aid') . '/options/' . $form_state->getValue('oid')]);
     $form_state->setRedirect('uc_attribute.options', ['aid' => $form_state->getValue('aid')]);
 }
Example #7
0
 public function write($sid, $value)
 {
     if ($value === '') {
         return true;
     }
     $fields = array('sid' => $sid, 'session' => $value, 'timestamp' => time() + $this->expire);
     db_merge('sessions')->key(array('sid' => $sid))->fields($fields)->execute();
     return true;
 }
Example #8
0
 /**
  * Save data associated with a user.
  */
 public function putData($username, $data)
 {
     // Encrypt the data, if a plugin in available.
     if (module_exists('aes')) {
         $data = aes_encrypt($data);
     } elseif (module_exists('encrypt')) {
         $data = encrypt($data);
     }
     $result = db_merge('ga_login')->key(array('name' => $username))->fields(array('keydata' => $data))->execute();
     if ($result) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $form_state->cleanValues();
     if ($form_state->hasValue('mid')) {
         db_merge('uc_weightquote_methods')->key(array('mid' => $form_state->getValue('mid')))->fields($form_state->getValues())->execute();
         drupal_set_message(t('Weight quote shipping method was updated.'));
         $form_state->setRedirect('uc_quote.methods');
     } else {
         db_insert('uc_weightquote_methods')->fields($form_state->getValues())->execute();
         // Ensure Rules picks up the new condition.
         // entity_flush_caches();
         drupal_set_message(t('Created and enabled new weight quote shipping method.'));
         $form_state->setRedirect('uc_quote.methods');
         //$form_state['redirect'] = 'admin/store/config/quotes/manage/get_quote_from_weightquote_' . $form_state->getValue('mid');
     }
 }
 /**
  * Implements DrupalCacheInterface::set().
  */
 function set($cid, $data, $expire = CACHE_PERMANENT)
 {
     $fields = array('serialized' => 0, 'created' => REQUEST_TIME, 'expire' => $expire);
     if (!is_string($data)) {
         $fields['data'] = igbinary_serialize($data);
         $fields['serialized'] = 1;
     } else {
         $fields['data'] = $data;
         $fields['serialized'] = 0;
     }
     try {
         db_merge($this->bin)->key(array('cid' => $cid))->fields($fields)->execute();
     } catch (Exception $e) {
         // The database may not be available, so we'll ignore cache_set requests.
     }
 }
 /**
  * Run the configured migrations.
  */
 public function import()
 {
     $log = new DrushLogMigrateMessage();
     foreach ($this->migrationList as $migration_id) {
         /** @var MigrationInterface $migration */
         $migration = Migration::load($migration_id);
         drush_print(dt('Upgrading @migration', ['@migration' => $migration_id]));
         $executable = new MigrateExecutable($migration, $log);
         // drush_op() provides --simulate support.
         drush_op([$executable, 'import']);
         // @todo Remove when https://www.drupal.org/node/2598696 is released.
         if ($migration_id == 'd6_user' || $migration_id == 'd7_user') {
             $table = 'migrate_map_' . $migration_id;
             db_merge($table)->key(['sourceid1' => 1])->fields(['destid1' => -1])->execute();
         }
     }
 }
 /**
  * Tests garbage collection.
  */
 public function testGarbageCollection()
 {
     $collection = $this->randomMachineName();
     $store = new DatabaseStorageExpirable($collection, new PhpSerialize(), Database::getConnection());
     // Insert some items and confirm that they're set.
     for ($i = 0; $i <= 3; $i++) {
         $store->setWithExpire('key_' . $i, $this->randomObject(), rand(500, 100000));
     }
     $this->assertIdentical(sizeof($store->getAll()), 4, 'Four items were written to the storage.');
     // Manually expire the data.
     for ($i = 0; $i <= 3; $i++) {
         db_merge('key_value_expire')->keys(array('name' => 'key_' . $i, 'collection' => $collection))->fields(array('expire' => REQUEST_TIME - 1))->execute();
     }
     // Perform a new set operation and then trigger garbage collection.
     $store->setWithExpire('autumn', 'winter', rand(500, 1000000));
     system_cron();
     // Query the database and confirm that the stale records were deleted.
     $result = db_query('SELECT name, value FROM {key_value_expire} WHERE collection = :collection', array(':collection' => $collection))->fetchAll();
     $this->assertIdentical(count($result), 1, 'Only one item remains after garbage collection');
 }
/**
 * Save a custom menu.
 *
 * @param $menu
 *   An array representing a custom menu:
 *   - menu_name: The unique name of the custom menu (composed of lowercase
 *     letters, numbers, and hyphens).
 *   - title: The human readable menu title.
 *   - description: The custom menu description.
 *
 * Modules should always pass a fully populated $menu when saving a custom
 * menu, so other modules are able to output proper status or watchdog messages.
 *
 * @see menu_load()
 */
function menu_save($menu)
{
    $status = db_merge('menu_custom')->key(array('menu_name' => $menu['menu_name']))->fields(array('title' => $menu['title'], 'description' => $menu['description']))->execute();
    menu_cache_clear_all();
    switch ($status) {
        case SAVED_NEW:
            // Make sure the menu is present in the active menus variable so that its
            // items may appear in the menu active trail.
            // @see menu_set_active_menu_names()
            $active_menus = variable_get('menu_default_active_menus', array_keys(menu_get_menus()));
            if (!in_array($menu['menu_name'], $active_menus)) {
                $active_menus[] = $menu['menu_name'];
                variable_set('menu_default_active_menus', $active_menus);
            }
            module_invoke_all('menu_insert', $menu);
            break;
        case SAVED_UPDATED:
            module_invoke_all('menu_update', $menu);
            break;
    }
}
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $changed = FALSE;
     foreach ($form_state->getValue('attributes') as $aid => $attribute) {
         if ($attribute['remove']) {
             $remove_aids[] = $aid;
         } else {
             unset($attribute['remove']);
             db_merge($this->attributeTable)->key('aid', $aid)->fields($attribute)->execute();
             $changed = TRUE;
         }
     }
     if (isset($remove_aids)) {
         $select = db_select('uc_attribute_options', 'ao')->fields('ao', array('oid'))->condition('ao.aid', $remove_aids, 'IN');
         db_delete($this->optionTable)->condition('oid', $select, 'IN')->condition($this->idField, $this->idValue)->execute();
         db_delete($this->attributeTable)->condition($this->idField, $this->idValue)->condition('aid', $remove_aids, 'IN')->execute();
         $this->attributesRemoved();
         drupal_set_message($this->formatPlural(count($remove_aids), '1 attribute has been removed.', '@count attributes have been removed.'));
     }
     if ($changed) {
         drupal_set_message($this->t('The changes have been saved.'));
     }
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function assignUser(GradeScaleInterface $grade_scale, $account)
 {
     db_merge('grade_scale_users')->key('uid', $account->id())->fields(array('set_name' => $grade_scale->id()))->execute();
     drupal_static_reset('grade_scale_current_displayed_set');
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function assignUser(ShortcutSetInterface $shortcut_set, $account)
 {
     db_merge('shortcut_set_users')->key('uid', $account->id())->fields(array('set_name' => $shortcut_set->id()))->execute();
     drupal_static_reset('shortcut_current_displayed_set');
 }
Example #17
0
 /**
  * Grant permissions to a specific role, if it exists.
  *
  * @param string $role
  *    Role machine name.
  * @param string $permission
  *    Permission machine name.
  * @param string $module
  *    Module name.
  *
  * @return bool
  *    TRUE if operation was successful, FALSE otherwise.
  */
 public function grantPermission($role, $permission, $module = NULL)
 {
     $permission_rebuilt =& drupal_static(__CLASS__ . ':' . __FUNCTION__);
     if (!$permission_rebuilt) {
         // Make sure the list of available node types is up to date.
         node_types_rebuild();
         // Reset hook_permission() cached information.
         module_implements('permission', FALSE, TRUE);
         $permission_rebuilt = TRUE;
     }
     $permissions = is_array($permission) ? $permission : array($permission);
     $role_object = user_role_load_by_name($role);
     if ($role_object) {
         // Use code from user_role_grant_permissions() in order to be able
         // to force medule field in special cases.
         $modules = user_permission_get_modules();
         // Grant new permissions for the role.
         foreach ($permissions as $name) {
             $modules[$name] = isset($modules[$name]) ? $modules[$name] : $module;
             db_merge('role_permission')->key(array('rid' => $role_object->rid, 'permission' => $name))->fields(array('module' => $modules[$name]))->execute();
         }
         // Clear the user access cache.
         drupal_static_reset('user_access');
         drupal_static_reset('user_role_permissions');
         return TRUE;
     } else {
         return FALSE;
     }
 }
Example #18
0
/**
 * Respond to updates to a user role.
 *
 * Modules implementing this hook can act on the user role object when updated.
 * It's recommended that you implement this hook if your module adds additional
 * data to user roles object. The module should save its custom additions to
 * the database.
 *
 * @param $role
 *   A user role object.
 */
function hook_user_role_update($role)
{
    // Save extra fields provided by the module to user roles.
    db_merge('my_module_table')->key(array('role' => $role->name))->fields(array('role_description' => $role->description))->execute();
}
<?php

/**
 * @file
 * Handles counts of node views via Ajax with minimal bootstrap.
 */
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', substr($_SERVER['SCRIPT_FILENAME'], 0, strpos($_SERVER['SCRIPT_FILENAME'], '/modules/statistics/statistics.php')));
// Change the directory to the Drupal root.
chdir(DRUPAL_ROOT);
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);
if (variable_get('statistics_count_content_views', 0) && variable_get('statistics_count_content_views_ajax', 0)) {
    if (isset($_POST['nid'])) {
        $nid = $_POST['nid'];
        if (is_numeric($nid)) {
            db_merge('node_counter')->key(array('nid' => $nid))->fields(array('daycount' => 1, 'totalcount' => 1, 'timestamp' => REQUEST_TIME))->expression('daycount', 'daycount + 1')->expression('totalcount', 'totalcount + 1')->execute();
        }
    }
}
Example #20
0
 /**
  * Save (upsert) the stats records in prod_drupal_stats table.
  *
  * @return StatsProviderInterface
  *
  * @throws Drupal\Prod\Error\StatTaskException
  */
 public function save()
 {
     $this->logger->log('Saving StatProvider records for Users Stats ', NULL, WATCHDOG_DEBUG);
     // Upsert the record
     try {
         db_merge('prod_drupal_stats')->key(array('ptq_stat_tid' => $this->getId(), 'pds_name' => 'user_total'))->fields(array('pds_value' => $this->getTotalUsers(), 'pds_is_1024' => 0, 'pds_timestamp' => REQUEST_TIME, 'pds_enable' => 1))->execute();
         db_merge('prod_drupal_stats')->key(array('ptq_stat_tid' => $this->getId(), 'pds_name' => 'user_enabled'))->fields(array('pds_value' => $this->getEnabledUSers(), 'pds_is_1024' => 0, 'pds_timestamp' => REQUEST_TIME, 'pds_enable' => 1))->execute();
         db_merge('prod_drupal_stats')->key(array('ptq_stat_tid' => $this->getId(), 'pds_name' => 'user_active'))->fields(array('pds_value' => $this->getActiveUsers(), 'pds_is_1024' => 0, 'pds_timestamp' => REQUEST_TIME, 'pds_enable' => 1))->execute();
         db_merge('prod_drupal_stats')->key(array('ptq_stat_tid' => $this->getId(), 'pds_name' => 'online_users'))->fields(array('pds_value' => $this->getRecentConnected(), 'pds_is_1024' => 0, 'pds_timestamp' => REQUEST_TIME, 'pds_enable' => 1))->execute();
         db_merge('prod_drupal_stats')->key(array('ptq_stat_tid' => $this->getId(), 'pds_name' => 'day_active_users'))->fields(array('pds_value' => $this->getDayConnected(), 'pds_is_1024' => 0, 'pds_timestamp' => REQUEST_TIME, 'pds_enable' => 1))->execute();
         db_merge('prod_drupal_stats')->key(array('ptq_stat_tid' => $this->getId(), 'pds_name' => 'month_active_users'))->fields(array('pds_value' => $this->getMonthConnected(), 'pds_is_1024' => 0, 'pds_timestamp' => REQUEST_TIME, 'pds_enable' => 1))->execute();
     } catch (Exception $e) {
         throw new StatTaskException(__METHOD__ . ": Unable to save the Task Stat record. " . $e->getMessage());
     }
     return $this;
 }
Example #21
0
 /**
  * Tests that an invalid merge query throws an exception.
  */
 function testInvalidMerge()
 {
     try {
         // This query will fail because there is no key field specified.
         // Normally it would throw an exception but we are suppressing it with
         // the throw_exception option.
         $options['throw_exception'] = FALSE;
         db_merge('test_people', $options)->fields(array('age' => 31, 'name' => 'Tiffany'))->execute();
         $this->pass('$options[\'throw_exception\'] is FALSE, no InvalidMergeQueryException thrown.');
     } catch (InvalidMergeQueryException $e) {
         $this->fail('$options[\'throw_exception\'] is FALSE, but InvalidMergeQueryException thrown for invalid query.');
         return;
     }
     try {
         // This query will fail because there is no key field specified.
         db_merge('test_people')->fields(array('age' => 31, 'name' => 'Tiffany'))->execute();
     } catch (InvalidMergeQueryException $e) {
         $this->pass('InvalidMergeQueryException thrown for invalid query.');
         return;
     }
     $this->fail('No InvalidMergeQueryException thrown');
 }
Example #22
0
 protected function _saveTask(TaskInterface $task)
 {
     try {
         db_merge('prod_stats_task_queue')->key(array('ptq_module' => $task->getTaskModule(), 'ptq_name' => $task->getTaskName()))->fields(array('ptq_timestamp' => $task->getScheduling(), 'ptq_enable' => (int) $task->isEnabled(), 'ptq_is_internal' => (int) $task->isInternal()))->execute();
     } catch (Exception $e) {
         throw new StatTaskQueueException('An error occured while creating or updating a Stat Task queue record.' . $e->getmessage());
     }
     // get the record id
     try {
         $id = null;
         $query = db_select('prod_stats_task_queue', 'q');
         $query->fields('q', array('ptq_stat_tid'))->condition('ptq_module', $task->getTaskModule())->condition('ptq_name', $task->getTaskName());
         $result = $query->execute();
         foreach ($result as $res) {
             $id = $res->ptq_stat_tid;
         }
         if (is_null($id)) {
             throw new StatTaskQueueException('Record not found.');
         }
         $task->setId($id);
         return $id;
     } catch (Exception $e) {
         throw new StatTaskQueueException('Unable to reload the Stat Task queue record.' . $e->getmessage());
     }
 }
Example #23
0
function subscriptionData($op, $mail = FALSE, $key = FALSE, $autoConfirm = false)
{
    switch ($op) {
        case 'create':
            if ($autoConfirm) {
                $insert = db_insert('libya_subscriptions')->fields(array('mail' => $mail, 'code' => str_rand(12), 'confirm' => 1, 'sid' => 0))->execute();
            } else {
                $insert = db_insert('libya_subscriptions')->fields(array('mail' => $mail['mail'], 'code' => $mail['rand'], 'confirm' => 0, 'sid' => 0))->execute();
            }
            return $insert;
            break;
        case 'read':
            $data = NULL;
            if (!$key) {
                $r = db_query("select * from libya_subscriptions where `mail` = :mail", array(":mail" => $mail));
                $data = $r->fetchObject();
            } else {
                $r = db_query("select * from libya_subscriptions where `mail` = :mail and code = :code", array(":mail" => $mail, ':code' => $key));
                $data = $r->fetchObject();
            }
            return $data;
            break;
        case 'update':
            $update = db_merge('libya_subscriptions')->key(array('sid' => $mail->sid))->fields(array('mail' => $mail->mail, 'code' => $mail->code, 'confirm' => $mail->confirm, 'sid' => $mail->sid))->execute();
            return $update;
            break;
        case "delete":
            $r = db_query("delete from libya_subscriptions where mail = :mail and code = :code", array(":mail" => $mail, ':code' => $key));
            break;
        default:
            return NULL;
            break;
    }
}
<?php

/**
 * @file
 * Database additions for state system upgrade tests.
 *
 * This dump only contains data and schema components relevant for system
 * functionality. The drupal-7.filled.bare.php file is imported before
 * this dump, so the two form the database structure expected in tests
 * altogether.
 */
// Update system settings to known values.
db_merge('variable')->keys(array('name' => 'node_cron_views_scale'))->fields(array('value' => serialize(1.0 / 2000)))->execute();
db_merge('variable')->keys(array('name' => 'statistics_day_timestamp'))->fields(array('value' => serialize(1352070595)))->execute();
db_merge('variable')->keys(array('name' => 'tracker_index_nid'))->fields(array('value' => serialize(0)))->execute();
db_merge('variable')->keys(array('name' => 'update_last_check'))->fields(array('value' => serialize(1304208000)))->execute();
db_merge('variable')->keys(array('name' => 'update_last_email_notification'))->fields(array('value' => serialize(1304208000)))->execute();
db_merge('variable')->keys(array('name' => 'node_access_needs_rebuild'))->fields(array('value' => serialize(TRUE)))->execute();
db_merge('variable')->keys(array('name' => 'node_cron_last'))->fields(array('value' => serialize(1304208001)))->execute();
db_merge('variable')->keys(array('name' => 'cron_last'))->fields(array('value' => serialize(1304208002)))->execute();
db_merge('variable')->keys(array('name' => 'cron_key'))->fields(array('value' => serialize('kdm95qppDDlyZrcUOx453YwQqDA4DNmxi4VQcxzFU9M')))->execute();
db_merge('variable')->keys(array('name' => 'drupal_private_key'))->fields(array('value' => serialize('G38mKqASKus8VGMkMzVuXImYbzspCQ1iRT2iEZpMYmQ')))->execute();
db_merge('variable')->keys(array('name' => 'node_cron_comments_scale'))->fields(array('value' => serialize(1.0 / 1000)))->execute();
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Build the file_product object from the form values.
     $file = uc_file_get_by_name($form_state->getValue('uc_file_filename'));
     $file_product = array('fid' => $file->fid, 'filename' => $file->filename, 'pfid' => $form_state->getValue('pfid'), 'model' => $form_state->getValue('uc_file_model'), 'description' => $form_state->getValue('uc_file_description'), 'shippable' => $form_state->getValue('uc_file_shippable'), 'download_limit' => $form_state->getValue('download_limit_number') ?: UC_FILE_LIMIT_SENTINEL, 'address_limit' => $form_state->getValue('download_limit_addresses') ?: UC_FILE_LIMIT_SENTINEL, 'time_granularity' => $form_state->getValue('download_limit_duration_granularity') ?: UC_FILE_LIMIT_SENTINEL, 'time_quantity' => $form_state->getValue('download_limit_duration_qty') ?: UC_FILE_LIMIT_SENTINEL);
     // Build product feature descriptions.
     $file_config = $this->config('uc_file.settings');
     $description = $this->t('<strong>SKU:</strong> @sku<br />', ['@sku' => empty($file_product['model']) ? 'Any' : $file_product['model']]);
     if (is_dir($file_config->get('base_dir') . "/" . $file_product['filename'])) {
         $description .= $this->t('<strong>Directory:</strong> @dir<br />', ['@dir' => $file_product['filename']]);
     } else {
         $description .= $this->t('<strong>File:</strong> @file<br />', ['@file' => \Drupal::service('file_system')->basename($file_product['filename'])]);
     }
     $description .= $file_product['shippable'] ? $this->t('<strong>Shippable:</strong> Yes') : $this->t('<strong>Shippable:</strong> No');
     $data = array('pfid' => $file_product['pfid'], 'nid' => $form_state->getValue('nid'), 'fid' => 'file', 'description' => $description);
     uc_product_feature_save($data);
     $file_product['pfid'] = $data['pfid'];
     unset($file_product['filename']);
     $key = NULL;
     if ($fpid = _uc_file_get_fpid($file_product['pfid'])) {
         $key = $fpid;
     }
     // Insert or update (if $key is already in table) uc_file_products table.
     db_merge('uc_file_products')->key(['fpid' => $key])->fields($file_product)->execute();
     $form_state->setRedirect('uc_product.features', ['node' => $data['nid']]);
 }
Example #26
0
    //    ->key(array('field1' => $data_received, ))
    //    ->insertFields(array('field1' => $data_received, 'ip' => $_SERVER['REMOTE_ADDR']))
    //    ->updateFields(array('field1' => $data_received))
    //    ->execute();
    //Insert the user data and timestamp into your databases
    // $query = sprintf("INSERT INTO user_tracking (cmrc_code, company_email, company_name, started_at, status) VALUES('%s', '%s', '%s', '%s', '%s')", $cmrc_code, $company_email, $company_name, $started_at, $status );
    // mysql_query($query) or die(mysql_error());
}
if (isset($_POST['status']) && $_POST['status'] === '2') {
    $completed_at = date("Y-m-d H:i:s");
    // if (db_query('user_tracking_new') ->key(array('cmrc_code' => $cmrc_code, 'company_email' => $company_email))) {
    // update status to 2 and end time only if status is not 2 in db
    // ->insertFields(array('completed_at' => $completed_at))
    // add status => 2 // add attempts value
    // only most recent submission time is recorded
    db_merge('user_tracking')->key(array('cmrc_code' => $cmrc_code, 'company_email' => $company_email))->updateFields(array('completed_at' => $completed_at, 'status' => $status))->execute();
    //check if loggedin
    function logincheck($logincode, $users_table, $pass_column, $user_column)
    {
        //conect to DB
        $this->dbconnect();
        //make sure password column and table are set
        if ($this->pass_column == "") {
            $this->pass_column = $pass_column;
        }
        if ($this->users_column == "") {
            $this->users_column = $users_column;
        }
        if ($this->users_table == "") {
            $this->users_table = $users_table;
        }
Example #27
0
/**
 * Act before entity deletion of a particular entity type.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that is about to be deleted.
 *
 * @ingroup entity_crud
 * @see hook_entity_predelete()
 */
function hook_ENTITY_TYPE_predelete(Drupal\Core\Entity\EntityInterface $entity)
{
    // Count references to this entity in a custom table before they are removed
    // upon entity deletion.
    $id = $entity->id();
    $type = $entity->getEntityTypeId();
    $count = db_select('example_entity_data')->condition('type', $type)->condition('id', $id)->countQuery()->execute()->fetchField();
    // Log the count in a table that records this statistic for deleted entities.
    db_merge('example_deleted_entity_statistics')->key(array('type' => $type, 'id' => $id))->fields(array('count' => $count))->execute();
}
Example #28
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $cart_links_config = $this->config('uc_cart_links.settings');
     $actions = explode('-', urldecode($this->actions));
     $rebuild_cart = FALSE;
     $messages = array();
     $id = $this->t('(not specified)');
     $cart = Cart::create(\Drupal::getContainer());
     foreach ($actions as $action) {
         switch (Unicode::substr($action, 0, 1)) {
             // Set the ID of the Cart Link.
             case 'i':
             case 'I':
                 $id = Unicode::substr($action, 1, 32);
                 break;
                 // Add a product to the cart.
             // Add a product to the cart.
             case 'p':
             case 'P':
                 // Set the default product variables.
                 $p = array('nid' => 0, 'qty' => 1, 'data' => array());
                 $msg = TRUE;
                 // Parse the product action to adjust the product variables.
                 $parts = explode('_', $action);
                 foreach ($parts as $part) {
                     switch (Unicode::substr($part, 0, 1)) {
                         // Set the product node ID: p23
                         case 'p':
                         case 'P':
                             $p['nid'] = intval(Unicode::substr($part, 1));
                             break;
                             // Set the quantity to add to cart: _q2
                         // Set the quantity to add to cart: _q2
                         case 'q':
                         case 'Q':
                             $p['qty'] = intval(Unicode::substr($part, 1));
                             break;
                             // Set an attribute/option for the product: _a3o6
                         // Set an attribute/option for the product: _a3o6
                         case 'a':
                         case 'A':
                             $attribute = intval(Unicode::substr($part, 1, stripos($part, 'o') - 1));
                             $option = (string) Unicode::substr($part, stripos($part, 'o') + 1);
                             if (!isset($p['attributes'][$attribute])) {
                                 $p['attributes'][$attribute] = $option;
                             } else {
                                 // Multiple options for this attribute implies checkbox
                                 // attribute, which we must store as an array
                                 if (is_array($p['attributes'][$attribute])) {
                                     // Already an array, just append this new option
                                     $p['attributes'][$attribute][$option] = $option;
                                 } else {
                                     // Set but not an array, means we already have at least one
                                     // option, so put that into an array with this new option
                                     $p['attributes'][$attribute] = array($p['attributes'][$attribute] => $p['attributes'][$attribute], $option => $option);
                                 }
                             }
                             break;
                             // Suppress the add to cart message: _s
                         // Suppress the add to cart message: _s
                         case 's':
                         case 'S':
                             $msg = FALSE;
                             break;
                     }
                 }
                 // Add the item to the cart, suppressing the default redirect.
                 if ($p['nid'] > 0 && $p['qty'] > 0) {
                     // If it's a product kit, we need black magic to make everything work
                     // right. In other words, we have to simulate FAPI's form values.
                     $node = node_load($p['nid']);
                     if ($node->status) {
                         if (isset($node->products) && is_array($node->products)) {
                             foreach ($node->products as $nid => $product) {
                                 $p['data']['products'][$nid] = array('nid' => $nid, 'qty' => $product->qty);
                             }
                         }
                         $cart->addItem($p['nid'], $p['qty'], $p['data'] + \Drupal::moduleHandler()->invokeAll('uc_add_to_cart_data', array($p)), NULL, $msg, FALSE, FALSE);
                         $rebuild_cart = TRUE;
                     } else {
                         $this->logger('uc_cart_link')->error('Cart Link on %url tried to add an unpublished product to the cart.', array('%url' => $this->getRequest()->server->get('HTTP_REFERER')));
                     }
                 }
                 break;
                 // Empty the shopping cart.
             // Empty the shopping cart.
             case 'e':
             case 'E':
                 if ($cart_links_config->get('empty')) {
                     $cart->emptyCart();
                 }
                 break;
                 // Display a pre-configured message.
             // Display a pre-configured message.
             case 'm':
             case 'M':
                 // Load the messages if they haven't been loaded yet.
                 if (empty($messages)) {
                     $data = explode("\n", $cart_links_config->get('messages'));
                     foreach ($data as $message) {
                         list($mkey, $mdata) = explode('|', $message, 2);
                         $messages[trim($mkey)] = trim($mdata);
                     }
                 }
                 // Parse the message key and display it if it exists.
                 $mkey = intval(Unicode::substr($action, 1));
                 if (!empty($messages[$mkey])) {
                     drupal_set_message($messages[$mkey]);
                 }
                 break;
         }
         // Rebuild the cart cache if necessary.
         if ($rebuild_cart) {
             $cart->getContents(NULL, 'rebuild');
         }
     }
     if ($cart_links_config->get('track')) {
         db_merge('uc_cart_link_clicks')->key(array('cart_link_id' => (string) $id))->fields(array('clicks' => 1, 'last_click' => REQUEST_TIME))->expression('clicks', 'clicks + :i', array(':i' => 1))->execute();
     }
     $_SESSION['uc_cart_last_url'] = $this->getRequest()->server->get('HTTP_REFERER');
     $query = $this->getRequest()->query;
     if ($query->has('destination')) {
         $options = UrlHelper::parse($query->get('destination'));
         $path = $options['path'];
     } else {
         $path = 'cart';
         $options = array();
     }
     $options += array('absolute' => TRUE);
     // Form redirect is for confirmed links.
     $form_state->setRedirectUrl(Url::fromUri('base:/' . $path, $options));
 }
 /**
  * Save segment's translation for the given target
  *
  * @param int
  *   the lid of the segment being translated
  * @param string
  *   the 2-digit language code for the target language
  * @param string
  *   the translated content to be saved
  */
 public static function saveSegmentTranslation($lid, $target_language, $content)
 {
     // insert/update translations, overwriting everything that is there
     // except for the i18n_status field, which should preserve its
     // currently-set flags, and the plid and plural fields which just
     // take default values for now.
     db_merge('{locales_target}')->key(array('lid' => $lid, 'language' => $target_language))->fields(array('lid' => $lid, 'translation' => $content, 'language' => $target_language))->execute();
 }
Example #30
0
function banner_set_banner_count($tid, $count)
{
    db_merge('banner_count')->key(array('tid' => $tid))->fields(array('count' => $count))->execute();
}