public function addToUser($postData, $user_id)
 {
     // $postData['news_date'] = date("Y-m-d H:i:s");
     $postData['author'] = 1;
     // echo "<pre>";var_dump($postData);echo (db_insert($this->table, $postData));die;
     return db_insert($this->table, $postData);
 }
Example #2
0
 /**
  * The student inserts this initially once he/she accepts a project offer
  * @param unknown $props
  * @param unknown $proposal_id
  * @return boolean|unknown
  */
 static function insertAgreement($props)
 {
     if (!$props) {
         drupal_set_message(t('Insert requested with empty (filtered) data set'), 'error');
         return false;
     }
     if (!isset($props['proposal_id'])) {
         drupal_set_message(t('Insert requested with no proposal set'), 'error');
         return false;
     }
     global $user;
     $txn = db_transaction();
     try {
         $proposal = objectToArray(Proposal::getInstance()->getProposalById($props['proposal_id']));
         $project = objectToArray(Project::getProjectById($proposal['pid']));
         if (!isset($props['student_id'])) {
             $props['student_id'] = $user->uid;
         }
         if (!isset($props['supervisor_id'])) {
             $props['supervisor_id'] = $proposal['supervisor_id'];
         }
         if (!isset($props['mentor_id'])) {
             $props['mentor_id'] = $project['mentor_id'];
         }
         $props['project_id'] = $proposal['pid'];
         if (!isset($props['description'])) {
             $props['description'] = '';
         }
         if (!isset($props['student_signed'])) {
             $props['student_signed'] = 0;
         }
         if (!isset($props['supervisor_signed'])) {
             $props['supervisor_signed'] = 0;
         }
         if (!isset($props['mentor_signed'])) {
             $props['mentor_signed'] = 0;
         }
         /*
         if (! testInput($props, array('owner_id', 'org_id', 'inst_id', 'supervisor_id','pid', 'title'))){
         	return FALSE;
         }
         */
         try {
             $id = db_insert(tableName(_AGREEMENT_OBJ))->fields($props)->execute();
         } catch (Exception $e) {
             drupal_set_message($e->getMessage(), 'error');
         }
         if ($id) {
             drupal_set_message(t('You have created your agreement: you can continue editing it later.'));
             return $id;
         } else {
             drupal_set_message(t('We could not add your agreement. ') . (_DEBUG ? '<br/>' . getDrupalMessages() : ""), 'error');
         }
         return $result;
     } catch (Exception $ex) {
         $txn->rollback();
         drupal_set_message(t('We could not add your agreement.') . (_DEBUG ? $ex->__toString() : ''), 'error');
     }
     return FALSE;
 }
 /**
  * Tests aborting of traditional SQL database systems with invalid data.
  */
 function testInsertDuplicateData()
 {
     // Try to insert multiple records where at least one has bad data.
     try {
         db_insert('test')->fields(array('name', 'age', 'job'))->values(array('name' => 'Elvis', 'age' => 63, 'job' => 'Singer'))->values(array('name' => 'John', 'age' => 17, 'job' => 'Consultant'))->values(array('name' => 'Frank', 'age' => 75, 'job' => 'Singer'))->execute();
         $this->fail('Insert succeedded when it should not have.');
     } catch (IntegrityConstraintViolationException $e) {
         // Check if the first record was inserted.
         $name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 63))->fetchField();
         if ($name == 'Elvis') {
             if (!Database::getConnection()->supportsTransactions()) {
                 // This is an expected fail.
                 // Database engines that don't support transactions can leave partial
                 // inserts in place when an error occurs. This is the case for MySQL
                 // when running on a MyISAM table.
                 $this->pass("The whole transaction has not been rolled-back when a duplicate key insert occurs, this is expected because the database doesn't support transactions");
             } else {
                 $this->fail('The whole transaction is rolled back when a duplicate key insert occurs.');
             }
         } else {
             $this->pass('The whole transaction is rolled back when a duplicate key insert occurs.');
         }
         // Ensure the other values were not inserted.
         $record = db_select('test')->fields('test', array('name', 'age'))->condition('age', array(17, 75), 'IN')->execute()->fetchObject();
         $this->assertFalse($record, 'The rest of the insert aborted as expected.');
     }
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     //TODO v2 Send Email via Cron not on Submit
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $username = $user->get('name')->value;
     $userId = $user->get('uid')->value;
     $mailManager = \Drupal::service('plugin.manager.mail');
     $jobNode = \Drupal::routeMatch()->getParameter('node');
     $jobNodeTitle = $jobNode->getTitle();
     $companyNodeEntity = $jobNode->get('field_company');
     $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
     $companyEmail = $companyNode->field_email->value;
     $resumeFileId = $form_state->getValue('resume');
     $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField();
     $atttachment = array('filepath' => $resumeFile);
     $module = 'job_mailer';
     $key = 'apply_job';
     $params['job_title'] = $jobNodeTitle;
     $params['message'] = "<html>\n           <p>Please see attached resume for user: {$username}\n           </html>";
     $params['attachment'] = $atttachment;
     $langcode = \Drupal::currentUser()->getPreferredLangcode();
     $send = true;
     $reply = \Drupal::config('system.site')->get('mail');
     $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send);
     db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute();
     drupal_set_message('Your application has been sent.');
 }
Example #5
0
 public function add_tag($idPost, $tag)
 {
     $idTag = NULL;
     $arrTag = explode(",", $tag);
     foreach ($arrTag as $t) {
         $t = trim($t);
         //bo cac khoang trang
         if ($t != "") {
             //truong hop k co tag
             //query tag table
             $sql = "SELECT * FROM `{$this->table_tag}` where `name` = '{$t}'";
             $result = db_get_all($sql);
             if (count($result) == 0) {
                 $temp = array('name' => $t);
                 db_insert($this->table_tag, $temp);
                 $idTag = mysql_insert_id();
             } else {
                 //lay id cua tag nay
                 $idTag = $result[0]['id'];
             }
             $temp2 = array('post_id' => $idPost, 'tag_id' => $idTag);
             db_insert('post_tag', $temp2);
         }
     }
 }
Example #6
0
function api_graph_template_suggested_values_save($graph_template_id, $_fields_suggested_values) {
	require_once(CACTI_BASE_PATH . "/lib/sys/sequence.php");

	/* sanity checks */
	validate_id_die($graph_template_id, "graph_template_id");

	/* insert the new custom field values */
	if (is_array($_fields_suggested_values) > 0) {
		foreach ($_fields_suggested_values as $field_name => $field_array) {
			foreach ($field_array as $field_item) {
				if (empty($field_item["id"])) {
					db_insert("graph_template_suggested_value",
						array(
							"id" => array("type" => DB_TYPE_INTEGER, "value" => "0"),
							"graph_template_id" => array("type" => DB_TYPE_INTEGER, "value" => $graph_template_id),
							"field_name" => array("type" => DB_TYPE_STRING, "value" => $field_name),
							"value" => array("type" => DB_TYPE_STRING, "value" => $field_item["value"]),
							"sequence" => array("type" => DB_TYPE_INTEGER, "value" => seq_get_current(0, "sequence", "graph_template_suggested_value", "graph_template_id = " . sql_sanitize($graph_template_id) . " and field_name = '" . sql_sanitize($field_name) . "'"))
							),
						array("id"));
				}else{
					db_update("graph_template_suggested_value",
						array(
							"id" => array("type" => DB_TYPE_INTEGER, "value" => $field_item["id"]),
							"value" => array("type" => DB_TYPE_STRING, "value" => $field_item["value"])
							),
						array("id"));
				}
			}
		}
	}
}
 function apachesolr_mark_node($nid)
 {
     if (function_exists('apachesolr_mark_entity')) {
         // Bug killer - Check if the target nodeId exists in the apachesolr_index_entities_node table...
         $nodeExistsInIndexTbl = false;
         $query = "SELECT count(entity_id) AS 'count' FROM apachesolr_index_entities_node WHERE entity_id={$nid} ";
         $results = db_query($query);
         foreach ($results as $record) {
             if (intval($record->count) > 0) {
                 $nodeExistsInIndexTbl = true;
             }
             break;
         }
         // Bug killer - If the target nodeId does not exist in the apachesolr_index_entities_node table, insert it
         if ($nodeExistsInIndexTbl === false) {
             $results = db_query("SELECT nid, type, status, changed FROM node WHERE nid={$nid} LIMIT 1");
             foreach ($results as $record) {
                 $nodeInfo = $record;
             }
             if (!empty($nodeInfo)) {
                 db_insert('apachesolr_index_entities_node')->fields(array('entity_type' => 'node', 'entity_id' => $nid, 'bundle' => $nodeInfo->type, 'status' => $nodeInfo->status, 'changed' => $nodeInfo->changed))->execute();
             }
         }
         apachesolr_mark_entity('node', $nid);
     }
 }
Example #8
0
/**
 * This is an example implementation for the hook. Preforms actions when converting a node based on it's type.
 *
 * @param $data
 *   An array containing information about the conversion process. The keys are
 *   - dest_node_type  The destination type of the node
 *   - node  The node object
 *   - Any other information passed by $op = 'options' or $op = 'options validate'
 * @param $op
 *   A string containing the operation which should be executed. These are the possible values
 *   - insert  Operations which should be run when the node is transferred to the new node type.
 *   Usually for transferring and adding new node information into the database.
 *   - delete  Operations which should be run after the node is transferred to the new node type.
 *   Usually for deleting unneeded information from the database after the transfer.
 *   - options  Configuration elements shown on the conversion form. Should return a FAPI array.
 *   - options validate  Validation check on the options elements.
 * @return
 *    Should return a FAPI array only when using the options operation.
 */
function hook_node_convert_change($data, $op)
{
    // All of this is just an example.
    if ($op == 'insert') {
        if ($data['dest_node_type'] == 'book') {
            $book = array();
            $node = $data['node'];
            $book['link_path'] = 'node/' . $node->nid;
            $book['link_title'] = $node->title;
            $book['plid'] = 0;
            $book['menu_name'] = book_menu_name($node->nid);
            $mlid = menu_link_save($book);
            $book['bid'] = $data['hook_options']['bid'];
            if ($book['bid'] == 'self') {
                $book['bid'] = $node->nid;
            }
            $id = db_insert('book')->fields(array('nid' => $node->nid, 'mlid' => $book['mlid'], 'bid' => $book['bid']))->execute();
        }
        if ($data['dest_node_type'] == 'forum') {
            $id = db_insert('forum')->fields(array('tid' => $data['hook_options']['forum'], 'vid' => $data['node']->vid, 'nid' => $data['node']->nid))->execute();
            $id = db_insert('taxonomy_term_node')->fields(array('tid' => $data['hook_options']['forum'], 'vid' => $data['node']->vid, 'nid' => $data['node']->nid))->execute();
        }
    } elseif ($op == 'delete') {
        if ($data['node']->type == 'book') {
            menu_link_delete($data['node']->book['mlid']);
            db_delete('book')->condition('mlid', $data['node']->book['mlid'])->execute();
        }
        if ($data['node']->type == 'forum') {
            db_delete('forum')->condition('nid', $data['node']->nid)->execute();
            db_delete('taxonomy_term_node')->condition('nid', $data['node']->nid)->execute();
        }
    } elseif ($op == 'options') {
        $form = array();
        if ($data['dest_node_type'] == 'book') {
            foreach (book_get_books() as $book) {
                $options[$book['nid']] = $book['title'];
            }
            $options = array('self' => '<' . t('create a new book') . '>') + $options;
            $form['bid'] = array('#type' => 'select', '#title' => t('Book'), '#options' => $options, '#description' => t('Your page will be a part of the selected book.'), '#attributes' => array('class' => 'book-title-select'));
        }
        if ($data['dest_node_type'] == 'forum') {
            $vid = variable_get('forum_nav_vocabulary', '');
            $form['forum'] = taxonomy_form($vid);
            $form['forum']['#weight'] = 7;
            $form['forum']['#required'] = TRUE;
            $form['forum']['#options'][''] = t('- Please choose -');
        }
        return $form;
    } elseif ($op == 'options validate') {
        $form_state = $data['form_state'];
        if ($data['dest_node_type'] == 'forum') {
            $containers = variable_get('forum_containers', array());
            $term = $form_state['values']['hook_options']['forum'];
            if (in_array($term, $containers)) {
                $term = taxonomy_term_load($term);
                form_set_error('hook_options][forum', t('The item %forum is only a container for forums. Please select one of the forums below it.', array('%forum' => $term->name)));
            }
        }
    }
}
Example #9
0
 /**
  * Write the values into the database.
  * Return 0 if there was an error, else 1.
  */
 function updateDatabase($form, $myvalues)
 {
     //Try to create the record now
     $nSiteID = $this->m_oContext->getSiteID();
     $nIEN = $myvalues['tid'];
     $nUID = $this->m_oContext->getUID();
     $sCWFS = $this->m_oTT->getTicketWorkflowState($nSiteID . '-' . $nIEN);
     $updated_dt = date("Y-m-d H:i:s", time());
     if ($myvalues['reason'] == 'Other' && (!isset($myvalues['suspend_notes_tx']) || trim($myvalues['suspend_notes_tx']) == '')) {
         form_set_error('suspend_notes_tx', 'Cannot suspend a ticket without an explanation when reason is "Other".');
         return 0;
     }
     //Create the raptor_ticket_suspend_notes record now
     try {
         $oInsert = db_insert('raptor_ticket_suspend_notes')->fields(array('siteid' => $nSiteID, 'IEN' => $nIEN, 'notes_tx' => 'REASON:' . $myvalues['reason'] . '<br>NOTES:' . $myvalues['suspend_notes_tx'], 'author_uid' => $nUID, 'created_dt' => $updated_dt))->execute();
     } catch (\Exception $e) {
         error_log('Failed to create raptor_ticket_suspend_notes: ' . $e . "\nDetails..." . print_r($oInsert, true));
         form_set_error('suspend_notes_tx', 'Failed to save notes for this ticket!');
         return 0;
     }
     $sNewWFS = 'IA';
     $this->m_oTT->setTicketWorkflowState($nSiteID . '-' . $nIEN, $nUID, $sNewWFS, $sCWFS, $updated_dt);
     //Write success message
     drupal_set_message('Suspended ' . $myvalues['tid'] . ' (' . $myvalues['procName'] . ')');
     return 1;
 }
Example #10
0
 public function addToUser($postData, $user_id)
 {
     $postData['datetime'] = date("Y-m-d H:i:s");
     $postData['user_id'] = $user_id;
     // var_dump($postData);die();
     return db_insert($this->table, $postData);
 }
 /**
  * called by $this->store() after storing $this->values in the database
  * can be used to update additional tables, call scripts etc.
  */
 protected function storemore()
 {
     if ($this->new && $this->values['default_aliases']) {
         foreach (Config::read('default_aliases') as $address => $goto) {
             $address = $address . "@" . $this->id;
             # if $goto doesn't contain @, let the alias point to the same domain
             if (!strstr($goto, '@')) {
                 $goto = $goto . "@" . $this->id;
             }
             # TODO: use AliasHandler->add instead of writing directly to the alias table
             $arr = array('address' => $address, 'goto' => $goto, 'domain' => $this->id);
             $result = db_insert('alias', $arr);
             # TODO: error checking
         }
     }
     if ($this->new) {
         if (!$this->domain_postcreation()) {
             $this->errormsg[] = Config::lang('domain_postcreate_failed');
         }
     } else {
         # we don't have domain_postedit()
     }
     return true;
     # TODO: don't hardcode
 }
Example #12
0
 function addComment($props)
 {
     if (!$props) {
         drupal_set_message(t('Insert requested with empty (filtered) data set'), 'error');
         return false;
     }
     //global $user;
     $txn = db_transaction();
     try {
         //$uid = $user->uid;
         //$props['author'] = $uid;
         $now = new DateTime();
         $props['date_posted'] = $now->format('Y-m-d H:i:s');
         // check for top level posts with an empty parent & set it to mysql null.
         if (!isset($props['parent_id']) || empty($props['parent_id'])) {
             $props['parent_id'] = null;
         }
         $result = FALSE;
         $query = db_insert(tableName('comment'))->fields($props);
         $id = $query->execute();
         if ($id) {
             $result = $id;
         } else {
             drupal_set_message(t('We could not add your comment'), 'error');
         }
     } catch (Exception $ex) {
         $txn->rollback();
         drupal_set_message(t('We could not add your comment. ') . (_DEBUG ? $ex->__toString() : ''), 'error');
     }
     return $result;
 }
Example #13
0
 public function createInvoice($user_id = NULL)
 {
     $response = array();
     if (isset($user_id) && $user_id > 0) {
         $user_storage = \Drupal::entityManager()->getStorage('user');
         $user = $user_storage->load($user_id);
         $total_price = 0;
         $total_quantity = 0;
         if (isset($user)) {
             // insert new invoice
             $fields = array('user_id' => $user_id, 'total_quantity' => 0, 'total_price' => 0, 'date' => time(), 'note' => '');
             $invoice_id = db_insert('invoice')->fields($fields)->execute();
             // create relationship between invoice and purchased products of customer
             $fields = array('invoice_id' => $invoice_id);
             db_update('product_user_relationship')->condition('user_id', $user_id)->condition('status', 1)->isNull('invoice_id')->fields($fields)->execute();
             // update total_price and total_quantity
             $rows = db_select('product_user_relationship', 'e')->condition('invoice_id', $invoice_id)->fields('e', array('total_price', ' quantity'))->execute()->fetchAll();
             foreach ($rows as $row) {
                 $total_price += $row->total_price;
                 $total_quantity += $row->quantity;
             }
             // re-update invoice: total price, total quantity
             $fields = array('total_price' => $total_price, 'total_quantity' => $total_quantity);
             db_update('invoice')->condition('id', $invoice_id)->fields($fields)->execute();
             $response = array('success' => true, 'message' => $this->t('Create successfully.'));
         }
     }
     return new JsonResponse($response);
 }
Example #14
0
/**
 * プロフィールの登録
 *
 * @param array $queries
 * @param array $options
 *
 * @return resource
 */
function insert_profiles($queries, $options = array())
{
    $queries = db_placeholder($queries);
    // 初期値を取得
    $defaults = default_profiles();
    if (isset($queries['values']['created'])) {
        if ($queries['values']['created'] === false) {
            unset($queries['values']['created']);
        }
    } else {
        $queries['values']['created'] = $defaults['created'];
    }
    if (isset($queries['values']['modified'])) {
        if ($queries['values']['modified'] === false) {
            unset($queries['values']['modified']);
        }
    } else {
        $queries['values']['modified'] = $defaults['modified'];
    }
    // データを登録
    $queries['insert_into'] = DATABASE_PREFIX . 'profiles';
    $resource = db_insert($queries);
    if (!$resource) {
        return $resource;
    }
    return $resource;
}
function _tranCrear($oid)
{
    $data = array("id_orden" => $oid);
    $query = db_insert("todopago_transaccion");
    $query->fields($data)->execute();
    return _tranEstado($oid);
}
function dexp_layerslider_clone($slideid)
{
    $slide = db_select('{dexp_layerslider}', 'd')->fields('d')->condition('id', $slideid, '=')->execute()->fetchAssoc();
    db_insert("{dexp_layerslider}")->fields(array('name' => "Copy of " . $slide['name'], 'settings' => $slide['settings'], 'data' => $slide['data']))->execute();
    drupal_set_message("Successfully cloned.");
    drupal_goto('admin/dexp_layerslider');
}
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $category = $form_state->getValue('category');
     $header_bg = $form_state->getValue('header_bg')[0];
     $fid = $form_state->getValue('header_bg')[0];
     $filename = db_select('file_managed', 'f')->condition('f.fid', $fid, '=')->fields('f', array('filename'))->execute()->fetchField();
     $data = db_select('file_managed', 'f')->condition('f.fid', $fid, '=')->fields('f', array('uri'))->execute()->fetchField();
     $config = $this->config('amazons.settings');
     $AccessKeyId = $config->get('AccessKeyId');
     $SecretAccessKey = $config->get('SecretAccessKey');
     $region = $config->get('region');
     $bucket = $config->get('bucketname');
     $s3Client = new \Aws\S3\S3Client(['version' => 'latest', 'region' => $region, 'credentials' => ['key' => $AccessKeyId, 'secret' => $SecretAccessKey]]);
     //Creating bucket dynamically
     // $result1 = $s3Client->createBucket(array('Bucket' => 'mybucket'));
     //
     // echo "<pre>";
     // print_r($result1);
     // exit;
     //$bucket = 'ncdfiles';
     $key = date('ymdhis') . time() . $filename;
     //$data = 'public://ncdfiles/' . $filename;
     $result = $s3Client->putObject(array('Bucket' => $bucket, 'Key' => $key, 'SourceFile' => $data, 'ACL' => 'public-read'));
     db_insert('amazon_s3_data')->fields(array('cat_name' => $category, 'file_path' => $result['ObjectURL'], 'fid' => $fid))->execute();
     drupal_set_message('File uploaded to AWS server');
     return;
 }
 /**
  * Tests the handlers.
  */
 public function testHandlers()
 {
     $nodes = array();
     $nodes[] = $this->drupalCreateNode();
     $nodes[] = $this->drupalCreateNode();
     $account = $this->drupalCreateUser();
     $this->drupalLogin($account);
     \Drupal::currentUser()->setAccount($account);
     db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute();
     db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute();
     $column_map = array('nid' => 'nid');
     // Test the history field.
     $view = Views::getView('test_history');
     $view->setDisplay('page_1');
     $this->executeView($view);
     $this->assertEqual(count($view->result), 2);
     $output = $view->preview();
     $this->setRawContent(\Drupal::service('renderer')->renderRoot($output));
     $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker'));
     $this->assertEqual(count($result), 1, 'Just one node is marked as new');
     // Test the history filter.
     $view = Views::getView('test_history');
     $view->setDisplay('page_2');
     $this->executeView($view);
     $this->assertEqual(count($view->result), 1);
     $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map);
 }
Example #19
0
 /**
  * Save all points of the collection
  */
 public function save()
 {
     $ins_query = db_insert('prod_rrd')->fields(array('prs_id', 'pr_timestamp', 'pr_value', 'pr_value_max', 'pr_value_min', 'pr_rrd_index', 'pr_aggregate_level'));
     foreach ($this->points as $point) {
         if ($point->isNew()) {
             $record = array();
             // remap
             $record['prs_id'] = $this->getRRDId();
             $record['pr_timestamp'] = $point->getTimestamp();
             // the value is transformed in the point to allow
             // storage of decimals as ints
             $record['pr_value'] = $point->getValue();
             $record['pr_value_max'] = $point->getMaxValue();
             $record['pr_value_min'] = $point->getMinValue();
             $record['pr_rrd_index'] = $point->getIndex();
             $record['pr_aggregate_level'] = $point->getAggregateLevel();
             $ins_query->values($record);
         } else {
             $update_query = db_update('prod_rrd')->fields(array('pr_timestamp' => $point->getTimestamp(), 'pr_value' => $point->getValue(), 'pr_value_max' => $point->getMaxValue(), 'pr_value_min' => $point->getMinValue()))->condition('prs_id', $this->getRRDId())->condition('pr_rrd_index', $point->getIndex())->condition('pr_aggregate_level', $point->getAggregateLevel());
             $update_query->execute();
         }
     }
     // we always have at least 1 insert
     $ins_query->execute();
 }
Example #20
0
 /**
  * called by $this->store() after storing $this->values in the database
  * can be used to update additional tables, call scripts etc.
  */
 protected function storemore()
 {
     # store list of allowed domains in the domain_admins table
     if (isset($this->values['domains'])) {
         if (is_array($this->values['domains'])) {
             $domains = $this->values['domains'];
         } elseif ($this->values['domains'] == '') {
             $domains = array();
         } else {
             $domains = explode(',', $this->values['domains']);
         }
         db_delete('domain_admins', 'username', $this->id, "AND domain != 'ALL'");
         foreach ($domains as $domain) {
             $values = array('username' => $this->id, 'domain' => $domain);
             db_insert('domain_admins', $values, array('created'));
             # TODO: check for errors
         }
     }
     # Temporary workaround to keep the database compatible with 2.3.x
     if (isset($this->values['superadmin'])) {
         if ($this->values['superadmin'] == 1) {
             $values = array('username' => $this->id, 'domain' => 'ALL');
             $where = db_where_clause(array('username' => $this->id, 'domain' => 'ALL'), $this->struct);
             $result = db_query("SELECT username from " . table_by_key('domain_admins') . " " . $where);
             if ($result['rows'] == 0) {
                 db_insert('domain_admins', $values, array('created'));
                 # TODO: check for errors
             }
         } else {
             db_delete('domain_admins', 'username', $this->id, "AND domain = 'ALL'");
         }
     }
     return true;
     # TODO: don't hardcode
 }
function flickr_backups_create(&$user, $type_id)
{
    $now = time();
    $backup = array('user_id' => $user['id'], 'type_id' => $type_id, 'date_created' => $now);
    $hash = array();
    foreach ($backup as $k => $v) {
        $hash[$k] = AddSlashes($v);
    }
    $rsp = db_insert('FlickrBackups', $hash);
    if ($rsp['ok']) {
        $rsp['backup'] = $backup;
    } else {
        if ($rsp['error_code'] == 1062) {
            $map = flickr_backups_type_map();
            $backups = flickr_backups_for_user($user, $type_id);
            $rsp = okay(array('backup' => $backups[$map[$type_id]]));
        } else {
        }
    }
    if ($rsp['ok']) {
        $enabled = $rsp['backup']['disabled'] ? 0 : 1;
        $push_rsp = flickr_backups_toggle_push_subscription($rsp['backup'], $enabled);
        $rsp['push_backup'] = $push_rsp;
    }
    return $rsp;
}
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     uc_payment_enter($form_state->getValue('order_id'), 'check', $form_state->getValue('amount'), $this->currentUser()->id(), '', $form_state->getValue('comment'));
     db_insert('uc_payment_check')->fields(array('order_id' => $form_state->getValue('order_id'), 'clear_date' => mktime(12, 0, 0, $form_state->getValue('clear_month'), $form_state->getValue('clear_day'), $form_state->getValue('clear_year'))))->execute();
     drupal_set_message($this->t('Check received, expected clear date of @date.', ['@date' => uc_date_format($form_state->getValue('clear_month'), $form_state->getValue('clear_day'), $form_state->getValue('clear_year'))]));
     $form_state->setRedirect('uc_order.admin_view', ['uc_order' => $form_state->getValue('order_id')]);
 }
 /**
  * Function to insert records into the checkbook_api table
  *
  * @param CheckbookAPIEntity $checkbookAPI
  * @return mixed
  */
 public function insertCheckbookAPI(CheckbookAPIEntity $checkbookAPI)
 {
     // Remove any null properties
     $fields = array_filter((array) $checkbookAPI);
     $api_id = db_insert('checkbook_api')->fields($fields)->execute();
     return self::getCheckbookAPI($api_id);
 }
Example #24
0
 /**
  * Tests the handlers.
  */
 public function testHandlers()
 {
     $nodes = array();
     $nodes[] = $this->drupalCreateNode();
     $nodes[] = $this->drupalCreateNode();
     $account = $this->drupalCreateUser();
     $this->drupalLogin($account);
     \Drupal::currentUser()->setAccount($account);
     db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute();
     db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute();
     $column_map = array('nid' => 'nid');
     // Test the history field.
     $view = Views::getView('test_history');
     $view->setDisplay('page_1');
     $this->executeView($view);
     $this->assertEqual(count($view->result), 2);
     $output = $view->preview();
     $this->setRawContent(\Drupal::service('renderer')->renderRoot($output));
     $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker'));
     $this->assertEqual(count($result), 1, 'Just one node is marked as new');
     // Test the history filter.
     $view = Views::getView('test_history');
     $view->setDisplay('page_2');
     $this->executeView($view);
     $this->assertEqual(count($view->result), 1);
     $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map);
     // Install Comment module and make sure that content types without comment
     // field will not break the view.
     // See \Drupal\history\Plugin\views\filter\HistoryUserTimestamp::query()
     \Drupal::service('module_installer')->install(['comment']);
     $view = Views::getView('test_history');
     $view->setDisplay('page_2');
     $this->executeView($view);
 }
Example #25
0
 /**
  * Confirms that we can update two blob columns in the same table.
  */
 function testUpdateMultipleBlob()
 {
     $id = db_insert('test_two_blobs')->fields(array('blob1' => 'This is', 'blob2' => 'a test'))->execute();
     db_update('test_two_blobs')->condition('id', $id)->fields(array('blob1' => 'and so', 'blob2' => 'is this'))->execute();
     $r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
     $this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', 'Can update multiple blobs per row.');
 }
Example #26
0
function store_file($challenge_id, $file)
{
    if ($file['error']) {
        message_error('Could not upload file: ' . file_upload_error_description($file['error']));
    }
    if ($file['size'] > max_file_upload_size()) {
        message_error('File too large.');
    }
    $file_id = db_insert('files', array('added' => time(), 'added_by' => $_SESSION['id'], 'title' => $file['name'], 'size' => $file['size'], 'challenge' => $challenge_id));
    if (file_exists(CONFIG_PATH_FILE_UPLOAD . $file_id)) {
        message_error('File already existed! This should never happen!');
    }
    // do we put the file on AWS S3?
    if (CONFIG_AWS_S3_KEY_ID && CONFIG_AWS_S3_SECRET && CONFIG_AWS_S3_BUCKET) {
        try {
            // Instantiate the S3 client with your AWS credentials
            $client = S3Client::factory(array('key' => CONFIG_AWS_S3_KEY_ID, 'secret' => CONFIG_AWS_S3_SECRET));
            $file_key = '/challenges/' . $file_id;
            // Upload an object by streaming the contents of a file
            $result = $client->putObject(array('Bucket' => CONFIG_AWS_S3_BUCKET, 'Key' => $file_key, 'SourceFile' => $file['tmp_name']));
            // We can poll the object until it is accessible
            $client->waitUntil('ObjectExists', array('Bucket' => CONFIG_AWS_S3_BUCKET, 'Key' => $file_key));
        } catch (Exception $e) {
            message_error('Caught exception uploading file to S3: ' . $e->getMessage());
        }
    } else {
        move_uploaded_file($file['tmp_name'], CONFIG_PATH_FILE_UPLOAD . $file_id);
        if (!file_exists(CONFIG_PATH_FILE_UPLOAD . $file_id)) {
            delete_file($file_id);
            message_error('File upload failed!');
        }
    }
}
Example #27
0
 public static function create($title, $extension, $size, $userid, $width, $height)
 {
     $hash = hash_random();
     $id = db_insert('photos', compact('title', 'extension', 'size', 'userid', 'hash', 'width', 'height'));
     assert($id > 0);
     return array('id' => $id, 'filename' => $id . '-' . $hash . '.' . $extension);
 }
/**
 * Respond to creation of a new fieldable panels pane.
 *
 * @param $panels_pane
 *   The fieldable that is being created.
 *
 * @ingroup fieldable_panels_pane_api_hooks
 */
function hook_fieldable_panels_pane_insert($panels_pane) {
  db_insert('mytable')
    ->fields(array(
      'fpid' => $panels_pane->fpid,
      'vid' => $panels_pane->vid,
    ))
    ->execute();
}
Example #29
0
 /**
  * Ensures that non-ASCII UTF-8 data is stored in the database properly.
  */
 function testRegression_310447()
 {
     // That's a 255 character UTF-8 string.
     $name = str_repeat("é", 255);
     db_insert('test')->fields(array('name' => $name, 'age' => 20, 'job' => 'Dancer'))->execute();
     $from_database = db_query('SELECT name FROM {test} WHERE name = :name', array(':name' => $name))->fetchField();
     $this->assertIdentical($name, $from_database, 'The database handles UTF-8 characters cleanly.');
 }
Example #30
0
 function new_cheatsheet()
 {
     if ($_POST) {
         $_POST['user_id'] = $this->user->id;
         db_insert('cs_cheatsheet', $_POST);
     }
     $this->tpl->view('cheatsheet/cheatsheet_new');
 }