/** * (non-PHPdoc) * @see AbstractCallback::getListeUser() * * Fonction pour récupérer tous les utilisateurs ADEFIM * */ public function getListeUser() { $users = array(); db_set_active(); $rids = array ( 8, // CONSEILLER ADEFIM 9, // DIRECTEUR ADEFIM 10, // GESTIONNAIRE ADEFIM 12, // REFERENT ADEFIM ); $query = db_select('users_roles', 'ur') ->fields('ur', array('uid')) ->condition('rid', $rids, 'IN'); $results = $query->execute()->fetchAll(); foreach ($results as $result) { $users[] = $result->uid; } $users = array_unique($users); return $users; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeDestinataireMail() */ public function getListeDestinataireMail() { $destinataires = array(); db_set_active(@DB_EXTRANET); $query = db_select('user_responsable', 'ur'); $query->join('user_entreprise', 'ue', 'ue.id_user_responsable = ur.id'); $query->join('drupal_user', 'du', 'ue.id_drupal_user = du.id'); $query->fields('ur'); $query->condition('du.id_user_drupal' , $this->param->id_user, '='); $query->range(0,1); $result = $query->execute()->fetchAssoc(); db_set_active(); $destinataires[] = array( 'email' => $result['email'], 'name' => trim($result['prenom']) . ' ' . trim($result['nom']) ); return $destinataires; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeUser() * * Fonction pour récupérer tous les utilisateurs OPCAIM * */ public function getListeUser() { $users = array(); db_set_active(); $rids = array ( 6, // ADMIN OPCAIM 13 // SUPER ADMIN OPCAIM ); $query = db_select('users_roles', 'ur') ->fields('ur', array('uid')) ->condition('rid', $rids, 'IN'); $results = $query->execute()->fetchAll(); foreach ($results as $result) { $users[] = $result->uid; } $users = array_unique($users); return $users; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeUser() * * Fonction pour récupérer Les utilisateurs et leurs mails * des ADEFIM rattachées rattachées aux entreprise * */ public function getListeDestinataireMail() { $destinataires = array(); $id_entreprises = $this->param->id_entreprises; $id_adefims = array(); foreach ($id_entreprises as $id_entreprise) { $id_adefims[] = shared_get_id_adefim_from_id_entreprise($id_entreprise); } db_set_active(@DB_SLAVE); $query = db_select('v_comptes_adefims', 'ca'); $query->fields('ca'); $query->condition('id_adefim', $id_adefims, 'IN'); $result = $query->execute(); $comptes_adefim = $result->fetchAll(); db_set_active(); foreach ($comptes_adefim as $compte_adefim) { $destinataires[] = array( 'email' => $compte_adefim->email, 'name' => trim($compte_adefim->prenom) . ' ' . trim($compte_adefim->nom) ); } return $destinataires; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeDestinataireMail() */ public function getListeDestinataireMail() { $destinataires = array(); if (isset($this->param->id_user)) { db_set_active(@DB_EXTRANET); $query = db_select('drupal_user', 'du'); $query->fields('du'); $query->condition('du.id_user_drupal' , $this->param->id_user, '='); $query->range(0,1); $result = $query->execute()->fetchAssoc(); db_set_active(); if ($result) { $destinataires[] = array( 'email' => $result['mail'], 'name' => trim($result['first_name']) . ' ' . trim($result['last_name']) ); } } else { // dans le cas d'un utilisateur supprimé $destinataires[] = array( 'email' => $this->param->email, 'name' => $this->param->name ); } return $destinataires; }
/** @brief Switch to the object's database if necessary. **/ public function switch_to_db() { // There is no extra database specified, which means we never change db. if (self::db() == '') { return; } db_set_active(self::db()); }
function page_fast_cache() { if ($this->fast_cache === TRUE) { require_once './includes/database.inc'; db_set_active(); } return $this->fast_cache; }
/** * {@inheritdoc} */ protected function connect() { try { // This doesn't actually test the connection. db_set_active(); // Now actually do a check. Database::getConnection(); $this->pass('Drupal can CONNECT to the database ok.'); } catch (\Exception $e) { // Attempt to create the database if it is not found. if ($e->getCode() == Connection::DATABASE_NOT_FOUND) { // Remove the database string from connection info. $connection_info = Database::getConnectionInfo(); $database = $connection_info['default']['database']; unset($connection_info['default']['database']); // In order to change the Database::$databaseInfo array, need to remove // the active connection, then re-add it with the new info. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $connection_info['default']); try { // Now, attempt the connection again; if it's successful, attempt to // create the database. Database::getConnection()->createDatabase($database); Database::closeConnection(); // Now, restore the database config. Database::removeConnection('default'); $connection_info['default']['database'] = $database; Database::addConnectionInfo('default', 'default', $connection_info['default']); // Check the database connection. Database::getConnection(); $this->pass('Drupal can CONNECT to the database ok.'); } catch (DatabaseNotFoundException $e) { // Still no dice; probably a permission issue. Raise the error to the // installer. $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage()))); return FALSE; } catch (\PDOException $e) { // Still no dice; probably a permission issue. Raise the error to the // installer. $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage()))); return FALSE; } } else { // Database connection failed for some other reason than the database // not existing. $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage()))); return FALSE; } } return TRUE; }
function wyc_import_ratings($member_number = '') { db_set_active('wyc_import_database'); //SELECT * FROM wyc_production.wyc_ratings r JOIN wyc_production.wycdatabase d ON r.member=d.WYCNumber ORDER BY r.date ASC /*$query = db_select('wyc_ratings', 'r'); $query->join('wycdatabase', 'd', 'r.member=d.WYCNumber'); $query ->fields('r')->fields('d') ->range(0, 100) ->orderBy('d.WYCNumber', 'DESC') ->orderBy('r.date', 'ASC'); if($member_number) { $query->condition('r.member', $member_number); }*/ // get all their ratings added that day // SELECT GROUP_CONCAT(r.rating SEPARATOR '|') as d_ratings, r.*, d.* ". // "FROM wyc_production.wyc_ratings r ". // "LEFT JOIN wyc_production.wycdatabase d ON r.member=d.WYCNumber ". // "GROUP BY d.WYCNumber, r.examiner, r.date ". // "ORDER BY r.member # db_set_active(); $query = db_select('wyc_ratings_import_cache', 'r'); $query->fields('r')->condition('r.ratings_cache', '', '='); //->range(0, 100); $results = $query->execute(); $drupal_users = $uids = array(); while ($data = $results->fetchAssoc()) { print "\n\nFOUND RATINGS....\n" . json_encode($data); flush(); list($rid, $rating_rating, $drupal_uid, $ratings_member, $rating_date, $rating_examiner, $ratings_comment) = array($data['id'], explode('|', $data['ratings']), $data['drupal_member'], $data['ratings_member'], $data['ratings_date'], $data['ratings_examiner'], $data['ratings_comment']); // cache ids if (empty($uids[$ratings_member])) { $uids[$ratings_member] = wyc_get_uid_by_wycnumber($ratings_member); } if (empty($uids[$rating_examiner])) { $uids[$rating_examiner] = wyc_get_uid_by_wycnumber($rating_examiner); } // cache users if (empty($ratings_member) || empty($drupal_users[$ratings_member]->uid)) { $id = $drupal_uid ? $drupal_uid : $uids[$ratings_member]; $drupal_user = user_load($id); $drupal_users[$ratings_member] = $drupal_user; } if (empty($drupal_user->uid)) { wyc_log('wyc_ratings_missing_user', $data, WATCHDOG_ERROR); } else { wyc_log('wyc_ratings_adding_ratings', $users[$ratings_member]->uid, WATCHDOG_NOTICE); wyc_add_rating($rid, $drupal_user, $ratings_member, $rating_date, $rating_rating, $uids[$rating_examiner], $ratings_comment); } } }
function get_data1d($lakeid, $variable) { $sqlstatement = get_sql_query($lakeid, $variable); db_set_active('dbmaker'); $result = db_query($sqlstatement); //Initialize arrays $idx = 0; $Dates = array(); $Values = array(); foreach ($result as $row) { $Dates[$idx] = $row->sampledate; $Values[$idx++] = $row->{$variable}; } db_set_active('default'); $GLOBALS['numsamps'] = $idx; $GLOBALS['Dates'] = $Dates; $GLOBALS['Values'] = $Values; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeUser() * * Fonction pour récupérer l'utilisateur ayant créé la DGF * */ public function getListeUser() { $users = array(); db_set_active(@DB_EXTRANET); $query = db_select('dgf', 'd') ->fields('d', array('id_user_creation')) ->condition('id', $this->param, '='); $results = $query->execute()->fetchAssoc(); $users[] = $results['id_user_creation']; db_set_active(); return $users; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeUser() * * Fonction pour récupérer Le référent (et Directeur si différent) * de l’ADEFIM rattachée * */ public function getListeUser() { $users = array(); $id_entreprises = $this->param->id_entreprises; db_set_active(@DB_EXTRANET); $query = db_select('user_entreprise', 'ue'); $query->join('lien_user_entreprise_ref_esclave_entreprise', 'luee', 'luee.id_user_entreprise = ue.id'); $query->join('drupal_user', 'du', 'ue.id_drupal_user = du.id'); $query->fields('du', array('id_user_drupal')); $query->condition('luee.est_actif' , 1, '='); //filtre par entreprise $query->condition('luee.id_ref_esclave_entreprise', $id_entreprises, 'IN'); $results = $query->execute()->fetchAll(); db_set_active(); foreach ($results as $result) { //chercher si l'utilisateur existe dans drupal $user = user_load($result->id_user_drupal); if ($user != false) { // Vérifier si l'utilisateur est ADMIN ENTREPISE (role 5) // @todo RESPONSABLE ENTREPISE if (user_has_role(5,$user)) { $users[] = $user->uid; } } } // Supprimer les doublons si plusieurs entreprises $users = array_unique($users); return $users; }
/** * (non-PHPdoc) * @see AbstractCallback::getListeUser() * * Fonction pour récupérer Le référent (et Directeur si différent) * de l’ADEFIM rattachée à partir de la liste d'ID Entreprise * */ public function getListeUser() { $users = array(); $ids_entreprise = $this->param->id_entreprises; db_set_active(@DB_SLAVE); $query = db_select('comptes_adefims', 'ca'); $query->join('fonctions_adefims', 'fa', 'ca.id_fonction_adefim = fa.id'); $query->join('adefims', 'a', 'ca.id_adefim = a.id'); $query->join('v_adefims_entreprise', 'lae', 'lae.id_adefim = a.id'); $query->join('entreprises', 'e', 'lae.id_entreprise = e.id'); $query->fields('ca', array('id','nom_utilisateur')); $query->condition('a.est_actif' , 1, '='); $query->condition('ca.est_actif' , 1, '='); //filtre par entreprise $query->condition('e.id', $ids_entreprise, 'IN'); //filtre par fonction Directeur et Référent $query->condition('fa.id' , array('I.1','I.3'), 'IN'); $results = $query->execute()->fetchAll(); db_set_active(); //Récupération des uid des users Adefim depuis drupal foreach ($results as $user_adefim) { $user = user_load_by_name(rtrim($user_adefim->nom_utilisateur)); if ($user != false) { $users[] = $user->uid; } } // Supprimer les doublons si plusieurs entreprises $users = array_unique($users); return $users; }
function getSyslog($limit = FALSE, $start = FALSE) { global $priorities; $sql = 'SELECT * FROM (' . ' SELECT' . ' id,' . ' DATE_PART(\'epoch\', devicereportedtime) AS time,' . ' priority AS priority_id,' . ' message,' . ' syslogtag AS service' . ' FROM systemevents' . ' WHERE facility = ?'; $params = array(SYSLOG_MAIL); if ($start) { $sql .= ' AND id > ?'; $params[] = $start; } $sql .= ' ORDER BY id DESC'; if ($limit) { $sql .= ' LIMIT ?'; $params[] = $limit; } $sql .= ') AS LOG' . ' ORDER BY id'; db_set_active('logs'); $rows = db_getrows($sql, $params); db_set_active('default'); if (!$rows) { return FALSE; } $i = 0; foreach ($rows as $row) { $pid = null; $service = str_replace(':', '', $row['service']); if (preg_match('/^(.*)\\[(.*)\\]$/', $service, $matches)) { $service = $matches[1]; $pid = $matches[2]; } $rows[$i]['pid'] = $pid; $rows[$i]['service'] = $service; $message = htmlspecialchars($row['message']); $rows[$i]['message'] = $message; $i++; } return $rows; }
/** * Check if we can connect to the database. */ protected function connect() { try { // This doesn't actually test the connection. db_set_active(); // Now actually do a check. Database::getConnection(); $this->pass('Drupal can CONNECT to the database ok.'); } catch (\Exception $e) { $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage()))); return FALSE; } return TRUE; }
function _collclaim_del_author($uid) { //dbug_message('my delete'); try { db_set_active(CLAIM_DB); // Use claim database if (db_table_exists(CLAIM_AUTHOR)) { db_delete(CLAIM_AUTHOR)->condition('uid', $uid)->execute(); } } catch (Exception $e) { drupal_set_message('_collclaim_del_author(): ' . $e->getMessage()); } db_set_active(); // delete releated claimed collection _collclaim_del_claim_by_uid($uid); }
/** * Check locked state for multiple jobs. * * This has yet to be optimized. */ public function isLockedMultiple($jobs) { $handles = array(); foreach ($jobs as $job) { $handles[] = 'uc-' . $job->name; } try { $old_db = db_set_active('background_process'); $processes = db_select('background_process', 'bp')->fields('bp', array('handle', 'args'))->condition('handle', $handles, 'IN')->execute()->fetchAllAssoc('handle', PDO::FETCH_OBJ); db_set_active($old_db); } catch (Throwable $e) { db_set_active($old_db); throw $e; } catch (Exception $e) { db_set_active($old_db); throw $e; } $lock_ids = array(); foreach ($jobs as $job) { $lock_ids[$job->name] = FALSE; if (isset($processes['uc-' . $job->name])) { $process = $processes['uc-' . $job->name]; $process->args = unserialize($process->args); $lock_ids[$job->name] = $process->args[1]; } } return $lock_ids; }
function delete_claim_by_id($claim_id) { $claim = get_claim_by_id($claim_id); //dbug_message($claim); if (!empty($claim)) { if ($claim['verified'] == 1) { // the verified claim if (has_verified_claims_of_a_collection($claim['cid']) == 1) { // only 1 verified claim of a collection // make collection's copyright status uncertain. if (_make_collection_copyright_unknown($claim['cid'])) { bg_index(); } } } } else { return false; } db_set_active(CLAIM_DB); if (!db_table_exists(CLAIM_COLL)) { db_set_active(); return false; } $num_deleted = db_delete(CLAIM_COLL)->condition('id', $claim_id)->execute(); db_set_active(); if (empty($num_deleted)) { return false; } else { return true; } }
public function execute($callback, $args = array()) { $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); $this->connection = FALSE; $this->determineServiceHost(); return $this->dispatch(); }
<?php /*! * qwp: https://github.com/steem/qwp * * Copyright (c) 2015 Steem * Released under the MIT license */ require_once DRUPAL_DB_ROOT . '/database.inc'; global $QWP_ACTIVE_DB; if (isset($QWP_ACTIVE_DB)) { db_set_active($QWP_ACTIVE_DB); } function qwp_db_try_connect_db() { try { db_query('select version()')->execute(); } catch (PDOException $e) { log_db_exception($e, "try_connect_db"); db_remove_active(); } } function qwp_db_and_from_array(&$ids, $field = 'id', $op = '=') { $ret = '('; $sep = ''; foreach ($ids as &$id) { $ret .= $sep . "{$field}{$op}'{$id}'"; if (!$sep) { $sep = ' and '; }
} else { _stored_passwords_help(); } /** * Make sure realm is set. */ $uname = posix_uname(); $edit['realm'] = isset($edit['realm']) ? $edit['realm'] : $uname['nodename']; /** * Open a database connection. */ $cwd = getcwd(); chdir($drupal); require "./includes/bootstrap.inc"; require_once "./includes/database.inc"; db_set_active(); chdir($cwd); _securesite_schema(); /** * Execute command. */ _stored_passwords_manage($edit); /** * Work with stored passwords. * @param $edit * An array of data with the following keys: * - username: User name * - realm: Site realm * - pass: User password * - op: The operation to be performed. If none is given, an existing user will be updated. * @return
function get_waterTemps($lakeid) { $php_cur_year = 2015; if ($lakeid == 'SP') { //SP data $table_name = "sensor_sparkling_lake_watertemp_daily"; $php_depths = array(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18); $php_num_depths = 25; } else { if ($lakeid == 'TR') { //TR data $table_name = "sensor_trout_lake_russ_watertemp_daily"; $php_depths = array(0, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 20, 25, 30); $php_num_depths = 25; } } $sql_getdays = "(SELECT min(daynum) as minday, max(daynum) as maxday FROM `" . $table_name . "` where year4 = 2015)"; db_set_active('dbmaker'); $result = db_query($sql_getdays); foreach ($result as $row) { $php_min_day = $row->minday; $php_max_day = $row->maxday; } $php_numdays = $php_max_day - $php_min_day + 1; //Initialize the temps array to -1; null values to appear as white $php_dates = array(); $php_temps = array(); for ($col = 0; $col < $php_numdays; $col++) { for ($row = 0; $row < $php_num_depths; $row++) { $php_temps[$row][$col] = -1; } } //Loop days; build an sql query seperately for each day. for ($col = 0; $col < $php_numdays; $col++) { $curday = $php_min_day + $col; $sqlstatement = "(SELECT sampledate, depth, wtemp FROM `" . $table_name . "` where year4=2015 and daynum=" . $curday . ")"; $result = db_query($sqlstatement); foreach ($result as $row) { $php_dates[$col] = $row->sampledate; $depth = $row->depth; $wtemp = $row->wtemp; //Brute force way to order depths but doesn't require that depth order in the table remain constant. for ($i = 0; $i < $php_num_depths; $i++) { if ($depth == $php_depths[$i]) { $php_temps[$i][$col] = $wtemp; //2d array of [depths][days] } //if } //for $i } //foreach } //for $col db_set_active('default'); $GLOBALS['numdays'] = $php_numdays; $GLOBALS['numdepths'] = $php_num_depths; $GLOBALS['Depths'] = $php_depths; $GLOBALS['Temps'] = $php_temps; $GLOBALS['Dates'] = $php_dates; }
function makeDataSetInJS($qname, $qstr, $aoColumns = '', $ext = 'cte', $asObject = false, $append = false) { $isGdata = false; if (getURLParam("gdata") == $qname) { $isGdata = true; } //google.visualization.Query.setResponse({version:'0.6',reqId:'0',status:'ok',sig:'5982206968295329967',table:{cols:[{id:'Col1',label:'',type:'number'},{id:'Col2',label:'',type:'number'},{id:'Col3',label:'',type:'number'}],rows:[{c:[{v:1.0,f:'1'},{v:2.0,f:'2'},{v:3.0,f:'3'}]},{c:[{v:2.0,f:'2'},{v:3.0,f:'3'},{v:4.0,f:'4'}]},{c:[{v:3.0,f:'3'},{v:4.0,f:'4'},{v:5.0,f:'5'}]},{c:[{v:1.0,f:'1'},{v:2.0,f:'2'},{v:3.0,f:'3'}]}]}}); if (!isset($qstr)) { return ''; } if (!isset($qname)) { $qname = "data1"; } if (!isset($ext)) { $ext = "cte"; } db_set_active($ext); $q = db_query($qstr); $i = 0; $r = ""; $o = array(); //if $asObject is true then this object is returned instead of the string $r ... global $firstDataSet; $cols = array(); while ($rw = db_fetch_array($q)) { $newrw = array(); //temp holder of object data... //if r=='' then this is the first row... so set up the dataset and initialize cteReportTemplate if necessary... if ($r == "") { //firstDataSet is a global flag so that preliminaty js can be initialized... if ($firstDataSet) { $r = <<<EOF \t\t\t<script type='text/javascript'> \t\t\tvar popup; \t\t\tvar cteReportTemplate=dataSetObjects;</script> EOF; $firstDataSet = false; } $r .= "\t\t\t<script type='text/javascript'>\nif(!cteReportTemplate['{$qname}']) cteReportTemplate.newTable('{$qname}');"; $sep = ""; //set up fields... $rfn = "\n " . ($append ? "if(!cteReportTemplate.{$qname}.fields) " : "") . "cteReportTemplate.{$qname}.fields=["; if ($aoColumns) { $flds = json_decode($aoColumns); foreach ($flds as $fo) { if (is_object($fo) && $fo->field) { $tmprw = ""; $datakey = ""; reset($rw); if (array_key_exists($fo->field, $rw)) { $datakey = htmlspecialchars($fo->field); } else { reset($rw); foreach (array_keys($rw) as $rwk) { $tmprw .= $rwk . " :"; if (strtolower($rwk) == strtolower($fo->field)) { $datakey = htmlspecialchars($rwk); break; } } } if ($datakey) { $cols[] = $datakey; $rfn .= $sep . '{'; $fsep = ""; $fo->field = strtolower($fo->field); foreach ($fo as $fitem => $fval) { $rfn .= $fsep . '"' . $fitem . '":"' . htmlspecialchars($fval) . '"'; $fsep = ","; } $rfn .= '}'; $sep = ","; } else { drupal_set_message("Error, column key '{$fo->field}' not found in query data ({$tmprw})", 'error'); } } else { drupal_set_message("Error, key value missing field or otherwise not an object", 'error'); } } } else { foreach (array_keys($rw) as $f) { $rfn .= $sep . '{"sTitle":"' . htmlspecialchars($f) . '","field":"' . htmlspecialchars($f) . '"}'; $sep = ","; $cols[] = htmlspecialchars($f); } } $r .= $rfn; $r .= "];\n " . ($append ? "if(!cteReportTemplate.{$qname}.data) " : "") . "cteReportTemplate.{$qname}.data=[];\n//end if {$qname} already exists\n"; } //end if first roww setup ... $sep = ""; $r .= "cteReportTemplate.{$qname}.data.push(["; foreach ($cols as $fld) { $f = $rw[$fld]; $newrw[] = $f; $badChars = array("\r", "\n", "\\"); $r .= $sep . '"' . htmlspecialchars(str_replace($badChars, " ", $f)) . '"'; $sep = ","; } $r .= "]);\n"; $o[] = $newrw; //adds row into object $i++; } //end while... if ($i == 0) { $r = <<<EOF \t<script type='text/javascript'> \t\t//alert("No data found");;\t\t \t\tvar cteReportTemplate=this.dataSetObjects; \t\tif(!cteReportTemplate) cteReportTemplate=dataSetObjects; \t\tif(cteReportTemplate) cteReportTemplate.newTable("{$qname}"); \t\t/* {$qstr} */ EOF; } // if($i>400) $r=''.$r.' jQuery("#"+settings.bg_id).fadeOut("normal"); jQuery("#"+settings.main_id).fadeOut("normal");' //$r=str_replace("var popup;","$.popup.show('Data Loading', 'Please wait...');",$r)."\n $.popup.hide();"; $r .= "</script>"; db_set_active('default'); if ($asObject) { return $o; } else { return "" . $r . ""; } }
/** * {@inheritdoc} */ protected function connect() { try { // This doesn't actually test the connection. db_set_active(); // Now actually do a check. try { Database::getConnection(); } catch (\Exception $e) { // Detect utf8mb4 incompability. if ($e->getCode() == Connection::UNSUPPORTED_CHARSET || $e->getCode() == Connection::SQLSTATE_SYNTAX_ERROR && $e->errorInfo[1] == Connection::UNKNOWN_CHARSET) { $this->fail(t('Your MySQL server and PHP MySQL driver must support utf8mb4 character encoding. Make sure to use a database system that supports this (such as MySQL/MariaDB/Percona 5.5.3 and up), and that the utf8mb4 character set is compiled in. See the <a href=":documentation" target="_blank">MySQL documentation</a> for more information.', array(':documentation' => 'https://dev.mysql.com/doc/refman/5.0/en/cannot-initialize-character-set.html'))); $info = Database::getConnectionInfo(); $info_copy = $info; // Set a flag to fall back to utf8. Note: this flag should only be // used here and is for internal use only. $info_copy['default']['_dsn_utf8_fallback'] = TRUE; // In order to change the Database::$databaseInfo array, we need to // remove the active connection, then re-add it with the new info. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $info_copy['default']); // Connect with the new database info, using the utf8 character set so // that we can run the checkEngineVersion test. Database::getConnection(); // Revert to the old settings. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $info['default']); } else { // Rethrow the exception. throw $e; } } $this->pass('Drupal can CONNECT to the database ok.'); } catch (\Exception $e) { // Attempt to create the database if it is not found. if ($e->getCode() == Connection::DATABASE_NOT_FOUND) { // Remove the database string from connection info. $connection_info = Database::getConnectionInfo(); $database = $connection_info['default']['database']; unset($connection_info['default']['database']); // In order to change the Database::$databaseInfo array, need to remove // the active connection, then re-add it with the new info. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $connection_info['default']); try { // Now, attempt the connection again; if it's successful, attempt to // create the database. Database::getConnection()->createDatabase($database); } catch (DatabaseNotFoundException $e) { // Still no dice; probably a permission issue. Raise the error to the // installer. $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage()))); } } else { // Database connection failed for some other reason than the database // not existing. $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist or does the database user have sufficient privileges to create the database?</li><li>Have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage()))); return FALSE; } } return TRUE; }
/** * The Drupal installation happens in a series of steps. We begin by verifying * that the current environment meets our minimum requirements. We then go * on to verify that settings.php is properly configured. From there we * connect to the configured database and verify that it meets our minimum * requirements. Finally we can allow the user to select an installation * profile and complete the installation process. * * @param $phase * The installation phase we should proceed to. */ function install_main() { require_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION); // This must go after drupal_bootstrap(), which unsets globals! global $profile, $install_locale; require_once './modules/system/system.install'; require_once './includes/file.inc'; // Ensure correct page headers are sent (e.g. caching) drupal_page_header(); // Check existing settings.php. $verify = install_verify_settings(); // Drupal may already be installed. if ($verify) { // Establish a connection to the database. require_once './includes/database.inc'; db_set_active(); // Check if Drupal is installed. if (install_verify_drupal()) { install_already_done_error(); } } // Load module basics (needed for hook invokes). include_once './includes/module.inc'; $module_list['system']['filename'] = 'modules/system/system.module'; $module_list['filter']['filename'] = 'modules/filter/filter.module'; module_list(TRUE, FALSE, FALSE, $module_list); drupal_load('module', 'system'); drupal_load('module', 'filter'); // Decide which profile to use. if (!empty($_GET['profile'])) { $profile = preg_replace('/[^a-zA-Z_0-9]/', '', $_GET['profile']); } elseif ($profile = install_select_profile()) { install_goto("install.php?profile={$profile}"); } else { install_no_profile_error(); } // Locale selection if (!empty($_GET['locale'])) { $install_locale = preg_replace('/[^a-zA-Z_0-9]/', '', $_GET['locale']); } elseif (($install_locale = install_select_locale($profile)) !== FALSE) { install_goto("install.php?profile={$profile}&locale={$install_locale}"); } // Load the profile. require_once "./profiles/{$profile}/{$profile}.profile"; // Check the installation requirements for Drupal and this profile. install_check_requirements($profile); // Change the settings.php information if verification failed earlier. // Note: will trigger a redirect if database credentials change. if (!$verify) { install_change_settings($profile, $install_locale); } // Verify existence of all required modules. $modules = drupal_verify_profile($profile, $install_locale); if (!$modules) { install_missing_modules_error($profile); } // Perform actual installation defined in the profile. drupal_install_profile($profile, $modules); // Warn about settings.php permissions risk $settings_file = './' . conf_path() . '/settings.php'; if (!drupal_verify_install_file($settings_file, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE)) { drupal_set_message(st('All necessary changes to %file have been made, so you should now remove write permissions to this file. Failure to remove write permissions to this file is a security risk.', array('%file' => $settings_file)), 'error'); } else { drupal_set_message(st('All necessary changes to %file have been made. It has been set to read-only for security.', array('%file' => $settings_file))); } // Show end page. install_complete($profile); }
public static function run() { if (PHP_SAPI !== 'cli') { return; } ini_set('max_execution_time', 60 * 60); ini_set('memory_limit', '2G'); // Get list of common tables. // Check if the "old" database connection is properly defined during the // first switch. if (db_set_active('old') === NULL) { print "ERROR: the 'old' database connection is not defined!\n"; return; } $tables_old = db_query('SHOW TABLES')->fetchCol(); db_set_active(); $tables_new = db_query('SHOW TABLES')->fetchCol(); $tables_common = array_intersect($tables_old, $tables_new); // This is what we want to migrate. The array values are table names or // table name prefixes. $base_tables_to_migrate = ['block', 'comment', 'file', 'node', 'taxonomy', 'url', 'user', 'users']; $tables_to_migrate = []; foreach ($tables_common as $table_name) { foreach ($base_tables_to_migrate as $base_table_name) { if ($table_name == $base_table_name || strpos($table_name, $base_table_name . '_') === 0) { $tables_to_migrate[] = $table_name; break; } } } // Migrate common data. foreach ($tables_to_migrate as $table) { // Get column info. db_set_active('old'); $columns_old = db_query('SHOW COLUMNS FROM ' . $table)->fetchCol(); db_set_active(); $columns_new = db_query('SHOW COLUMNS FROM ' . $table)->fetchCol(); $exists_only_in_old_db = array_diff($columns_old, $columns_new); $exists_only_in_new_db = array_diff($columns_new, $columns_old); // Get rows. db_set_active('old'); $rows = db_select($table, 't')->fields('t')->execute()->fetchAll(PDO::FETCH_ASSOC); // Prepare table. db_set_active(); db_truncate($table)->execute(); $table_status = db_query("SHOW TABLE STATUS LIKE '{$table}'")->fetch(); if (isset($table_status->Auto_increment)) { db_query("ALTER TABLE `{$table}` AUTO_INCREMENT = 1"); } // Copy rows. foreach ($rows as $row) { // Modify row data if required. // CASE: some columns were removed in new scheme. if (!empty($exists_only_in_old_db) && empty($exists_only_in_new_db)) { foreach ($exists_only_in_old_db as $column) { unset($row[$column]); } } elseif (empty($exists_only_in_old_db) && count($exists_only_in_new_db) == 1 && reset($exists_only_in_new_db) == 'langcode') { $row['langcode'] = 'en'; } elseif (preg_match('/^.*__field_link$/', $table)) { unset($row['field_link_route_name']); unset($row['field_link_route_parameters']); $row['field_link_uri'] = 'internal:/' . $row['field_link_url']; unset($row['field_link_url']); } elseif ($table == 'taxonomy_index') { $langcode = db_select('node', 'n')->fields('n', ['langcode'])->condition('n.nid', $row['nid'])->execute()->fetchField(); $row['status'] = db_select('node_field_data', 'nfd')->fields('nfd', ['status'])->condition('nfd.nid', $row['nid'])->condition('nfd.langcode', $langcode)->execute()->fetchField(); } // Insert. db_insert($table)->fields($row)->execute(); } echo "Migrated {$table} table.\n"; } // Migrate user roles. db_set_active('old'); $rows = db_select('users_roles', 'ur')->fields('ur')->execute()->fetchAll(PDO::FETCH_ASSOC); db_set_active(); db_truncate('user__roles')->execute(); foreach ($rows as $row) { $row = ['bundle' => 'user', 'deleted' => 0, 'entity_id' => $row['uid'], 'revision_id' => $row['uid'], 'langcode' => 'en', 'delta' => 0, 'roles_target_id' => $row['rid']]; db_insert('user__roles')->fields($row)->execute(); } echo "Migrated user roles.\n"; echo "Rebuilding caches...\n"; drupal_flush_all_caches(); echo "DONE!\n"; }
/** * @file * A special, detachable routine for importing subscriptions. * * The process of importing subscriptions relies on Drupal API calls that may * not be intended for large batch processing. This script is intended to be * called via exec() by a higher level import routine to handle a small subset * of Drupal user objects at a time and avoid exhausting memory. */ require_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); require_boinc('db'); // Parse arguments $record_offset = isset($argv[1]) ? $argv[1] : 0; $chunk_size = isset($argv[2]) ? $argv[2] : 100; // Construct sql conditions $limit = sprintf('LIMIT %d,%d', $record_offset, $chunk_size); $total_count = 0; // Get the users with subscriptions to import db_set_active('boinc'); $subscribed_boinc_users = db_query("\n SELECT DISTINCT userid FROM {subscriptions}\n ORDER BY userid ASC %s", $limit); db_set_active('default'); // Import subscriptions while ($boinc_subscription = db_fetch_object($subscribed_boinc_users)) { $uid = get_drupal_id($boinc_subscription->userid); $count = boincuser_pull_subscriptions($uid); $total_count += $count; echo "\nuser: {$uid}; boinc_id: {$boinc_subscription->userid}; {$count} subscriptions"; } echo "\n"; echo $total_count;
/** * Tests that we can log queries separately on different connections. */ function testEnableMultiConnectionLogging() { // Clone the primary credentials to a fake connection. // That both connections point to the same physical database is irrelevant. $connection_info = Database::getConnectionInfo('default'); Database::addConnectionInfo('test2', 'default', $connection_info['default']); Database::startLog('testing1'); Database::startLog('testing1', 'test2'); db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol(); $old_key = db_set_active('test2'); db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'replica'))->fetchCol(); db_set_active($old_key); $queries1 = Database::getLog('testing1'); $queries2 = Database::getLog('testing1', 'test2'); $this->assertEqual(count($queries1), 1, 'Correct number of queries recorded for first connection.'); $this->assertEqual(count($queries2), 1, 'Correct number of queries recorded for second connection.'); }
/** * The Drupal installation happens in a series of steps. We begin by verifying * that the current environment meets our minimum requirements. We then go * on to verify that settings.php is properly configured. From there we * connect to the configured database and verify that it meets our minimum * requirements. Finally we can allow the user to select an installation * profile and complete the installation process. * * @param $phase * The installation phase we should proceed to. */ function install_main() { require_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION); // The user agent header is used to pass a database prefix in the request when // running tests. However, for security reasons, it is imperative that no // installation be permitted using such a prefix. if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], "simpletest") !== FALSE) { header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); exit; } // This must go after drupal_bootstrap(), which unsets globals! global $profile, $install_locale, $conf; require_once './modules/system/system.install'; require_once './includes/file.inc'; // Ensure correct page headers are sent (e.g. caching) drupal_page_header(); // Set up $language, so t() caller functions will still work. drupal_init_language(); // Load module basics (needed for hook invokes). include_once './includes/module.inc'; $module_list['system']['filename'] = 'modules/system/system.module'; $module_list['filter']['filename'] = 'modules/filter/filter.module'; module_list(TRUE, FALSE, FALSE, $module_list); drupal_load('module', 'system'); drupal_load('module', 'filter'); // Install profile chosen, set the global immediately. // This needs to be done before the theme cache gets // initialized in drupal_maintenance_theme(). if (!empty($_GET['profile'])) { $profile = preg_replace('/[^a-zA-Z_0-9]/', '', $_GET['profile']); } // Set up theme system for the maintenance page. drupal_maintenance_theme(); // Check existing settings.php. $verify = install_verify_settings(); if ($verify) { // Since we have a database connection, we use the normal cache system. // This is important, as the installer calls into the Drupal system for // the clean URL checks, so we should maintain the cache properly. require_once './includes/cache.inc'; $conf['cache_inc'] = './includes/cache.inc'; // Establish a connection to the database. require_once './includes/database.inc'; db_set_active(); // Check if Drupal is installed. $task = install_verify_drupal(); if ($task == 'done') { install_already_done_error(); } } else { // Since no persistent storage is available yet, and functions that check // for cached data will fail, we temporarily replace the normal cache // system with a stubbed-out version that short-circuits the actual // caching process and avoids any errors. require_once './includes/cache-install.inc'; $conf['cache_inc'] = './includes/cache-install.inc'; $task = NULL; } // No profile was passed in GET, ask the user. if (empty($_GET['profile'])) { if ($profile = install_select_profile()) { install_goto("install.php?profile={$profile}"); } else { install_no_profile_error(); } } // Load the profile. require_once "./profiles/{$profile}/{$profile}.profile"; // Locale selection if (!empty($_GET['locale'])) { $install_locale = preg_replace('/[^a-zA-Z_0-9\\-]/', '', $_GET['locale']); } elseif (($install_locale = install_select_locale($profile)) !== FALSE) { install_goto("install.php?profile={$profile}&locale={$install_locale}"); } // Tasks come after the database is set up if (!$task) { global $db_url; if (!$verify && !empty($db_url)) { // Do not install over a configured settings.php. install_already_done_error(); } // Check the installation requirements for Drupal and this profile. install_check_requirements($profile, $verify); // Verify existence of all required modules. $modules = drupal_verify_profile($profile, $install_locale); // If any error messages are set now, it means a requirement problem. $messages = drupal_set_message(); if (!empty($messages['error'])) { install_task_list('requirements'); drupal_set_title(st('Requirements problem')); print theme('install_page', ''); exit; } // Change the settings.php information if verification failed earlier. // Note: will trigger a redirect if database credentials change. if (!$verify) { install_change_settings($profile, $install_locale); } // Install system.module. drupal_install_system(); // Save the list of other modules to install for the 'profile-install' // task. variable_set() can be used now that system.module is installed // and drupal is bootstrapped. variable_set('install_profile_modules', array_diff($modules, array('system'))); } // The database is set up, turn to further tasks. install_tasks($profile, $task); }
$nq = str_replace('2000', $r->year, str_replace('05', $r->gradelevel, $q5)); //creates grade/year sub-combo exception list... db_query($nq); echo (string) (intval(time()) - $strt) . "- whole school filters added.\n<br>"; ob_flush(); } $i++; } $output .= " <br> " . $i . " grades/years checked, " . $added . " grades/years processed (version b) "; echo $output; exit; } //end exceptions $schId = getURLParam('clearfilters'); if ($schId) { db_set_active('isbe'); $q = <<<UINQ delete FROM isbefilters UINQ; $rr = db_query($q); echo "All Filters have been deleted..."; exit; } //end clearfilters $colnames = <<<UINQ [{"sTitle":"Filter","field":"filter"},{"sTitle":"Count","field":"cnt"}] UINQ; $q = "select filter, count(*) cnt from isbefilters group by filter"; $output .= makeDS("noreport", $q, $colnames, 'isbe'); // header('Content-Type: text/javascript; charset=utf-8'); ?>