Example #1
0
 /**
  * Write online information to the database
  *
  * @param int    $uid    UID of the active user
  * @param string $uname  Username
  * @param int    $time   Timestamp
  * @param int    $module Current module id
  * @param string $ip     User's IP address
  *
  * @internal param string $timestamp
  * @return bool TRUE on success
  */
 public function write($uid, $uname, $time, $module, $ip)
 {
     $uid = (int) $uid;
     $uname = $this->db->quote($uname);
     $time = (int) $time;
     $module = (int) $module;
     $ip = $this->db->quote($ip);
     if ($uid > 0) {
         $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('online') . " WHERE online_uid={$uid}";
     } else {
         $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('online') . " WHERE online_uid={$uid} AND online_ip={$ip}";
     }
     list($count) = $this->db->fetchRow($this->db->queryF($sql));
     if ($count > 0) {
         $sql = 'UPDATE ' . $this->db->prefix('online') . " SET online_updated = {$time}, online_module = {$module} WHERE online_uid = {$uid}";
         if ($uid === 0) {
             $sql .= " AND online_ip={$ip}";
         }
     } else {
         $sql = sprintf('INSERT INTO %s (online_uid, online_uname, online_updated, online_ip, online_module)' . ' VALUES (%u, %s, %u, %s, %u)', $this->db->prefix('online'), $uid, $uname, $time, $ip, $module);
     }
     if (!$this->db->queryF($sql)) {
         return false;
     }
     return true;
 }
Example #2
0
 /**
  * Set value for specific key
  *
  * @param  string $key
  * @param  mixed $value
  */
 public function set($key, $value)
 {
     $value = $this->connection->quote(json_encode($value, JSON_NUMERIC_CHECK));
     if ($this->exists($key)) {
         $sql = "UPDATE storage SET `keyval`={$value} WHERE `key`='{$key}'";
     } else {
         $sql = "INSERT INTO storage (`key`,`keyval`) VALUES ('{$key}',{$value})";
     }
     $this->connection->exec($sql);
 }
 /**
  * Change password for user in the storage container
  *
  * @param string Username
  * @param string The new password (plain text)
  */
 function changePassword($username, $password)
 {
     $this->log('Auth_Container_MDB2::changePassword() called.', AUTH_LOG_DEBUG);
     // Prepare for a database query
     $err = $this->_prepare();
     if ($err !== true) {
         return PEAR::raiseError($err->getMessage(), $err->getCode());
     }
     if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {
         $cryptFunction = 'strval';
     } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {
         $cryptFunction = $this->options['cryptType'];
     } else {
         $cryptFunction = 'md5';
     }
     $password = $cryptFunction($password);
     $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", $this->options['final_table'], $this->options['final_passwordcol'], $this->db->quote($password, 'text'), $this->options['final_usernamecol'], $this->db->quote($username, 'text'));
     // check if there is an optional parameter db_where
     if ($this->options['db_where'] != '') {
         // there is one, so add it to the query
         $query .= " AND " . $this->options['db_where'];
     }
     $this->log('Running SQL against MDB2: ' . $query, AUTH_LOG_DEBUG);
     $res = $this->query($query);
     if (MDB2::isError($res)) {
         return PEAR::raiseError($res->getMessage(), $res->code);
     }
     return true;
 }
Example #4
0
 /**
  * Inserts $message to the currently open database.  Calls open(),
  * if necessary.  Also passes the message along to any Log_observer
  * instances that are observing this Log.
  *
  * @param mixed  $message  String or object containing the message to log.
  * @param string $priority The priority of the message.  Valid
  *                  values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT,
  *                  PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING,
  *                  PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG.
  * @return boolean  True on success or false on failure.
  * @access public     
  */
 function log($message, $priority = null)
 {
     /* If a priority hasn't been specified, use the default value. */
     if ($priority === null) {
         $priority = $this->_priority;
     }
     /* Abort early if the priority is above the maximum logging level. */
     if (!$this->_isMasked($priority)) {
         return false;
     }
     /* If the connection isn't open and can't be opened, return failure. */
     if (!$this->_opened && !$this->open()) {
         return false;
     }
     /* Extract the string representation of the message. */
     $message = $this->_extractMessage($message);
     /* Build the SQL query for this log entry insertion. */
     $id = $this->_db->nextId('log_id');
     $q = sprintf('insert into %s (id, logtime, ident, priority, message)' . 'values(%d, CURRENT_TIMESTAMP, %s, %d, %s)', $this->_table, $id, $this->_db->quote($this->_ident), $priority, $this->_db->quote($message));
     $result = $this->_db->query($q);
     if (DB::isError($result)) {
         return false;
     }
     $this->_announce(array('priority' => $priority, 'message' => $message));
     return true;
 }
Example #5
0
 /**
  * Garbage collection class function - handles removal of old sessions (Called by
  * PHP internally, based on session.gc_probability and session.gc_divisor values)
  *
  * @param int $lifetime
  * @return bool
  */
 function session_gc($lifetime)
 {
     global $db_prefix;
     $query = "DELETE FROM {$db_prefix}sessions WHERE session_modified < " . $this->_db_object->quote(time() - $this->_session_options['session_lifetime'], 'integer');
     $this->_db_object->query($query);
     return true;
 }
Example #6
0
 /**
  * Remove module entries from the appropriate table, depending on the Joomla version
  *
  * @param   string  $name    Plugin name
  * @param   int     $client  Client (site=0, admin=1)
  * @return  bool
  **/
 public function deleteModuleEntry($element, $client = null)
 {
     if ($this->baseDb->tableExists('#__extensions')) {
         // Delete module entry
         $query = "DELETE FROM `#__extensions` WHERE `element` = '{$element}'" . (isset($client) ? " AND `client_id` = " . $this->baseDb->quote($client) : '');
         $this->baseDb->setQuery($query);
         $this->baseDb->query();
         // See if entries are present in #__modules table as well
         $query = "SELECT `id` FROM `#__modules` WHERE `module` = '{$element}'" . (isset($client) ? " AND `client_id` = " . $this->baseDb->quote($client) : '');
         $this->baseDb->setQuery($query);
         $ids = $this->baseDb->loadColumn();
         if ($ids && count($ids) > 0) {
             // Delete modules and module menu entries
             $query = "DELETE FROM `#__modules` WHERE `id` IN (" . implode(',', $ids) . ")";
             $this->baseDb->setQuery($query);
             $this->baseDb->query();
             $query = "DELETE FROM `#__modules_menu` WHERE `moduleid` IN (" . implode(',', $ids) . ")";
             $this->baseDb->setQuery($query);
             $this->baseDb->query();
         }
     } else {
         $query = "SELECT `id` FROM `#__modules` WHERE `module` = '{$element}'" . (isset($client) ? " AND `client_id` = " . $this->baseDb->quote($client) : '');
         $this->baseDb->setQuery($query);
         $ids = $this->baseDb->loadColumn();
         if ($ids && count($ids) > 0) {
             // Delete modules and module menu entries
             $query = "DELETE FROM `#__modules` WHERE `id` IN (" . implode(',', $ids) . ")";
             $this->baseDb->setQuery($query);
             $this->baseDb->query();
             $query = "DELETE FROM `#__modules_menu` WHERE `moduleid` IN (" . implode(',', $ids) . ")";
             $this->baseDb->setQuery($query);
             $this->baseDb->query();
         }
     }
 }
Example #7
0
 /**
  * Load a {@link Xmf_Object} object from the database
  *
  * @access protected
  *
  * @param   mixed    $id     ID
  * @param   array    $fields    fields to fetch
  * @return  object  {@link XoopsObject}
  **/
 function &get($id = null, $fields = null)
 {
     $object = null;
     if (empty($id)) {
         $object = $this->create();
         return $object;
     }
     if (is_array($fields) && count($fields) > 0) {
         $select = implode(",", $fields);
         if (!in_array($this->keyName, $fields)) {
             $select .= ", " . $this->keyName;
         }
     } else {
         $select = "*";
     }
     $sql = "SELECT {$select} FROM {$this->table} WHERE {$this->keyName} = " . $this->db->quote($id);
     if (!($result = $this->db->query($sql))) {
         return $object;
     }
     if (!$this->db->getRowsNum($result)) {
         return $object;
     }
     $object =& $this->create(false);
     $object->assignVars($this->db->fetchArray($result));
     return $object;
 }
Example #8
0
 /**
  * bindParam()
  *
  * @access public
  * @param  string $sQuery
  * @param  array  $aryParams
  * @return mixed             string | PEAR_Error
  */
 function bindParam($sQuery, $aryParams)
 {
     $objStatement = $this->_objWork->prepare($sQuery);
     $objStatement->bindValueArray($aryParams);
     $sRealquery = '';
     $iLastPosition = 0;
     foreach ($objStatement->positions as $iCurrentPosition => $sParameter) {
         if (!array_key_exists($sParameter, $objStatement->values)) {
             return PEAR::raiseError(null, MDB2_ERROR_NOT_FOUND, null, null, 'Unable to bind to missing placeholder: ' . $sParameter, __FUNCTION__);
         }
         $sValue = $objStatement->values[$sParameter];
         $sRealquery .= substr($sQuery, $iLastPosition, $iCurrentPosition - $iLastPosition);
         if ('' == $sValue) {
             $sValueQuoted = 'NULL';
         } else {
             $sValueQuoted = $this->_objWork->quote($sValue);
             if (PEAR::isError($sValueQuoted)) {
                 return $sValueQuoted;
             }
         }
         $sRealquery .= $sValueQuoted;
         $iLastPosition = $iCurrentPosition + 1;
     }
     $sRealquery .= substr($sQuery, $iLastPosition);
     $objStatement->free();
     return $sRealquery;
 }
Example #9
0
 /**
  * Executes a query
  *
  * @access  public
  * @param   string  SQL To Execute
  * @param   array   Array that has the params to replace
  * @return  string  parsed sql string with [[table]] and {field} replaced
  */
 function sqlParse($sql, $params = null)
 {
     $sql = preg_replace_callback('@\\[\\[(.*?)\\]\\]@sm', array($this, 'quoteIdentifier'), $sql);
     $sql = preg_replace_callback('@\\[(.*?)\\]@sm', array($this, 'quoteIdentifier'), $sql);
     if (is_array($params)) {
         foreach ($params as $key => $param) {
             if (is_array($param)) {
                 $value = $param['value'];
                 $type = $param['type'];
             } else {
                 $value = $param;
                 $type = null;
             }
             //Add "N" character before text field value,
             //when using FreeTDS as MSSQL driver, to supporting unicode text
             if ($this->_dsn['phptype'] == 'mssql' && is_string($value) && $this->Is_FreeTDS_MSSQL_Driver()) {
                 $value = 'N' . $this->dbc->quote($value, $type);
             } else {
                 $value = $this->dbc->quote($value, $type);
             }
             $sql = str_replace('{' . $key . '}', $value, $sql);
         }
     }
     $GLOBALS['log']->Log(JAWS_LOG_DEBUG, "Query:\n" . $sql, 2);
     return $sql;
 }
Example #10
0
 /**
  * LiveUser_Auth_Container_MDB2::userExists()
  *
  * Helper function that checks if there is a user in
  * the database who's matching the given parameters.
  * If $checkHandle is given and $checkPW is set to
  * false, it only checks if a user with that handle
  * exists. If only $checkPW is given and $checkHandle
  * is set to false, it will check if there exists a
  * user with that password. If both values are set to
  * anything but false, it will find the first user in
  * the database with both values matching.
  * Please note:
  * - If no match was found, the return value is false
  * - If a match was found, the auth_user_id from the database
  *   is being returned
  * Whatever is returned, please keep in mind that this
  * function only searches for the _first_ occurence
  * of the search values in the database. So when you
  * have multiple users with the same handle, only the
  * ID of the first one is returned. Same goes for
  * passwords. Searching for both password and handle
  * should be pretty safe, though - having more than
  * one user with the same handle/password combination
  * in the database would be pretty stupid anyway.
  *
  * @param boolean $checkHandle  The handle (username) to search
  * @param boolean $checkPW      The password to check against
  * @return mixed  auth_user_id DB error or false if the user does not exist
  */
 function userExists($checkHandle = false, $checkPW = false)
 {
     if (!$this->init_ok) {
         return false;
     }
     if ($checkHandle !== false && $checkPW === false) {
         // only search for the first user with the given handle
         $sql = 'SELECT ' . $this->authTableCols['user_id']['name'] . '
                    FROM ' . $this->authTable . '
                    WHERE ' . $this->authTableCols['handle']['name'] . '=' . $this->dbc->quote($checkHandle, $this->authTableCols['handle']['type']);
     } elseif ($checkHandle === false && $checkPW !== false) {
         // only search for the first user with the given password
         $sql = 'SELECT ' . $this->authTableCols['user_id']['name'] . '
                    FROM ' . $this->authTable . '
                    WHERE ' . $this->authTableCols['handle']['name'] . '=' . $this->dbc->quote($this->encryptPW($checkPW), $this->authTableCols['passwd']['type']);
     } else {
         // check for a user with both handle and password matching
         $sql = 'SELECT ' . $this->authTableCols['user_id']['name'] . '
                     FROM ' . $this->authTable . '
                     WHERE ' . $this->authTableCols['handle']['name'] . '=' . $this->dbc->quote($checkHandle, $this->authTableCols['handle']['type']) . '
                     AND ' . $this->authTableCols['passwd']['name'] . '=' . $this->dbc->quote($this->encryptPW($checkPW), $this->authTableCols['passwd']['type']);
     }
     $result = $this->dbc->queryOne($sql, $this->authTableCols['user_id']['type']);
     if (MDB2::isError($result)) {
         return $result;
     }
     if (is_null($result)) {
         return false;
     }
     return true;
 }
 /**
  * Quoting for DB with change empty strings to NULL statement
  *
  * @param string $s
  *
  * @return string
  * @access public
  */
 public function quote($s, $null = false)
 {
     if ($null && '' == $s) {
         return 'NULL';
     } else {
         return self::$db->quote($s);
     }
 }
 function escape_string($string)
 {
     $string = $this->db->quote($string);
     // Remove ' from the begginging of the string and at the end of the string, because we already use it in insert_query
     $string = substr($string, 1);
     $string = substr($string, 0, -1);
     return $string;
 }
Example #13
0
 /**
  * Get list extra id belong to $roomtypeId
  *
  * @param   int $roomtypeId
  *
  * @return  array
  */
 public function getExtra($roomtypeId)
 {
     $query = $this->_dbo->getQuery(true);
     $query->select('extra_id')->from($this->_dbo->quoteName('#__sr_room_type_extra_xref'));
     $query->where('room_type_id = ' . $this->_dbo->quote($roomtypeId));
     $this->_dbo->setQuery($query);
     return $this->_dbo->loadColumn();
 }
 /**
  * Quoting for DB with change empty strings to NULL statement
  *
  * @param string $s
  *
  * @return string
  * @access public
  */
 public function quotenull($s)
 {
     if ('' == $s) {
         return 'NULL';
     } else {
         return $this->db->quote($s);
     }
 }
Example #15
0
 /**
  * Store extra information
  *
  * @param  int      $reservationId
  * @param  int      $roomId
  * @param  string   $roomLabel
  * @param  int      $extraId
  * @param  string   $extraName
  * @param  int      $extraQuantity The extra quantity or NULL if extra does not have quantity
  * @param  int      $price
  *
  * @return void
  */
 public function storeExtra($reservationId, $roomId, $roomLabel, $extraId, $extraName, $extraQuantity = NULL, $price = 0)
 {
     $query = $this->_dbo->getQuery(true);
     $query->insert($this->_dbo->quoteName('#__sr_reservation_room_extra_xref'));
     $query->columns(array($this->_dbo->quoteName('reservation_id'), $this->_dbo->quoteName('room_id'), $this->_dbo->quoteName('room_label'), $this->_dbo->quoteName('extra_id'), $this->_dbo->quoteName('extra_name'), $this->_dbo->quoteName('extra_quantity'), $this->_dbo->quoteName('extra_price')));
     $query->values($this->_dbo->quote($reservationId) . ',' . $this->_dbo->quote($roomId) . ',' . $this->_dbo->quote($roomLabel) . ',' . $this->_dbo->quote($extraId) . ',' . $this->_dbo->quote($extraName) . ',' . ($extraQuantity === NULL ? NULL : $this->_dbo->quote($extraQuantity)) . ',' . $this->_dbo->quote($price));
     $this->_dbo->setQuery($query);
     $this->_dbo->execute();
 }
Example #16
0
 /**
  * Gets all users with handle, passwd, auth_user_id
  * lastlogin, is_active and individual rights.
  *
  * The array will look like this:
  * <code>
  * $userData[0]['auth_user_id'] = 'wujha433gawefawfwfiuj2ou9823r98h';
  *             ['handle']       = 'myLogin';
  *             ['passwd']       = 'd346gs2gwaeiuhaeiuuweijfjuwaefhj';
  *             ['lastlogin']    = 1254801292; (Unix timestamp)
  *             ['is_active']    = 1; (1 = yes, 0 = no)
  *             ['owner_user_id']    = 1;
  *             ['owner_group_id']   = 1;
  * </code>
  *
  * Filters can be either complex or simple.
  *
  * In their simple form you just need to pass an associative array
  * with key/value, the key will be the table field name and value the value
  * you are searching. It will consider that you want an do to do a
  * field=value comparison, every additinnal filter will be appended with AND
  *
  * The complicated form of filters is to pass an array such as
  *
  * array(
  *     'fieldname' => array('op' => '>', 'value' => 'dummy', 'cond' => '', type = 'text'),
  *     'fieldname' => array('op' => '<', 'value' => 'dummy2', 'cond' => 'OR', 'type' = 'text'),
  * );
  *
  * It can then build relatively complex queries. If you need joins or more
  * complicated queries than that please consider using an alternative
  * solution such as PEAR::DB_DataObject
  *
  * Any aditional field will be returned. The array key will be of the same
  * case it is given.
  *
  *  $cols = array(
  *   array('name' => 'myField', 'type' => 'text'),
  * );
  *
  * e.g.: getUsers(null, $cols) will return
  *
  * <code>
  * $userData[0]['auth_user_id'] = 'wujha433gawefawfwfiuj2ou9823r98h';
  *             ['handle']       = 'myLogin';
  *             ['passwd']       = 'd346gs2gwaeiuhaeiuuweijfjuwaefhj';
  *             ['myField']      = 'value';
  * </code>
  *
  * @access  public
  * @param   array  filters to apply to fetched data
  * @param   string  if not null 'ORDER BY $order' will be appended to the query
  * @param   boolean will return an associative array with the auth_user_id
  *                  as the key by using DB::getAssoc() instead of DB::getAll()
  * @return  mixed  Array with user data or DB error.
  */
 function getUsers($filters = array(), $order = null, $rekey = false)
 {
     if (!$this->init_ok) {
         return false;
     }
     $fields = $where = '';
     if (isset($this->authTableCols['optional']['lastlogin'])) {
         $customFields[$this->authTableCols['optional']['lastlogin']['name'] . ' AS lastlogin'] = $this->authTableCols['optional']['lastlogin']['type'];
     }
     if (isset($this->authTableCols['optional']['is_active'])) {
         $customFields[$this->authTableCols['optional']['is_active']['name'] . ' AS is_active'] = $this->authTableCols['optional']['is_active']['type'];
     }
     if (isset($this->authTableCols['optional']['owner_user_id'])) {
         $customFields[$this->authTableCols['optional']['owner_user_id']['name'] . ' AS owner_user_id'] = $this->authTableCols['optional']['owner_user_id']['type'];
     }
     if (isset($this->authTableCols['optional']['owner_group_id'])) {
         $customFields[$this->authTableCols['optional']['owner_group_id']['name'] . ' AS owner_group_id'] = $this->authTableCols['optional']['owner_group_id']['type'];
     }
     $cTypes = array();
     if (sizeof($this->authTableCols['custom']) > 0) {
         foreach ($this->authTableCols['custom'] as $alias => $field_data) {
             $cFields[] = $field_data['name'] . ' AS ' . $alias;
             $cTypes[] = $field_data['type'];
         }
         $fields = ',';
         $fields .= implode(',', $cFields);
     }
     if (sizeof($filters) > 0) {
         $where = ' WHERE';
         foreach ($filters as $f => $v) {
             if (is_array($v)) {
                 $cond = ' ' . $v['cond'];
                 $where .= ' ' . $v['name'] . $v['op'] . $this->dbc->quote($v['value'], $v['type']) . $cond;
             } else {
                 $cond = ' AND';
                 $where .= " {$f}={$v}" . $cond;
             }
         }
         $where = substr($where, 0, -strlen($cond));
     }
     if (!is_null($order)) {
         $order = ' ORDER BY ' . $order;
     }
     // First: Get all data from auth table.
     $query = '
         SELECT
             ' . $this->authTableCols['required']['auth_user_id']['name'] . ' AS auth_user_id,
             ' . $this->authTableCols['required']['handle']['name'] . ' AS handle,
             ' . $this->authTableCols['required']['passwd']['name'] . ' AS passwd
             ' . $fields . '
         FROM
             ' . $this->authTable . $where . $order;
     $types = array($this->authTableCols['required']['auth_user_id']['type'], $this->authTableCols['required']['handle']['type'], $this->authTableCols['required']['passwd']['type']);
     $types = array_merge($types, $cTypes);
     $res = $this->dbc->queryAll($query, $types, MDB2_FETCHMODE_ASSOC, $rekey);
     return $res;
 }
Example #17
0
 /**
  * Process a single record
  *
  * @param   integer  $id
  * @return  object
  */
 public function record($id)
 {
     if (strstr($id, ':')) {
         list($id, $revision) = explode(':', $id);
     }
     $id = intval($id);
     if (!isset($revision)) {
         $revision = 0;
     }
     $this->database->setQuery("SELECT pv.*, pv.doi AS identifier, rt.alias AS type, pv.publication_id\n\t\t\tFROM `#__publication_versions` AS pv\n\t\t\tINNER JOIN `#__publications` AS p ON p.id = pv.publication_id\n\t\t\tINNER JOIN `#__publication_categories` AS rt ON rt.id = p.category\n\t\t\tWHERE pv.id = " . $this->database->quote($id));
     $record = $this->database->loadObject();
     $record->version_id = $record->id;
     $id = $record->publication_id;
     $record->id = $id;
     if (!$record->identifier) {
         $record->identifier = self::$base . '/' . ltrim(\Route::url('index.php?option=com_publications&id=' . $id . ($record->version_id ? '&v=' . $record->version_id : '')), '/');
     }
     $record->base = $this->name();
     $record->type = $record->base . ':' . $record->type;
     $record->description = strip_tags($record->description);
     $record->description = trim($record->description);
     $this->database->setQuery("SELECT pv.submitted\n\t\t\tFROM `#__publication_versions` pv, `#__publications` p\n\t\t\tWHERE p.id = pv.publication_id AND p.id = " . $this->database->quote($id) . "\n\t\t\tORDER BY pv.submitted DESC LIMIT 1");
     $record->date = $this->database->loadResult();
     $this->database->setQuery("SELECT pa.name\n\t\t\tFROM `#__publication_authors` pa, `#__publication_versions` pv, `#__publications` p\n\t\t\tWHERE pa.publication_version_id = pv.id AND pa.role != 'submitter' AND pv.publication_id = p.id AND p.id=" . $this->database->quote($id) . "\n\t\t\tORDER BY pa.name");
     $record->creator = $this->database->loadColumn();
     $this->database->setQuery("SELECT DISTINCT t.raw_tag\n\t\t\tFROM `#__tags` t, `#__tags_object` tos\n\t\t\tWHERE t.id = tos.tagid AND tos.objectid=" . $this->database->quote($id) . " AND tos.tbl='publications' AND t.admin=0\n\t\t\tORDER BY t.raw_tag");
     $record->subject = $this->database->loadColumn();
     // Relations
     $record->relation = array();
     $this->database->setQuery("SELECT *\n\t\t\tFROM `#__citations` AS a\n\t\t\tLEFT JOIN `#__citations_assoc` AS n ON n.`cid`=a.`id`\n\t\t\tWHERE n.`tbl`='publication' AND n.`oid`=" . $this->database->quote($id) . " AND n.`type`='owner' AND a.`published`=1\n\t\t\tORDER BY `year` DESC");
     $references = $this->database->loadObjectList();
     if (count($references) && file_exists(PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'format.php')) {
         include_once PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'format.php';
         $formatter = new \Components\Citations\Helpers\Format();
         $formatter->setTemplate('apa');
         foreach ($references as $reference) {
             $cite = strip_tags(html_entity_decode($reference->formatted ? $reference->formatted : \Components\Citations\Helpers\Format::formatReference($reference, '')));
             $cite = str_replace('&quot;', '"', $cite);
             $record->relation[] = array('type' => 'isReferencedBy', 'value' => trim($cite));
         }
     }
     $this->database->setQuery("SELECT *\n\t\t\tFROM `#__citations` AS a\n\t\t\tLEFT JOIN `#__citations_assoc` AS n ON n.`cid`=a.`id`\n\t\t\tWHERE n.`tbl`='publication' AND n.`oid`=" . $this->database->quote($id) . " AND n.`type`!='owner' AND a.`published`=1\n\t\t\tORDER BY `year` DESC");
     $references = $this->database->loadObjectList();
     if (count($references) && file_exists(PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'format.php')) {
         include_once PATH_CORE . DS . 'components' . DS . 'com_citations' . DS . 'helpers' . DS . 'format.php';
         $formatter = new \Components\Citations\Helpers\Format();
         $formatter->setTemplate('apa');
         foreach ($references as $reference) {
             $cite = strip_tags(html_entity_decode($reference->formatted ? $reference->formatted : \Components\Citations\Helpers\Format::formatReference($reference, '')));
             $cite = str_replace('&quot;', '"', $cite);
             $record->relation[] = array('type' => 'references', 'value' => trim($cite));
         }
     }
     return $record;
 }
Example #18
0
 /**
  * Checks if a preference exists in the database.  
  *
  * @param string $user_id The userid of the preference owner.
  * @param string $pref_id The preference to check for.
  * @return bool True if the preference exists.
  * @access private
  */
 function _exists($user_id, $pref_id)
 {
     $query = sprintf("SELECT COUNT(%s) FROM %s WHERE %s=%s AND %s=%s", $this->_nameColumn, $this->_table, $this->_userColumn, $this->_db->quoteSmart($user_id), $this->_nameColumn, $this->_db->quote($pref_id));
     $result = $this->_db->getOne($query);
     if (DB::isError($result)) {
         $this->_lastError = "DB Error: " . $result->getMessage();
         return false;
     } else {
         return (bool) $result;
     }
 }
Example #19
0
 /**
  * Set the default configuration values
  *
  * @return     boolean True on success, false on errors
  */
 public function loadDefaults()
 {
     $config = array('adminmail' => '', 'adminlevel' => '0', 'starday' => '0', 'mailview' => 'NO', 'byview' => 'NO', 'hitsview' => 'NO', 'repeatview' => 'NO', 'dateformat' => '0', 'calUseStdTime' => 'NO', 'navbarcolor' => '', 'startview' => 'month', 'calEventListRowsPpg' => '30', 'calSimpleEventForm' => 'NO', 'defColor' => '', 'calForceCatColorEventForm' => 'NO', 'fields' => '');
     foreach ($config as $p => $v) {
         $this->_db->setQuery("INSERT INTO {$this->_tbl} (param, value) VALUES (" . $this->_db->quote($p) . ", " . $this->_db->quote($v) . ")");
         if (!$this->_db->query()) {
             return false;
         }
     }
     return true;
 }
Example #20
0
 /**
  * from an associative array ([filed]=value) return the where statement
  *
  * @param array     associative array ([field]=param)
  * @param string    where condition (AND or OR. Default AND)
  * @return string   return the where condition generated
  * @access private
  */
 private function array2Where($array, $operator = 'AND')
 {
     $out = array();
     foreach ($array as $key => $val) {
         if ($val === null) {
             $out[] = $key . ' IS NULL';
         } else {
             $out[] = $key . ' = ' . $this->db->quote($val);
         }
     }
     return implode(' ' . $operator . ' ', $out);
 }
Example #21
0
 /**
  * Write a session to the database
  *
  * @param string $sess_id
  * @param string $sess_data
  *
  * @return bool
  **/
 public function write($sess_id, $sess_data)
 {
     $remoteAddress = \Xmf\IPAddress::fromRequest()->asReadable();
     $sess_id = $this->db->quoteString($sess_id);
     $sql = sprintf('UPDATE %s SET sess_updated = %u, sess_data = %s WHERE sess_id = %s', $this->db->prefix('session'), time(), $this->db->quoteString($sess_data), $sess_id);
     $this->db->queryF($sql);
     if (!$this->db->getAffectedRows()) {
         $sql = sprintf('INSERT INTO %s (sess_id, sess_updated, sess_ip, sess_data) VALUES (%s, %u, %s, %s)', $this->db->prefix('session'), $sess_id, time(), $this->db->quote($remoteAddress), $this->db->quote($sess_data));
         return $this->db->queryF($sql);
     }
     return true;
 }
 /**
  * 对字符串进行转义,提高数据库操作安全
  *
  * @access public
  *
  * @param string $value 待转义的字符串内容
  *
  * @return string
  */
 public function escape($value = null)
 {
     //参数分析
     if (is_null($value)) {
         return null;
     }
     if (!is_array($value)) {
         return trim($this->_dbLink->quote($value));
     }
     //当参数为数组时
     return array_map(array($this, 'escape'), $value);
 }
Example #23
0
 /**
  * Get the stringID for the given string
  *
  * @param string $stringID
  * @param string $pageID
  * @return string
  */
 function getStringID($string, $pageID = null)
 {
     $lang_col = $this->_getLangCol($this->currentLang['id']);
     $table = $this->_getLangTable($this->currentLang['id']);
     $query = sprintf('SELECT %s FROM %s WHERE %s = %s AND %s', $this->db->quoteIdentifier($this->options['string_id_col'], true), $this->db->quoteIdentifier($table, true), $this->db->quoteIdentifier($lang_col, true), $this->db->quote($string, 'text'), $this->db->quoteIdentifier($this->options['string_page_id_col'], true));
     if (is_null($pageID)) {
         $query .= ' IS NULL';
     } else {
         $query .= ' = ' . $this->db->quote($pageID, 'text');
     }
     ++$this->_queries;
     return $this->db->queryOne($query);
 }
Example #24
0
 /**
  * Reads user data from the given data source
  * If only $handle is given, it will read the data
  * from the first user with that handle and return
  * true on success.
  * If $handle and $passwd are given, it will try to
  * find the first user with both handle and password
  * matching and return true on success (this allows
  * multiple users having the same handle but different
  * passwords - yep, some people want this).
  * if only an auth_user_id is passed it will try to read the data based on the id
  * If no match is found, false is being returned.
  *
  * @param  string user handle
  * @param  string user password
  * @param  bool|int if the user data should be read using the auth user id
  * @return bool true on success or false on failure
  *
  * @access public
  */
 function readUserData($handle = '', $passwd = '', $auth_user_id = false)
 {
     $fields = array();
     foreach ($this->tables['users']['fields'] as $field => $req) {
         $fields[] = $this->alias[$field] . ' AS ' . $field;
     }
     // Setting the default query.
     $query = 'SELECT ' . implode(',', $fields) . '
                FROM ' . $this->prefix . $this->alias['users'] . '
                WHERE  ';
     if ($auth_user_id) {
         $query .= $this->alias['auth_user_id'] . '=' . $this->dbc->quote($auth_user_id);
     } else {
         if (!is_array($this->handles) || empty($this->handles)) {
             $this->stack->push(LIVEUSER_ERROR_CONFIG, 'exception', array('reason' => 'No handle set in storage config.'));
             return false;
         }
         $handles = array();
         foreach ($this->handles as $field) {
             $handles[] = $this->alias[$field] . '=' . $this->dbc->quote($handle);
         }
         $query .= '(' . implode(' OR ', $handles) . ')';
         if (!is_null($this->tables['users']['fields']['passwd'])) {
             // If $passwd is set, try to find the first user with the given
             // handle and password.
             $query .= ' AND   ' . $this->alias['passwd'] . '=' . $this->dbc->quote($this->encryptPW($passwd));
         }
     }
     // Query database
     $res = $this->dbc->query($query);
     if ($res === false) {
         $error_info = $this->dbc->errorInfo();
         $this->stack->push(LIVEUSER_ERROR, 'exception', array('reason' => $error_info[2], 'debug' => $query));
         return false;
     }
     $result = $res->fetch(PDO::FETCH_ASSOC);
     if ($result === false && $this->dbc->errorCode() != '00000') {
         $this->stack->push(LIVEUSER_ERROR, 'exception', array('reason' => $this->dbc->errorCode(), 'debug' => $this->dbc->errorInfo()));
         return false;
     }
     if (!is_array($result)) {
         return null;
     }
     // User was found, read data into class variables and set return value to true
     if (array_key_exists('lastlogin', $result) && !empty($result['lastlogin'])) {
         $result['lastlogin'] = strtotime($result['lastlogin']);
     }
     $this->propertyValues = $result;
     return true;
 }
Example #25
0
 /**
  * Generic check for whether dependancies exist for this object in the database schema
  *
  * Can be overloaded/supplemented by the child class
  *
  * @param   mixed  $pk     An optional primary key value check the row for.  If not
  * set the instance property value is used.
  * @param   array  $joins  An optional array to compiles standard joins formatted like:
  * [label => 'Label', name => 'table name' , idfield => 'field', joinfield => 'field']
  *
  * @return  boolean  True on success.
  *
  * @deprecated    12.1
  * @link    http://docs.joomla.org/JTable/canDelete
  * @since   11.1
  */
 public function canDelete($pk = null, $joins = null)
 {
     // Deprecation warning.
     JLog::add('JTable::canDelete() is deprecated.', JLog::WARNING, 'deprecated');
     // Initialise variables.
     $k = $this->_tbl_key;
     $pk = is_null($pk) ? $this->{$k} : $pk;
     // If no primary key is given, return false.
     if ($pk === null) {
         return false;
     }
     if (is_array($joins)) {
         // Get a query object.
         $query = $this->_db->getQuery(true);
         // Setup the basic query.
         $query->select($this->_db->quoteName($this->_tbl_key));
         $query->from($this->_db->quoteName($this->_tbl));
         $query->where($this->_db->quoteName($this->_tbl_key) . ' = ' . $this->_db->quote($this->{$k}));
         $query->group($this->_db->quoteName($this->_tbl_key));
         // For each join add the select and join clauses to the query object.
         foreach ($joins as $table) {
             $query->select('COUNT(DISTINCT ' . $table['idfield'] . ') AS ' . $table['idfield']);
             $query->join('LEFT', $table['name'] . ' ON ' . $table['joinfield'] . ' = ' . $k);
         }
         // Get the row object from the query.
         $this->_db->setQuery((string) $query, 0, 1);
         $row = $this->_db->loadObject();
         // Check for a database error.
         if ($this->_db->getErrorNum()) {
             $this->setError($this->_db->getErrorMsg());
             return false;
         }
         $msg = array();
         $i = 0;
         foreach ($joins as $table) {
             $k = $table['idfield'] . $i;
             if ($obj->{$k}) {
                 $msg[] = JText::_($table['label']);
             }
             $i++;
         }
         if (count($msg)) {
             $this->setError("noDeleteRecord" . ": " . implode(', ', $msg));
             return false;
         } else {
             return true;
         }
     }
     return true;
 }
Example #26
0
 /**
  * Change password for user in the storage container
  *
  * @param string Username
  * @param string The new password (plain text)
  */
 function changePassword($username, $password)
 {
     if (isset($this->options['cryptType']) && $this->options['cryptType'] == 'none') {
         $cryptFunction = 'strval';
     } elseif (isset($this->options['cryptType']) && function_exists($this->options['cryptType'])) {
         $cryptFunction = $this->options['cryptType'];
     } else {
         $cryptFunction = 'md5';
     }
     $password = $cryptFunction($password);
     $query = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", $this->options['table'], $this->options['passwordcol'], $this->db->quote($password, 'text'), $this->options['usernamecol'], $this->db->quote($username, 'text'));
     $res = $this->query($query);
     if (MDB2::isError($res)) {
         return PEAR::raiseError($res->getMessage(), $res->code);
     }
     return true;
 }
Example #27
0
 /**
  * Write data associated with a given unique ID to container
  *
  * @access public
  * @param  string  $uniqueId  IP address or other unique ID.
  * @param  array   $data      The data associated with a given unique ID.
  * @return void
  * @throws HTTP_FloodControl_Exception if an error occured during writing process.
  */
 public function write($uniqueId, $data)
 {
     $quotedTblName = $this->_db->quoteIdentifier($this->_options['table']);
     $this->_db->beginTransaction();
     $query = sprintf("DELETE FROM %s WHERE unique_id = %s", $quotedTblName, $this->_db->quote($uniqueId, 'text'));
     $result = $this->_db->exec($query);
     if (PEAR::isError($result)) {
         throw new HTTP_FloodControl_Exception($result->getMessage(), $result->getCode());
     }
     $query = sprintf("INSERT INTO %s (unique_id, data, access) VALUES (%s, %s, %d)", $quotedTblName, $this->_db->quote($uniqueId, 'text'), $this->_db->quote(serialize($data), 'text'), time());
     $result = $this->_db->exec($query);
     if (PEAR::isError($result)) {
         $this->_db->rollback();
         throw new HTTP_FloodControl_Exception($result->getMessage(), $result->getCode());
     }
     $this->_db->commit();
 }
Example #28
0
 /**
  * Inserts $message to the currently open database.  Calls open(),
  * if necessary.  Also passes the message along to any Log_observer
  * instances that are observing this Log.
  *
  * @param string $message  The textual message to be logged.
  * @param string $priority The priority of the message.  Valid
  *                  values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT,
  *                  PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING,
  *                  PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG.
  *                  The default is PEAR_LOG_INFO.
  * @return boolean  True on success or false on failure.
  * @access public     
  */
 function log($message, $priority = PEAR_LOG_INFO)
 {
     /* Abort early if the priority is above the maximum logging level. */
     if ($priority > $this->_maxLevel) {
         return;
     }
     if (!$this->_opened) {
         $this->open();
     }
     /* Build the SQL query for this log entry insertion. */
     $id = $this->_db->nextId('log_id');
     $q = sprintf('insert into %s (id, logtime, ident, priority, message)' . 'values(%d, CURRENT_TIMESTAMP, %s, %d, %s)', $this->_table, $id, $this->_db->quote($this->_ident), $priority, $this->_db->quote($message));
     $result = $this->_db->query($q);
     if (DB::isError($result)) {
         return false;
     }
     $this->_announce(array('priority' => $priority, 'message' => $message));
     return true;
 }
Example #29
0
 /**
  * Reads all rights of current user into an
  * associative array.
  *
  * Right => 1
  *
  * @access  public
  * @return  void
  */
 function readRights()
 {
     $query = '
         SELECT
             R.right_id AS rightid, ' . LIVEUSER_MAX_LEVEL . '
         FROM
             ' . $this->prefix . 'userrights UR
         INNER JOIN
             ' . $this->prefix . 'rights R
         ON
             UR.right_id=R.right_id
         WHERE
             UR.perm_user_id=' . $this->dbc->quote($this->permUserId, 'integer');
     $types = array('integer', 'integer');
     $result = $this->dbc->queryAll($query, $types, MDB2_FETCHMODE_ORDERED, true);
     if (MDB2::isError($result)) {
         return $result;
     }
     // if
     $this->rights = $result;
 }
Example #30
0
 /**
  * Get New Items
  *
  * Retrieve the IDs of items recently added to the catalog.
  *
  * @param int $page    Page number of results to retrieve (counting starts at 1)
  * @param int $limit   The size of each page of results to retrieve
  * @param int $daysOld The maximum age of records to retrieve in days (max. 30)
  * @param int $fundId  optional fund ID to use for limiting results (use a value
  * returned by getFunds, or exclude for no limit); note that "fund" may be a
  * misnomer - if funds are not an appropriate way to limit your new item
  * results, you can return a different set of values from getFunds. The
  * important thing is that this parameter supports an ID returned by getFunds,
  * whatever that may mean.
  *
  * @return array       An associative array with two keys: 'count' (the number
  * of items in the 'results' array) and 'results' (an array of associative
  * arrays, each with a single key: 'id', a record ID).
  */
 public function getNewItems($page, $limit, $daysOld, $fundId = null)
 {
     $limitFrom = ($page - 1) * $limit;
     //TODO better escaping; mssql, oracle
     $sql = "SELECT t.tcislo as tcislo, t.druhdoku as druhdoku " . "FROM svazky s JOIN tituly t ON s.tcislo = t.tcislo " . "WHERE s.datumvloz > DATE_SUB(CURDATE(),INTERVAL " . $this->db->quote($daysOld) . " DAY) AND s.datumvloz <= DATE_SUB(CURDATE(),INTERVAL " . $this->db->quote($this->hideNewItemsDays) . " DAY)";
     if ($fundId) {
         $sql .= " AND s.lokace = " . $this->db->quote($fundId);
     }
     $sql .= " ORDER BY s.datumvloz DESC LIMIT {$limitFrom}, {$limit}";
     try {
         $sqlSt = $this->db->prepare($sql);
         $sqlSt->execute();
         $result = $sqlSt->fetchAll();
         $return = ['count' => count($result), 'results' => []];
         foreach ($result as $row) {
             $return['results'][] = ['id' => $this->getLongId($row['tcislo'], $row['druhdoku'])];
         }
         return $return;
     } catch (PDOException $e) {
         throw new ILSException($e->getMessage());
     }
 }