/usr/share/bibus/dbBibMySQL.py is in bibus 1.5.2-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | # Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Bibus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
from MySQLdb import Error,IntegrityError,connect,version_info,paramstyle #
import MySQLdb.converters,dbBibBase
dbBibBase.SUBSTR = 'SUBSTRING'
#
import getpass, os.path
import BIB
#
from dbWizard import dbWizard
# Database fields definition
# tables are now defines in files
# mysql_tables.py ; mysql_41_tables.py
# depending on mysqlversion
TABLE_REF = ""
TMPTABLE_REF = ""
# This table maps ref to keys. A ref can be mapped to several keys.
# ref_Id = unique Id of bibref table
# key_id= unique Id of bibrefKey table
# the couple must be unique
# BIB_LINKS=('key_Id','ref_Id')
TABLE_LINK=""
# This table describes the tree of keys
# user = user name. To know to which user the key belongs to.
# key_id = unique Id of bibrefKey table
# parent = key_id of parent key. NULL = root
# key_name = key name
# BIB_KEYS=('user','key_Id','parent','key_name')
TABLE_KEY=""
# This table if for queries storage
# BIB_QUERY=('query_id','user','name','query')
TABLE_QUERY=""
# storage of modification
# ref_Id int(10) unsigned NOT NULL default '0',
# creator varchar(255) NOT NULL default '',
# date double NOT NULL default 0,
# user_modif varchar(255) NOT NULL default '',
# date_modif double NOT NULL default 0,
# UNIQUE ref_Id (ref_Id)
TABLE_MODIF = ""
# table with links to fulltext files (url)
TABLE_FILE = ""
class dbBib(dbBibBase.dbBib):
def __init__(self,parent=None):
dbBibBase.dbBib.__init__(self,parent,paramstyle)
dbBibBase.Error = Error # needed in dbBibBase for Error in db connection
dbBibBase.IntegrityError = IntegrityError # needed in dbBibBase for Error in db connection
if not BIB.CONFIG.userDefined('mysql') and BIB.USER == '':
try:
BIB.USER = getpass.getuser() # We try to get a default value if not already defined.
except:
BIB.USER = ''
self.user=BIB.USER
self.passwd=BIB.PASSWORD
self.db=BIB.DB_NAME
self.host=BIB.HOST
self.port=BIB.PORT
self.unix_socket=BIB.SOCKET
#
try:
# CPAO -> 23/05/05
# unicode parameter changed for use_unicode and encoding not needed with MySQLdb 1.2.0
if version_info[0:2]<(1,2):
mc=MySQLdb.converters.conversions.copy() # conversion dictionary
self.dbConnection = connect(user=self.user,passwd=self.passwd,db=self.db,host=self.host,port=self.port,unix_socket=self.unix_socket,conv=mc,unicode=BIB.ENCODING)
mc[unicode] = lambda x,d: MySQLdb.converters.string_literal(x.encode(BIB.ENCODING,BIB.ENC_ERRORS),d) # encode unicode string in utf-8
# conversion not needed anymore with MySQLdb 1.0.0
if version_info[0]<1:
mc[constants.FIELD_TYPE.BLOB] = mc[constants.FIELD_TYPE.CHAR] # decode TEXT fields from utf-8 (default is only CHAR et VARCHAR)
mc[constants.FIELD_TYPE.MEDIUM_BLOB] = mc[constants.FIELD_TYPE.CHAR] # decode TEXT fields from utf-8 (default is only CHAR et VARCHAR)
mc[constants.FIELD_TYPE.LONG_BLOB] = mc[constants.FIELD_TYPE.CHAR] # decode TEXT fields from utf-8 (default is only CHAR et VARCHAR)
else:
self.dbConnection = connect(read_default_file=os.path.join(BIB.SOURCEDIR,'MySQL_Bibus.ini'),user=self.user,passwd=self.passwd,db=self.db,host=self.host,port=self.port,unix_socket=self.unix_socket,use_unicode=(BIB.ENCODING=='utf-8'))
self.dbCursor=self.dbConnection.cursor()
self.dbCursor.execute("SELECT VERSION()")
self.mysqlversion = self.dbCursor.fetchone()[0].split('.')[:2]
# we import the correct table definition depending on mysql version
global TABLE_REF, TMPTABLE_REF, TABLE_LINK, TABLE_KEY, TABLE_QUERY, TABLE_MODIF, TABLE_FILE
if self.mysqlversion >= ['4','1']:
from mysql_41_tables import TABLE_REF, TMPTABLE_REF, TABLE_LINK, TABLE_KEY, TABLE_QUERY, TABLE_MODIF, TABLE_FILE
else:
from mysql_tables import TABLE_REF, TMPTABLE_REF, TABLE_LINK, TABLE_KEY, TABLE_QUERY, TABLE_MODIF, TABLE_FILE
#
dbBibBase.TABLE_REF, dbBibBase.TABLE_LINK, dbBibBase.TABLE_KEY, dbBibBase.TABLE_QUERY, dbBibBase.TABLE_MODIF, dbBibBase.TABLE_FILE = \
TABLE_REF, TABLE_LINK, TABLE_KEY, TABLE_QUERY, TABLE_MODIF, TABLE_FILE
except Error,errorType:
self.showError(`errorType.args`)
def selectDatabase(self,db=BIB.DB_NAME):
self.db=db
try:
self.dbCursor.execute("use %s"%db)
if self.getGrants() == 'rw': # we have the grants to temporary table creation
self.dbCursor.execute("CREATE TEMPORARY TABLE %s %s" % (BIB.TMP_ONLINE,TMPTABLE_REF))
self.dbCursor.execute("CREATE TEMPORARY TABLE %s %s" % (BIB.TMP_IMPORT,TMPTABLE_REF))
self.host = self.dbConnection.get_host_info().split()[0].lower()
self.passwd = None # for security clear the password when done
except Error,errorType:
self.showError(`errorType.args`)
#
# MySQL specific funtions
#
#
def getDatabases(self):
try:
self.dbCursor.execute('show databases')
return self.dbCursor.fetchall()
except Error,errorType:
self.showError(`errorType.args`)
def selectTable(self,tableref=BIB.DB_TABLE_REF,tablekey=BIB.DB_TABLE_KEY,tablelink=BIB.DB_TABLE_LINK,tablequery=BIB.DB_TABLE_QUERY,tablemodif=BIB.DB_TABLE_MODIF,tablefile=BIB.DB_TABLE_FILE):
self.tableRef = tableref
self.tableKey = tablekey
self.tableLink = tablelink
self.tableQuery = tablequery
self.tableModif = tablemodif
self.tableFile = tablefile
def getTables(self):
try:
self.dbCursor.execute('show tables')
return [table[0] for table in self.dbCursor.fetchall()]
except Error,errorType:
self.showError(`errorType.args`)
return []
def getFields(self,table):
try:
self.table=table
self.dbCursor.execute('describe %s' % (self.table))
return map(lambda x: x[0],self.dbCursor.fetchall())
except Error,errorType:
self.showError(`errorType.args`)
def get_insert_id(self):
"""Return the last inserted auto_incremented id"""
return self.dbCursor.lastrowid
def getDbInfo(self,key=''):
"""Return a tuple that represent the database connection. Here (host,db,table).
For another database it could be a file name or ... something that identify the database + connection"""
if key == u'Online':
table = BIB.TMP_ONLINE
elif key == u'Import':
table = BIB.TMP_IMPORT
else:
table = self.tableRef
return (self.host, self.db, table)
def getDbDescription(self):
"""Return a string that describes the connection in order to put it in the Frame title"""
return u"%s@%s using MySQL" % (self.db,self.host)
def createDatabase(self,db=BIB.DB_NAME,tableref=BIB.DB_TABLE_REF,tablekey=BIB.DB_TABLE_KEY,tablelink=BIB.DB_TABLE_LINK,tablequery=BIB.DB_TABLE_QUERY,tablemodif=BIB.DB_TABLE_MODIF,tablefile=BIB.DB_TABLE_FILE):
try:
self.dbCursor.execute("""create database %s""" % (db))
self.dbCursor.execute("""use %s""" % (db))
self.dbCursor.execute("""create table %s %s""" % (tableref,TABLE_REF))
self.dbCursor.execute("""create table %s %s""" % (tablekey,TABLE_KEY))
self.dbCursor.execute("""create table %s %s""" % (tablelink,TABLE_LINK))
self.dbCursor.execute("""create table %s %s""" % (tablequery,TABLE_QUERY))
self.dbCursor.execute("""create table %s %s""" % (tablemodif,TABLE_MODIF))
self.dbCursor.execute("""create table %s %s""" % (tablefile,TABLE_FILE))
self.db=db
self.tableRef=tableref
self.tableKey=tablekey
self.tableLink=tablelink
self.tableQuery = tablequery
self.tableModif = tablemodif
self.tableFile = tablefile
self.selectDatabase(self.db)
except Error,errorType:
#print `errorType.args`
self.showError(`errorType.args`)
def duplicateIdentifier(self,e):
"""Return True if the error correspond to a duplicate Identifier
e.args = (1062, "Duplicate entry 'Clement1991#8' for key 2") """
try:
return ( e.args[1].split()[:2] == ['Duplicate', 'entry'] ) and ( e.args[1].split()[3:] == ['for', 'key', '2'] )
except:
return False
def getGrants(self):
"""Return a string
True if temp table may be created with INSERT,DELETE,SELECT
'rw' if bibref is INSERT,DELETE,SELECT,UPDATE ; 'r' if INSERT ; '' else
'rw' if bibrefKey is INSERT,DELETE,SELECT,UPDATE or 'r' or ''
'rw' if bibrefLink is INSERT,DELETE,SELECT,UPDATE or 'r' or ''
'rw' if bibquery is INSERT,DELETE,SELECT,UPDATE or 'r' or ''
return:
'rw' if True,'rw','rw','rw','rw'
'ro' if Any,'r','rw','rw','rw'
'rk' if Any,'r','r','r','r'
'rr' else (normally we need at least 'r' on bibref) # rr = ReadRestricted
"""
ret=[]
if self.mysqlversion >= ['4','1']:
self.dbCursor.execute('SHOW GRANTS FOR current_user()')
else:
self.dbCursor.execute('SELECT current_user()')
user = self.dbCursor.fetchone()[0]
userp = user.split('@')
user = '\'' + userp[0] + '\'' + '@' + '\'' + userp[1] + '\''
# getting grants and store them in a dico
self.dbCursor.execute('SHOW GRANTS FOR %s' %user)
grants = {}
grant = self.dbCursor.fetchone()
while grant:
table = grant[0].split('ON')[1].split('TO')[0].strip()
grants[table] = [p.strip() for p in grant[0].split('ON')[0][5:].split(',')]
grant = self.dbCursor.fetchone()
# getting privileges for temporary tables
tmp = []
for key in ( '*.*', '`%s`.*'%BIB.DB_NAME ):
try:
tmp.extend( grants[key] )
except KeyError:
pass
if ( ('CREATE TEMPORARY TABLES' in tmp) and ('INSERT' in tmp) and ('DELETE' in tmp) and ('SELECT' in tmp) ) or ('ALL' in tmp) or ('ALL PRIVILEGES' in tmp):
ret.append(True)
else:
ret.append(False)
# fusion of the grants at the global + db + table levels for table
for table in (self.tableRef, self.tableKey, self.tableLink, self.tableQuery, self.tableModif, self.tableFile):
tmp = []
for key in '*.*','`%s`.*'%BIB.DB_NAME,'`%s`.`%s`'%(BIB.DB_NAME,table):
try:
tmp.extend( grants[key] )
except KeyError:
pass
if ( ('INSERT' in tmp) and ('DELETE' in tmp) and ('SELECT' in tmp) and ('UPDATE' in tmp) ) or ('ALL' in tmp) or ('ALL PRIVILEGES' in tmp):
ret.append('rw')
elif ('SELECT' in tmp) or ('ALL' in tmp) or ('ALL PRIVILEGES' in tmp):
ret.append('r')
else:
ret.append('')
#
if ret == [True,'rw','rw','rw','rw','rw','rw']:
return 'rw' # normal read-write user
elif ret[1:] == ['r','rw','rw','rw','rw','rw']:
return 'ro' # normal read-only user. Can create its own keytree but cannot add references in db
elif ret[1:] == ['r','r','r','r','r','r']:
return 'rk' # user able to read-only keytree. For collaborative work with a read-only user.
else:
return 'rr' # very restricted user. Can only see a flat list of references
# Database cleanup
def emptyTrash(self):
"""We delete all the ref which are not tagged by any user"""
try:
# We delete first from table_modif
self.dbCursor.execute("""DELETE FROM %s WHERE ref_Id IN (SELECT Id FROM %s LEFT JOIN %s ON Id=ref_Id WHERE ref_Id IS NULL)"""\
%(self.tableModif,self.tableRef,self.tableLink))
# idem from table file
self.dbCursor.execute("""DELETE FROM %s WHERE ref_Id IN (SELECT Id FROM %s LEFT JOIN %s ON Id=ref_Id WHERE ref_Id IS NULL)"""\
%(self.tableFile,self.tableRef,self.tableLink))
# Then the references
self.dbCursor.execute("""DELETE %s FROM %s LEFT JOIN %s ON Id=ref_Id WHERE ref_Id IS NULL"""\
%(self.tableRef,self.tableRef,self.tableLink))
self.dbConnection.commit()
except Error,errorType:
self.showError('dbBib.emptyTrash' + `errorType.args`)
def clean_tableModif(self):
self.dbCursor.execute("""DELETE %s FROM %s LEFT JOIN %s ON ref_Id=Id WHERE Id IS NULL"""
%(self.tableModif,self.tableModif,self.tableRef))
def clean_tableFile(self):
self.dbCursor.execute("""DELETE %s FROM %s LEFT JOIN %s ON ref_Id=Id WHERE Id IS NULL"""
%(self.tableFile,self.tableFile,self.tableRef))
|