/** * __construct * * @desc ćž„é€ ĺ™¨ * @access private * @return void */ private function __construct($dbOptions) { $dsn = $dbOptions["adapter"] . ':host=' . $dbOptions["host"] . ';dbname=' . $dbOptions["dbname"]; try { self::$_dbh = new PDO($dsn, $dbOptions["username"], $dbOptions["password"], array(PDO::ATTR_PERSISTENT => $dbOptions["use_pconnect"])); self::$_dbh->query("SET NAMES '" . $dbOptions["charset"] . "'"); if (strtolower($dbOptions['adapter']) == 'mysql' && true === $dbOptions["use_buffered_query"]) { self::$_dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); } if ($dbOptions['throw_exception']) { self::$_dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } } catch (PDOException $e) { throw new Exception($e->getMessage()); } }
function deleteQueueEntry($id, $position) { //delete DB entry $this->_wpdb->query("DELETE FROM {$this->QUEUE_TABLE} WHERE q_img_id = {$id}"); //delete cat entries $this->_wpdb->query("DELETE FROM {$this->QCAT_TABLE} WHERE q_fk_img_id = {$id}"); //delete field entries $this->_wpdb->query("DELETE FROM {$this->QUEUEMETA_TABLE} WHERE q_fk_img_id = {$id}"); //update queue positions $this->_wpdb->query("UPDATE {$this->QUEUE_TABLE} SET q_position = q_position-1 WHERE q_position > '{$position}'"); }
/** * Executa uma query no banco de dados * * @param string $sql * @return array */ function query($sql, $relacionado = array()) { if ($this->useTable === false) { return array(); } $rs = $this->db->query($sql); if ($this->relacionado != null) { if (stripos($sql, "select") !== false) { return $this->db->getResultsRel($rs, $this->chavePrimaria, get_class($this) . "__" . $this->relacionado); } } if (stripos($sql, "select") !== false) { return $this->db->getResults($rs, $this->chavePrimaria); } }
/** * Check if a character exists and is offline * @param Int $guid * @param Object $realmConnection * @param Int $realmId * @return Boolean */ public function characterExists($guid, $realmConnection, $realmId) { $query = $realmConnection->query("SELECT COUNT(*) AS `total` FROM " . table("characters", $realmId) . " WHERE " . column("characters", "guid", false, $realmId) . " = ? AND " . column("characters", "online", false, $realmId) . " = 0", array($guid)); if ($realmConnection->_error_message()) { die($realmConnection->_error_message()); } if ($query->num_rows() > 0) { $result = $query->result_array(); if ($result[0]['total']) { return true; } else { return false; } } else { return false; } }
/** * Delete Comments * * This function will delete a comment by it's note_id * This function will mainly be used by administrators and * people with enough karma to manage comments. * * @access public * @param Array $note_ids The array of the notes to delete * * @return Mixed $res An error object if query was erroneous, bool * if it was successful */ function deleteComments($note_ids) { if (!is_array($note_ids)) { return false; } /** * Let's just format the note ids so they are simple to * read within an IN() */ $notes = "'" . implode(', ', $note_ids) . "'"; $sql = "\n UPDATE {$this->notesTableName}\n SET note_deleted = 1, note_approved='no'\n WHERE note_id IN({$notes})\n "; $res = $this->dbc->query($sql); if (PEAR::isError($res)) { return $res; } return true; }
/** * Fetch query parameters * * @return string */ private function __queryParams() { $url = $this->request->query(); if (strlen($url) > 0) { $url = "?{$url}"; } return $url; if (isset($this->request->sock->config['request']['uri']['query'])) { $qParams = $this->request->sock->config['request']['uri']['query']; if (is_array($qParams) && count($qParams) > 0) { $url = '?' . OauthHelper::mapper($qParams, '&', ''); } elseif (is_string($qParams)) { $url = $qParams; } else { $url = '?'; } return $url; } else { return ''; } }
/** * Shot a query to database and return raw data * * @param string $query * * @return mixed * * @throws \Comodojo\Exception\DatabaseException */ public function rawQuery($query) { switch ($this->model) { case "MYSQLI": $response = $this->dbh->query($query); if (!$response) { throw new DatabaseException($this->dbh->error, $this->dbh->errno); } break; case "MYSQL_PDO": case "ORACLE_PDO": case "SQLITE_PDO": case "DBLIB_PDO": try { $response = $this->dbh->prepare($query); $response->execute(); } catch (\PDOException $e) { throw new DatabaseException($e->getMessage(), (int) $e->getCode()); } break; case "DB2": $response = db2_exec($this->dbh, $query); if (!$response) { throw new DatabaseException(db2_stmt_error()); } break; case "POSTGRESQL": $response = pg_query($this->dbh, $query); if (!$response) { throw new DatabaseException(pg_last_error()); } break; default: throw new DatabaseException('Invalid database model'); break; } return $response; }
/** * Builder method for the class * @param Object $db Database interface * @param string $table table name * @param string $field column name * @return IBM_DB2Field */ static function fromText($db, $table, $field) { global $wgDBmwschema; $q = <<<END SELECT lcase(coltype) AS typname, nulls AS attnotnull, length AS attlen FROM sysibm.syscolumns WHERE tbcreator=%s AND tbname=%s AND name=%s; END; $res = $db->query(sprintf($q, $db->addQuotes($wgDBmwschema), $db->addQuotes($table), $db->addQuotes($field))); $row = $db->fetchObject($res); if (!$row) { return null; } $n = new IBM_DB2Field(); $n->type = $row->typname; $n->nullable = $row->attnotnull == 'N'; $n->name = $field; $n->tablename = $table; $n->max_length = $row->attlen; return $n; }
/** * Given a list of conditions in params and a list of desired * return Properties generate the required select and from * clauses. Note that since the where clause introduces new * tables, the initial attempt also retrieves all variables used * in the params list * * @return void * @access public */ function selectClause() { $properties = array(); $cfIDs = array(); $this->addSpecialFields(); $this->addContributeFields(); //CRM_Core_Error::debug( 'f', $this->_fields ); //CRM_Core_Error::debug( 'p', $this->_params ); //format privacy options if (is_array($this->_params['privacy'])) { foreach ($this->_params['privacy'] as $key => $value) { if ($value) { $this->_params[$key] = 1; } } } foreach ($this->_fields as $name => $field) { $value = CRM_Utils_Array::value($name, $this->_params); // if we need to get the value for this param or we need all values if (!CRM_Utils_System::isNull($value) || CRM_Utils_Array::value($name, $this->_returnProperties)) { $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $value = CRM_Utils_Array::value($name, $this->_params); $cfIDs[$cfID] = $value; } else { if (isset($field['where'])) { list($tableName, $fieldName) = explode('.', $field['where'], 2); if (isset($tableName)) { if (CRM_Utils_Array::value($tableName, $GLOBALS['_CRM_CONTACT_BAO_QUERY']['_dependencies'])) { $this->_tables['civicrm_location'] = 1; $this->_select['location_id'] = 'civicrm_location.id as location_id'; $this->_element['location_id'] = 1; $this->_tables['civicrm_address'] = 1; $this->_select['address_id'] = 'civicrm_address.id as address_id'; $this->_element['address_id'] = 1; } $this->_tables[$tableName] = 1; // also get the id of the tableName $tName = substr($tableName, 8); if ($tName != 'contact') { $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id"; $this->_element["{$tName}_id"] = 1; } //special case for phone if ($name == 'phone') { $this->_select['phone_type'] = "civicrm_phone.phone_type as phone_type"; $this->_element['phone_type'] = 1; } if ($name == 'state_province') { $this->_select[$name] = "civicrm_state_province.abbreviation as `{$name}`"; } else { $this->_select[$name] = $field['where'] . " as `{$name}`"; } $this->_element[$name] = 1; } } elseif ($name === 'tags') { $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) AS tags"; $this->_tables['civicrm_tag'] = 1; $this->_tables['civicrm_entity_tag'] = 1; } elseif ($name === 'groups') { $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.name)) AS groups"; $this->_tables['civicrm_group'] = 1; $this->_tables['civicrm_group_contact'] = 1; } } } else { if (CRM_Utils_Array::value('is_search_range', $field)) { // this is a custom field with range search enabled, so we better check for two/from values $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $value = CRM_Utils_Array::value($name . '_from', $this->_params); if (!CRM_Utils_System::isNull($value)) { $cfIDs[$cfID]['from'] = $value; } $value = CRM_Utils_Array::value($name . '_to', $this->_params); if (!CRM_Utils_System::isNull($value)) { $cfIDs[$cfID]['to'] = $value; } } } } } // add location as hierarchical elements $this->addHierarchicalElements(); if (!empty($cfIDs)) { //CRM_Core_Error::debug( 'cfIDs', $cfIDs ); require_once 'CRM/Core/BAO/CustomQuery.php'; $this->_customQuery = new CRM_Core_BAO_CustomQuery($cfIDs); $this->_customQuery->query(); $this->_select = array_merge($this->_select, $this->_customQuery->_select); $this->_element = array_merge($this->_element, $this->_customQuery->_element); $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables); $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables); $this->_options = $this->_customQuery->_options; } }
/** * Retrieve packages informations * * @param Object $db A reference to the database * * @return array */ function report($db) { global $what, $smarty; $packages = null; $rpmrepo = new TableRpmRepo($db); $repos = $rpmrepo->getAllRepoHash(); $smarty->assign('repos', $repos); if (substr($what, 0, 1) == '%') { $sql = sprintf("SELECT DISTINCT name\n FROM rpm\n WHERE SUBSTRING(name,1,1)='%s'\n ORDER BY name", substr($what, 1, 1)); } else { $sql = sprintf("SELECT DISTINCT name\n FROM acls\n WHERE owner='%s'\n ORDER BY name", $what); } //echo "<p>SQL=$sql</p>"; $i = 0; $res = $db->query($sql); if ($res) { while ($desc = $res->fetchObject()) { $package = null; $rpmname = $desc->name; $sql2 = "SELECT DISTINCT owner FROM acls WHERE name LIKE '{$rpmname}'"; $res2 = $db->query($sql2); $dispowner = ""; $owners = array(); if ($res2) { while ($owner = $res2->fetchObject()) { $owners[] = $owner->owner; } } $sql3 = "SELECT * FROM rpm WHERE name LIKE '{$rpmname}'"; $res3 = $db->query($sql3); $rpm = $res3 ? $res3->fetchObject() : false; if ($rpm) { $url = $rpm->url; $des = htmlentities($rpm->summary); $rpms = array(); do { $rpms[$rpm->repo_main . "-" . $rpm->repo_sub] = $rpm; } while ($rpm = $res3->fetchObject()); $package['name'] = $rpmname; $package['description'] = $des; $package['owners'] = $owners; $versions = null; foreach ($repos as $repomain) { $display = ""; $class = ""; foreach ($repomain as $repo) { if (isset($rpms[$repo['main'] . "-" . $repo['sub']])) { $rpm = $rpms[$repo['main'] . "-" . $repo['sub']]; $maxver = isset($rpms["devel-"]) ? $rpms["devel-"]->ver : ""; if (strpos($repo['sub'], '-os') || strpos($repo['sub'], '-beta') || strpos($repo['sub'], '-base') || strpos($repo['sub'], '-optional') || strpos($repo['sub'], '-stable')) { // For CentOS $repotype = 'base'; } else { if (strpos($repo['sub'], 'testing')) { $repotype = 'testing'; } else { if (strpos($repo['sub'], 'updates')) { $repotype = 'updates'; } else { $repotype = $repo['sub']; } } } switch ($repotype) { case "base": if (isset($rpms[$repo['main'] . "-updates"])) { $display .= sprintf("%s-%s<br/>", $rpm->ver, $rpm->rel); } else { $display .= sprintf("<strong>%s</strong>-%s<br/>", $rpm->ver, $rpm->rel); $class = $rpm->ver == $maxver ? "check" : "attn"; } break; case "": $display .= sprintf("<strong>%s</strong>-%s<br/>", $rpm->ver, $rpm->rel); break; case "updates": $display .= sprintf("<strong>%s</strong>-%s<br/><small>(%s)</small><br/>", $rpm->ver, $rpm->rel, $repo['sub']); $class = $rpm->ver == $maxver ? "check" : "attn"; break; case "testing": $display .= sprintf("%s-%s<br/><small>(%s)</small><br/>", $rpm->ver, $rpm->rel, $repo['sub']); $class = $rpm->ver == $maxver ? "info" : "attn"; break; } } // RPM exists } // sub repo $versions[] = array('class' => $class && $maxver ? $class : '', 'display' => $display); $package['versions'] = $versions; } // mainrepo $i++; $packages[] = $package; } } // each Line } return $packages; }
/** * Method that returns count/total number of reviews * @param Object $dbObj Datatbase connectivity object * @param int $courseId Course Id * @return int Number of reviews */ public static function getRawCount($dbObj, $courseId = 0) { $sql = "SELECT * FROM course_review "; if ($courseId !== 0) { $sql = "SELECT * FROM course_review WHERE course = {$courseId} "; } $count = ""; $result = $dbObj->query($sql); $totalData = mysqli_num_rows($result); if ($result !== false) { $count = $totalData; } return $count; }
/** * Parses the sql file and executes the given statements. * * @param Object $db The db adapter to use * @param String $path The path to the sql file to execute * @param String $prefix The prefix to use for the tables */ function conjoon_createDatastructure($db, $path, $prefix = "") { // check here if we need to migrate data $migrate = false; $sql = "SELECT * FROM " . $prefix . "groupware_email_folders_users"; $result = $db->query($sql); if (!$result) { $migrate = true; } // twitter migrate $twittersql = "SELECT twitter_id FROM " . $prefix . "service_twitter_accounts"; $twitterresult = $db->query($twittersql); if (!$twitterresult) { $db->query("TRUNCATE TABLE `" . $prefix . "service_twitter_accounts`"); } $sqlFile = file_get_contents($path); // remove sql comments $sqlFile = preg_replace("/^--.*?\$/ims", "", $sqlFile); //replace prefix $sqlFile = str_replace('{DATABASE.TABLE.PREFIX}', $prefix, $sqlFile); $statements = explode(';', $sqlFile); for ($i = 0, $len = count($statements); $i < $len; $i++) { $statement = trim($statements[$i]); if ($statement == "") { continue; } InstallLogger::stdout(InstallLogger::getInstance()->logMessage("[STRUCTURE]: " . $statement)); if (!$db->query($statement)) { $err = $db->errorInfo(); InstallLogger::stdout(InstallLogger::getInstance()->logMessage("[STRUCTURE:FAILED]: " . (!empty($err) ? $err[2] : $statement))); } } if ($migrate) { sleep(1); // migrate to groupware_email_folders_users // get the user ids associated with the user accounts $folderAccountsQuery = "SELECT " . $prefix . "groupware_email_folders_accounts.*, " . "" . $prefix . "groupware_email_accounts.user_id FROM " . " " . $prefix . "groupware_email_folders_accounts, " . "" . $prefix . "groupware_email_accounts" . " " . $prefix . "groupware_email_accounts " . " WHERE " . $prefix . "groupware_email_accounts.id = " . "" . $prefix . "groupware_email_folders_accounts.groupware_email_accounts_id"; $folderAccountsResult = $db->query($folderAccountsQuery); if (!$folderAccountsResult) { // error or something - return return; } $folderAccountsResultCount = 0; $folderMapping = array(); foreach ($folderAccountsResult as $row) { $folderAccountsResultCount++; $folderMapping[] = $row; } if ($folderAccountsResultCount == 0) { return; } for ($i = 0, $len = count($folderMapping); $i < $len; $i++) { $query = "INSERT INTO " . $prefix . "groupware_email_folders_users " . "(groupware_email_folders_id, users_id, relationship) " . "VALUES (" . "" . $folderMapping[$i]['groupware_email_folders_id'] . "," . "" . $folderMapping[$i]['user_id'] . "," . "'owner'" . ")"; $db->query($query); } } }
/** * Method that returns count/total number of a particular course * @param Object $dbObj Datatbase connectivity object * @return int Number of courses */ public static function getRawCount($dbObj) { $sql = "SELECT * FROM " . self::$tableName . " "; $count = ""; $result = $dbObj->query($sql); $totalData = mysqli_num_rows($result); if ($result !== false) { $count = $totalData; } return $count; }
/** * Method that returns count/total number of a particular course * @param Object $dbObj Datatbase connectivity object * @return int Number of courses */ public static function getRawCount($dbObj, $dbPrefix) { $tableName = $dbPrefix . 'course_category'; $sql = "SELECT * FROM {$tableName} "; $count = ""; $result = $dbObj->query($sql); $totalData = mysqli_num_rows($result); if ($result !== false) { $count = $totalData; } return $count; }
/** * Given a list of conditions in params and a list of desired * return Properties generate the required select and from * clauses. Note that since the where clause introduces new * tables, the initial attempt also retrieves all variables used * in the params list * * @return void */ public function selectClause() { foreach ($this->_fields as $name => $field) { // if this is a hierarchical name, we ignore it $names = explode('-', $name); if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) { continue; } $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if (!empty($this->_paramLookup[$name]) || !empty($this->_returnProperties[$name])) { if ($cfID) { // add to cfIDs array if not present if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } } elseif (isset($field['where'])) { list($tableName, $fieldName) = explode('.', $field['where'], 2); if (isset($tableName)) { // also get the id of the tableName $this->_select[$name] = "{$tableName}.{$fieldName} as `{$name}`"; } } else { //dsm('volgende velden worden niet in select verwerkt'); //dsm($name); } if ($cfID && !empty($field['is_search_range'])) { // this is a custom field with range search enabled, so we better check for two/from values if (!empty($this->_paramLookup[$name . '_from'])) { if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) { // search in the cdID array for the same grouping $fnd = FALSE; foreach ($this->_cfIDs[$cfID] as $cID => $c) { if ($c[3] == $p[3]) { $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2]; $fnd = TRUE; } } if (!$fnd) { $p[2] = array('from' => $p[2]); $this->_cfIDs[$cfID][] = $p; } } } if (!empty($this->_paramLookup[$name . '_to'])) { if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) { // search in the cdID array for the same grouping $fnd = FALSE; foreach ($this->_cfIDs[$cfID] as $cID => $c) { if ($c[4] == $p[4]) { $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2]; $fnd = TRUE; } } if (!$fnd) { $p[2] = array('to' => $p[2]); $this->_cfIDs[$cfID][] = $p; } } } } } } if (!empty($this->_cfIDs)) { $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs); $this->_customQuery->query(); // Customquery hardcodes te relationship table to civicrm_relationship // We call this relationship, so we need to change this. $this->_customQuery->_tables = str_replace('civicrm_relationship', 'relationship', $this->_customQuery->_tables); $this->_customQuery->_whereTables = str_replace('civicrm_relationship', 'relationship', $this->_customQuery->_whereTables); $this->_select = array_merge($this->_select, $this->_customQuery->_select); $this->_element = array_merge($this->_element, $this->_customQuery->_element); $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables); $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables); $this->_options = $this->_customQuery->_options; } }
/** * Method that enrols for a course category * @param Object $dbMoObj Database connectivity and manipulation object * @param string $dbPrefix Database prefix * @param int $user User Id * @param datetime $timeStart Start time * @param int $modifierId Modifier Id * @param datetime $timeCreated Time created * @param datetime $timeModified Time Modified * @param int $category Catgory Id */ public static function enrolCategory($dbMoObj, $dbPrefix, $user, $timeStart, $modifierId, $timeCreated, $timeModified, $category) { $tableName = $dbPrefix . 'user_enrolments'; $enrolTable = $dbPrefix . 'enrol'; $courseTable = $dbPrefix . 'course'; $categoryTable = $dbPrefix . 'course_categories'; if ($category != 0) { $enrolCatResult = $dbMoObj->fetchAssoc("SELECT * FROM {$courseTable} WHERE category = {$category} AND format !='site' "); foreach ($enrolCatResult as $courseDet) { $enrolResult = $dbMoObj->fetchAssoc("SELECT * FROM {$enrolTable} WHERE courseid = " . $courseDet['id'] . " AND enrol='manual' LIMIT 1"); foreach ($enrolResult as $enrolResult) { $sql = "INSERT INTO {$tableName} (enrolid, userid, timestart, modifierid, timecreated, timemodified) " . "VALUES ('{$enrolResult['id']}','{$user}','{$timeStart}','" . $modifierId . "','" . $timeCreated . "','{$timeModified}')"; if (count($dbMoObj->fetchAssoc("SELECT * FROM {$tableName} WHERE userid = {$user} AND enrolid = '{$enrolResult['id']}' ")) < 1) { $result = $dbMoObj->query($sql); } } } $catDetails = $dbMoObj->fetchAssoc("SELECT * FROM {$categoryTable} WHERE parent = {$category} "); foreach ($catDetails as $catDetail) { User::enrolCategory($dbMoObj, $dbPrefix, $user, $timeStart, $modifierId, $timeCreated, $timeModified, $catDetail['id']); } } }
/** * Retrieve packages informations * * @param Object $db A reference to the database * @param string $type The current type * * @return array */ function report($db, $type) { global $what, $smarty; $packages = null; $rpmrepo = new TableRpmRepo($db); $rpmtable = new TableRpm($db); $uptable = new TableUpstream($db); $repos = $rpmrepo->getAllRepoHash(); $smarty->assign('repos', $repos); $crit = array('type' => $type, 'ORDER' => 'name'); if (substr($what, 0, 1) == '#') { $crit['channel'] = substr($what, 1); $what = '%fedora'; } $i = 0; foreach ($uptable->request($crit) as $up) { $package = null; $rpmname = $up['name']; $verup = strtolower($up['stable'] ? $up['stable'] : $up['unstable']); $sql2 = "SELECT DISTINCT owner FROM acls WHERE name = '{$rpmname}'"; $res2 = $db->query($sql2); $owners = array(); if ($res2) { while ($owner = $res2->fetchObject()) { $owners[] = $owner->owner; } } $package['name'] = $rpmname; $rpms = array(); foreach ($rpmtable->request(array('name' => $rpmname)) as $rpm) { $rpms[$rpm['repo_main'] . '-' . $rpm['repo_sub']] = $rpm; $package['name'] = '<a href="zoom.php?rpm=' . $rpmname . '" title="' . htmlentities($rpm['summary'], ENT_QUOTES) . '">' . $rpmname . '</a>'; } switch ($what) { case '%work': $display = false; if (count($rpms) && isset($rpms['devel-']) && $rpms['devel-']['ver'] != $verup) { $display = true; } break; case '%fedora': $display = count($rpms); break; case '%stable': $display = !empty($up['stable']); break; case '%all': $display = true; break; default: // owner $display = array_search($what, $owners) !== false; break; } if ($display) { if ($up['channel'] != $up['type']) { $package['channel'] = $up['channel']; } $dispowner = ""; $package['owners'] = $owners; if ($up['stable']) { $package['upstream_stable'] = $up['stable']; } if ($up['unstable'] && (!$up['stable'] || $up['stable'] != $up['unstable'])) { $package['upstream_unstable'] = $up['unstable'] . ' <small>(' . $up['state'] . ')</small>'; } $versions = null; foreach ($repos as $repomain) { $display = ""; $class = ""; foreach ($repomain as $k => $repo) { if (isset($rpms[$repo['main'] . "-" . $repo['sub']])) { $rpm = $rpms[$repo['main'] . "-" . $repo['sub']]; $verpm = $rpm['ver']; $pat = "/\\.((beta|RC)\\d*)\\./i"; if (preg_match($pat, $rpm['rel'], $res)) { $verpm .= strtolower($res[1]); } if (strpos($repo['sub'], '-os') || strpos($repo['sub'], '-beta') || strpos($repo['sub'], '-base') || strpos($repo['sub'], '-optional') || strpos($repo['sub'], '-stable')) { // For CentOS $repotype = 'base'; } else { if (strpos($repo['sub'], 'testing')) { $repotype = 'testing'; } else { if (strpos($repo['sub'], 'updates')) { $repotype = 'updates'; } else { $repotype = $repo['sub']; } } } switch ($repotype) { case "base": if (isset($rpms[$repo['main'] . "-updates"])) { $display .= sprintf("%s-%s<br/>", $rpm['ver'], $rpm['rel']); } else { $display .= sprintf("<strong>%s</strong>-%s<br/>", $rpm['ver'], $rpm['rel']); } if ($verup == $verpm) { $class = "check"; } break; case "": $display .= sprintf("<strong>%s</strong>-%s<br/>", $rpm['ver'], $rpm['rel']); if ($verup == $verpm) { $class = "check"; } break; case "updates": $display .= sprintf("<strong>%s</strong>-%s" . "<br/><small>(%s)</small><br/>", $rpm['ver'], $rpm['rel'], $repo['sub']); if ($verup == $verpm && $class != 'check') { $class = "check"; } break; case "testing": $display .= sprintf("%s-%s<br/><small>(%s)</small>", $rpm['ver'], $rpm['rel'], $repo['sub']); if ($verup == $verpm && !$class) { $class = "info"; } break; } } // RPM exists } // sub repo if ($display && empty($class)) { $class = "attn"; } $versions[] = array('class' => $class, 'display' => $display); $package['versions'] = $versions; } // mainrepo $i++; $packages[] = $package; } } return $packages; }
/** * Insert the current objects variables into the database * * Returns the ID of the inserted element (if auto increment or sequences are used.) * * for example * * Designed to be extended * * $object = new mytable(); * $object->name = "fred"; * echo $object->insert(); * * @access public * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success */ function insert() { $this->connect(); $t = $this->table(); $fields = array(); $values = array(); // pega a sequence_key (se o valor for igual a nulo) $sk = $this->oTable->sequence_key; if (isset($this->oTable->sequence_key) && !empty($this->oTable->sequence_key) && $this->{$sk} == '') { switch ($this->oTable->sequence_generator) { // Padrão case "default": // verifica se é uma classe extendida if (isset($this->oTable->extends) && $this->oTable->extends != '') { // tenta recuperar a classe que ela extende $clazz = Util::Import($this->oTable->extends); // se existir... if ($clazz !== false) { /// verifica se o campo de IDentificação desta entidade linka com a outra $idfield = $this->oTable->getFieldProperties($this->oTable->sequence_key); // se existir o link if (isset($idfield['linkOn']) && $idfield['linkOn'] != '') { // se não estiver vazio if (isset($this->{$idfield}['linkOn']) && $this->{$idfield}['linkOn'] != '') { $fields[] = $this->{$idfield}['column']; $values[] = $this->{$idfield}['linkOn']; break; // tenta salvar o objeto, setando a partir das propriedades dessa classe } else { $clazz->setFrom($this->toArray()); // insere o objeto $res = $clazz->insert(); // se deu tudo certo na inserção if ($res !== false) { // pega o valor e coloca nesta classe if ($clazz->{$idfield}['linkOn'] != '') { $fields[] = $idfield['column']; $values[] = $clazz->{$idfield}['linkOn']; break; } } // não conseguiu pegar o valor para a subclasse LumineLog::logger(2, "O valor para setar na subclass " . $this->oTable->class . " não encontrado na superclasse " . $clazz->oTable->class, __FILE__, __LINE__); return false; } } } } break; // uma sequencia: o nome da sequencia sempre será $table_$field_seq // uma sequencia: o nome da sequencia sempre será $table_$field_seq case "sequence": // $fields[] = $this->oTable->sequence_key; // $values[] = $this->conn->nextId($this->tablename(), $this->oTable->sequence_key); break; // se o gerador de sequencia for uma classe personalizada // se o gerador de sequencia for uma classe personalizada default: $fields[] = $this->oTable->sequence_key; // tenta usar a classe de geração informada pelo usuário $gen =& Util::Import($this->oTable->sequence_generator); // se encontrou a classe if ($gen !== false) { // passa como parâmetro a entidade para o gerador $values[] = $gen->{$method}($this->oTable); } else { //se não encontrar a classe // dá um alert LumineLog::logger(1, "Classe {$this->oTable->sequence_generator} não encontrada", __FILE__, __LINE__); return false; } break; } // se não tiver chave de sequencia } // se a chave de sequencia tiver um valor if (isset($this->{$sk}) && $this->{$sk} != '') { // pega os dados da chave $prop = $this->oTable->getColumnProperties($sk); // coloca para inserir $fields[] = $sk; $values[] = $this->fromValue($sk, $prop, true); } foreach ($t as $key => $prop) { if (!isset($prop['foreign'])) { if ($prop['column'] != $this->oTable->sequence_key) { if ($this->{$key} != '' || $this->{$key} == '' && isset($this->oTable->config->config['empty-as-null']) && $this->oTable->config->config['empty-as-null'] == '0') { $fields[] = $prop['column']; $values[] = $this->fromValue($key, $prop, true); } } } } // verifica o tipo da chave $keys = $this->oTable->getForeignKeys(); foreach ($keys as $key => $prop) { if ($prop['type'] == 'many-to-one') { $x = $this->{$key}; // se for um objeto if (is_object($x) && is_a($x, 'luminebase')) { // pega o valor $v = $x->{$prop}['linkOn']; // mas se este objeto ainda não está salvo if ($v == '') { // verifica se tem o método de salvar if (method_exists($x, 'save')) { // salva $x->save(); // pega a chave $v = $x->{$prop}['linkOn']; } } } else { // importa a classe de referencia $clazz = Util::Import($prop['class']); $pr = $clazz->oTable->getFieldProperties($prop['linkOn']); // pega o valor $clazz->{$key} = $x; $v = $clazz->fromValue($key, $pr, false); } $old = $this->{$key}; $this->{$key} = $v; if ($this->{$key} != '') { $fields[] = $prop['column']; $values[] = $this->fromValue($key, $prop, true); } $this->{$key} = $old; } } // campos preparados para inserção, agora inserimos :) if (count($fields) > 0 && count($values) > 0) { $sql = "INSERT INTO " . $this->tablename() . " (" . implode(", ", $fields) . ") values (" . implode(", ", $values) . ")"; LumineLog::logger(1, 'Executando a SQL: ' . $sql, __FILE__, __LINE__); if (($x = $this->conn->query($sql)) !== false) { $key = $this->oTable->sequence_key; if ($key && $this->{$key} == '') { $this->{$key} = $this->conn->Insert_ID($this->tablename(), $key); } $this->_saveAttachedObjects(); return $key ? $this->{$key} : true; } LumineLog::logger(3, "Erro de SQL: " . $this->conn->ErrorMsg(), __FILE__, __LINE__); } return false; }
/** * Method that returns count/total number of a particular course * @param Object $dbObj Datatbase connectivity object * @param Object $condition Additional optional condition * @return int Number of courses */ public static function getRawCount($dbObj, $condition = " 1=1 ") { $sql = "SELECT * FROM course WHERE {$condition} "; $count = ""; $result = $dbObj->query($sql); $totalData = mysqli_num_rows($result); if ($result !== false) { $count = $totalData; } return $count; }
/** * Given a list of conditions in params and a list of desired * return Properties generate the required select and from * clauses. Note that since the where clause introduces new * tables, the initial attempt also retrieves all variables used * in the params list */ public function selectClause() { $this->addSpecialFields(); foreach ($this->_fields as $name => $field) { // skip component fields // there are done by the alter query below // and need not be done on every field if (substr($name, 0, 12) == 'participant_' || substr($name, 0, 7) == 'pledge_' || substr($name, 0, 5) == 'case_' || substr($name, 0, 13) == 'contribution_' && (strpos($name, 'source') !== FALSE && strpos($name, 'recur') !== FALSE) || substr($name, 0, 8) == 'payment_') { continue; } // redirect to activity select clause if (substr($name, 0, 9) == 'activity_' || $name == 'parent_id') { CRM_Activity_BAO_Query::select($this); continue; } // if this is a hierarchical name, we ignore it $names = explode('-', $name); if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) { continue; } // make an exception for special cases, to add the field in select clause $makeException = FALSE; //special handling for groups/tags if (in_array($name, array('groups', 'tags', 'notes')) && isset($this->_returnProperties[substr($name, 0, -1)])) { $makeException = TRUE; } // since note has 3 different options we need special handling // note / note_subject / note_body if ($name == 'notes') { foreach (array('note', 'note_subject', 'note_body') as $noteField) { if (isset($this->_returnProperties[$noteField])) { $makeException = TRUE; break; } } } if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id', 'communication_style_id'))) { if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) { $makeException = TRUE; } } $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if (!empty($this->_paramLookup[$name]) || !empty($this->_returnProperties[$name]) || $makeException) { if ($cfID) { // add to cfIDs array if not present if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } } elseif (isset($field['where'])) { list($tableName, $fieldName) = explode('.', $field['where'], 2); if (isset($tableName)) { if (CRM_Utils_Array::value($tableName, self::$_dependencies)) { $this->_tables['civicrm_address'] = 1; $this->_select['address_id'] = 'civicrm_address.id as address_id'; $this->_element['address_id'] = 1; } if ($tableName == 'im_provider' || $tableName == 'email_greeting' || $tableName == 'postal_greeting' || $tableName == 'addressee') { if ($tableName == 'im_provider') { CRM_Core_OptionValue::select($this); } if (in_array($tableName, array('email_greeting', 'postal_greeting', 'addressee'))) { $this->_element["{$name}_id"] = 1; $this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id"; $this->_pseudoConstantsSelect[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id"); $this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as {$name}"; $this->_pseudoConstantsSelect[$name]['element'] = $name; if ($tableName == 'email_greeting') { $this->_pseudoConstantsSelect[$name]['join'] = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')"; $this->_pseudoConstantsSelect[$name]['join'] .= " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) "; } elseif ($tableName == 'postal_greeting') { $this->_pseudoConstantsSelect[$name]['join'] = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')"; $this->_pseudoConstantsSelect[$name]['join'] .= " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) "; } elseif ($tableName == 'addressee') { $this->_pseudoConstantsSelect[$name]['join'] = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')"; $this->_pseudoConstantsSelect[$name]['join'] .= " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) "; } $this->_pseudoConstantsSelect[$name]['table'] = $tableName; //get display $greetField = "{$name}_display"; $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}"; $this->_element[$greetField] = 1; //get custom $greetField = "{$name}_custom"; $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}"; $this->_element[$greetField] = 1; } } else { if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) { $this->_tables[$tableName] = 1; } // also get the id of the tableName $tName = substr($tableName, 8); if (in_array($tName, array('country', 'state_province', 'county'))) { if ($tName == 'state_province') { $this->_pseudoConstantsSelect['state_province_name'] = array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address', 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id "); $this->_pseudoConstantsSelect[$tName] = array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id", 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id "); } else { $this->_pseudoConstantsSelect[$name] = array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address', 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id "); } $this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id"; $this->_element["{$tName}_id"] = 1; } elseif ($tName != 'contact') { $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id"; $this->_element["{$tName}_id"] = 1; } //special case for phone if ($name == 'phone') { $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id"; $this->_element['phone_type_id'] = 1; } // if IM then select provider_id also // to get "IM Service Provider" in a file to be exported, CRM-3140 if ($name == 'im') { $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id"; $this->_element['provider_id'] = 1; } if ($tName == 'contact') { // special case, when current employer is set for Individual contact if ($fieldName == 'organization_name') { $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name"; } elseif ($fieldName != 'id') { if ($fieldName == 'prefix_id') { $this->_pseudoConstantsSelect['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact'); } if ($fieldName == 'suffix_id') { $this->_pseudoConstantsSelect['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact'); } if ($fieldName == 'gender_id') { $this->_pseudoConstantsSelect['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact'); } if ($name == 'communication_style_id') { $this->_pseudoConstantsSelect['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact'); } $this->_select[$name] = "contact_a.{$fieldName} as `{$name}`"; } } elseif (in_array($tName, array('country', 'county'))) { $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `{$name}`"; $this->_pseudoConstantsSelect[$name]['element'] = $name; } elseif ($tName == 'state_province') { $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `{$name}`"; $this->_pseudoConstantsSelect[$tName]['element'] = $name; } else { $this->_select[$name] = "{$field['where']} as `{$name}`"; } if (!in_array($tName, array('state_province', 'country', 'county'))) { $this->_element[$name] = 1; } } } } elseif ($name === 'tags') { $this->_useGroupBy = TRUE; $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags"; $this->_element[$name] = 1; $this->_tables['civicrm_tag'] = 1; $this->_tables['civicrm_entity_tag'] = 1; } elseif ($name === 'groups') { $this->_useGroupBy = TRUE; $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups"; $this->_element[$name] = 1; $this->_tables['civicrm_group'] = 1; } elseif ($name === 'notes') { // if note field is subject then return subject else body of the note $noteColumn = 'note'; if (isset($noteField) && $noteField == 'note_subject') { $noteColumn = 'subject'; } $this->_useGroupBy = TRUE; $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.{$noteColumn})) as notes"; $this->_element[$name] = 1; $this->_tables['civicrm_note'] = 1; } elseif ($name === 'current_employer') { $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer"; $this->_element[$name] = 1; } } if ($cfID && !empty($field['is_search_range'])) { // this is a custom field with range search enabled, so we better check for two/from values if (!empty($this->_paramLookup[$name . '_from'])) { if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) { // search in the cdID array for the same grouping $fnd = FALSE; foreach ($this->_cfIDs[$cfID] as $cID => $c) { if ($c[3] == $p[3]) { $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2]; $fnd = TRUE; } } if (!$fnd) { $p[2] = array('from' => $p[2]); $this->_cfIDs[$cfID][] = $p; } } } if (!empty($this->_paramLookup[$name . '_to'])) { if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) { // search in the cdID array for the same grouping $fnd = FALSE; foreach ($this->_cfIDs[$cfID] as $cID => $c) { if ($c[4] == $p[4]) { $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2]; $fnd = TRUE; } } if (!$fnd) { $p[2] = array('to' => $p[2]); $this->_cfIDs[$cfID][] = $p; } } } } } // add location as hierarchical elements $this->addHierarchicalElements(); // add multiple field like website $this->addMultipleElements(); //fix for CRM-951 CRM_Core_Component::alterQuery($this, 'select'); CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select'); if (!empty($this->_cfIDs)) { // @todo This function is the select function but instead of running 'select' it // is running the whole query. $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields); $this->_customQuery->query(); $this->_select = array_merge($this->_select, $this->_customQuery->_select); $this->_element = array_merge($this->_element, $this->_customQuery->_element); $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables); $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables); $this->_options = $this->_customQuery->_options; } }
/** update method updates user details * @param Object $dbObj Database connectivity and manipulation object * @param string $dbTable name of the database table from which a user should be checked * @return string Success or error message */ public function update($dbObj, $dbTable) { $sql = "UPDATE {$dbTable} SET username = '******', firstname='{$this->fname}', lastname='{$this->lname}', role='{$this->role}' WHERE id = {$this->id} "; if ($this->notEmpty($this->id)) { $result = $dbObj->query($sql); if ($result !== false) { return 'success'; } else { return 'error'; } } else { return 'error'; } }
/** * Given a list of conditions in params and a list of desired * return Properties generate the required select and from * clauses. Note that since the where clause introduces new * tables, the initial attempt also retrieves all variables used * in the params list * * @return void * @access public */ function selectClause() { $properties = array(); $this->addSpecialFields(); // CRM_Core_Error::debug( 'f', $this->_fields ); // CRM_Core_Error::debug( 'p', $this->_params ); // CRM_Core_Error::debug( 'p', $this->_paramLookup ); foreach ($this->_fields as $name => $field) { // skip component fields // there are done by the alter query below // and need not be done on every field if (substr($name, 0, 12) == 'participant_' || substr($name, 0, 7) == 'pledge_' || substr($name, 0, 5) == 'case_') { continue; } // redirect to activity select clause if (substr($name, 0, 9) == 'activity_') { CRM_Activity_BAO_Query::select($this); continue; } // if this is a hierarchical name, we ignore it $names = explode('-', $name); if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) { continue; } $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if (CRM_Utils_Array::value($name, $this->_paramLookup) || CRM_Utils_Array::value($name, $this->_returnProperties)) { if ($cfID) { // add to cfIDs array if not present if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } } elseif (isset($field['where'])) { list($tableName, $fieldName) = explode('.', $field['where'], 2); if (isset($tableName)) { if (substr($tableName, 0, 6) == 'quest_') { $this->_select['ethnicity_id_1'] = 'ethnicity_id_1'; $this->_select['gpa_weighted_calc'] = 'gpa_weighted_calc'; $this->_select['SAT_composite'] = 'SAT_composite'; $this->_select['household_income_total'] = 'household_income_total'; } if (CRM_Utils_Array::value($tableName, self::$_dependencies)) { $this->_tables['civicrm_address'] = 1; $this->_select['address_id'] = 'civicrm_address.id as address_id'; $this->_element['address_id'] = 1; } if ($tableName == 'gender' || $tableName == 'individual_prefix' || $tableName == 'individual_suffix' || $tableName == 'im_provider' || $tableName == 'email_greeting' || $tableName == 'postal_greeting' || $tableName == 'addressee') { CRM_Core_OptionValue::select($this); if (in_array($tableName, array('email_greeting', 'postal_greeting', 'addressee'))) { //get display $greetField = "{$name}_display"; $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}"; $this->_element[$greetField] = 1; //get custom $greetField = "{$name}_custom"; $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}"; $this->_element[$greetField] = 1; } } else { $this->_tables[$tableName] = 1; // also get the id of the tableName $tName = substr($tableName, 8); if ($tName != 'contact') { $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id"; $this->_element["{$tName}_id"] = 1; } //special case for phone if ($name == 'phone') { $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id"; $this->_element['phone_type_id'] = 1; } // if IM then select provider_id also // to get "IM Service Provider" in a file to be exported, CRM-3140 if ($name == 'im') { $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id"; $this->_element['provider_id'] = 1; } if ($name == 'state_province') { $this->_select[$name] = "civicrm_state_province.abbreviation as `{$name}`, civicrm_state_province.name as state_province_name"; $this->_element['state_province_name'] = 1; } elseif ($tName == 'contact') { // special case, when current employer is set for Individual contact if ($fieldName == 'organization_name') { $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name"; } elseif ($fieldName != 'id') { $this->_select[$name] = "contact_a.{$fieldName} as `{$name}`"; } } else { $this->_select[$name] = "{$field['where']} as `{$name}`"; } $this->_element[$name] = 1; } } } elseif ($name === 'tags') { $this->_useGroupBy = TRUE; $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags"; $this->_element[$name] = 1; $this->_tables['civicrm_tag'] = 1; $this->_tables['civicrm_entity_tag'] = 1; } elseif ($name === 'groups') { $this->_useGroupBy = TRUE; $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups"; $this->_element[$name] = 1; $this->_tables['civicrm_group'] = 1; } elseif ($name === 'notes') { $this->_useGroupBy = TRUE; $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.note)) as notes"; $this->_element[$name] = 1; $this->_tables['civicrm_note'] = 1; } elseif ($name === 'current_employer') { $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer"; $this->_element[$name] = 1; } } if ($cfID && CRM_Utils_Array::value('is_search_range', $field)) { // this is a custom field with range search enabled, so we better check for two/from values if (CRM_Utils_Array::value($name . '_from', $this->_paramLookup)) { if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) { // search in the cdID array for the same grouping $fnd = FALSE; foreach ($this->_cfIDs[$cfID] as $cID => $c) { if ($c[3] == $p[3]) { $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2]; $fnd = TRUE; } } if (!$fnd) { $p[2] = array('from' => $p[2]); $this->_cfIDs[$cfID][] = $p; } } } if (CRM_Utils_Array::value($name . '_to', $this->_paramLookup)) { if (!array_key_exists($cfID, $this->_cfIDs)) { $this->_cfIDs[$cfID] = array(); } foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) { // search in the cdID array for the same grouping $fnd = FALSE; foreach ($this->_cfIDs[$cfID] as $cID => $c) { if ($c[4] == $p[4]) { $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2]; $fnd = TRUE; } } if (!$fnd) { $p[2] = array('to' => $p[2]); $this->_cfIDs[$cfID][] = $p; } } } } } // add location as hierarchical elements $this->addHierarchicalElements(); // add multiple field like website $this->addMultipleElements(); //fix for CRM-951 CRM_Core_Component::alterQuery($this, 'select'); if (!empty($this->_cfIDs)) { $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE); $this->_customQuery->query(); $this->_select = array_merge($this->_select, $this->_customQuery->_select); $this->_element = array_merge($this->_element, $this->_customQuery->_element); $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables); $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables); $this->_options = $this->_customQuery->_options; } }
/** * Shot a query to database * * It sends $query to database handler and build a result set. If $return_raw is * set to true, method resultsToArray() will not be invoked and this will return * query's result as it is. If false, result will be returned as a standard array * composed by: * * - "data": array of fetched data * - "length": result length * - "id": transaction id (if any) * - "affected_rows": affected rows (if any) * * @param string $query * @param bool $return_raw * * @return Object $this */ public function query($query, $return_raw = false) { switch ($this->model) { case "MYSQLI": $response = $this->dbh->query($query); if (!$response) { throw new DatabaseException($this->dbh->error, $this->dbh->errno); } break; case "MYSQL_PDO": case "ORACLE_PDO": case "SQLITE_PDO": case "DBLIB_PDO": try { $response = $this->dbh->prepare($query); $response->execute(); } catch (\PDOException $e) { throw new DatabaseException($e->getMessage(), (int) $e->getCode()); } break; case "DB2": $response = db2_exec($this->dbh, $query); if (!$response) { throw new DatabaseException(db2_stmt_error()); } break; case "POSTGRESQL": $response = pg_query($this->dbh, $query); if (!$response) { throw new DatabaseException(pg_last_error()); } break; } if ($return_raw) { $return = $response; } else { try { $return = $this->resultsToArray($response); } catch (DatabaseException $e) { throw $e; } } return $return; }