func.py 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770
  1. # Init
  2. import os
  3. import sys
  4. import platform
  5. import json
  6. import smtplib
  7. import random
  8. import ipaddress
  9. import subprocess
  10. import email.mime.text
  11. import email.utils
  12. import email.header
  13. # Init-Version
  14. with open('version.json', encoding = 'utf8') as file_data:
  15. version_list = json.loads(file_data.read())
  16. print('Version : ' + version_list['beta']['r_ver'])
  17. print('DB set version : ' + version_list['beta']['c_ver'])
  18. print('Skin set version : ' + version_list['beta']['s_ver'])
  19. print('----')
  20. # Init-PIP_Install
  21. data_up_date = 1
  22. if os.path.exists(os.path.join('data', 'version.json')):
  23. with open(os.path.join('data', 'version.json'), encoding = 'utf8') as file_data:
  24. data_load_ver = file_data.read()
  25. if data_load_ver == version_list['beta']['r_ver']:
  26. data_up_date = 0
  27. if data_up_date == 1:
  28. with open(os.path.join('data', 'version.json'), 'w', encoding = 'utf8') as f:
  29. f.write(version_list['beta']['r_ver'])
  30. if platform.system() in ('Linux', 'Windows'):
  31. python_ver = ''
  32. python_ver = str(sys.version_info.major) + '.' + str(sys.version_info.minor)
  33. run_list = [sys.executable, 'python' + python_ver, 'python3', 'python', 'py -' + python_ver]
  34. for exe_name in run_list:
  35. try:
  36. subprocess.check_call([exe_name, "-m", "pip", "install", "--upgrade", "--user", "-r", "requirements.txt"])
  37. try:
  38. os.execl(exe_name, sys.executable, *sys.argv)
  39. except:
  40. pass
  41. try:
  42. os.execl(exe_name, '"' + sys.executable + '"', *sys.argv)
  43. except:
  44. pass
  45. try:
  46. os.execl(exe_name, os.path.abspath(__file__), *sys.argv)
  47. except:
  48. pass
  49. except:
  50. pass
  51. else:
  52. print('Error : automatic installation is not supported.')
  53. print('Help : try "python3 -m pip install -r requirements.txt"')
  54. else:
  55. print('Error : automatic installation is not supported.')
  56. print('Help : try "python3 -m pip install -r requirements.txt"')
  57. else:
  58. print('PIP check pass')
  59. print('----')
  60. # Init-Load
  61. from .func_tool import *
  62. from .func_render import class_do_render
  63. from diff_match_patch import diff_match_patch
  64. import waitress
  65. import werkzeug.routing
  66. import werkzeug.debug
  67. import flask
  68. import requests
  69. import pymysql
  70. if sys.version_info < (3, 6):
  71. import sha3
  72. # Init-Global
  73. global_lang = {}
  74. global_wiki_set = {}
  75. global_db_set = ''
  76. # Func
  77. # Func-main
  78. def do_db_set(db_set):
  79. global global_db_set
  80. global_db_set = db_set
  81. # Func-init
  82. def get_init_set_list(need = 'all'):
  83. init_set_list = {
  84. 'host' : {
  85. 'display' : 'Host',
  86. 'require' : 'conv',
  87. 'default' : '0.0.0.0'
  88. }, 'port' : {
  89. 'display' : 'Port',
  90. 'require' : 'conv',
  91. 'default' : '3000'
  92. }, 'language' : {
  93. 'display' : 'Language',
  94. 'require' : 'select',
  95. 'default' : 'ko-KR',
  96. 'list' : ['ko-KR', 'en-US']
  97. }, 'markup' : {
  98. 'display' : 'Markup',
  99. 'require' : 'select',
  100. 'default' : 'namumark',
  101. 'list' : ['namumark', 'markdown', 'custom', 'raw']
  102. }, 'encode' : {
  103. 'display' : 'Encryption method',
  104. 'require' : 'select',
  105. 'default' : 'sha3',
  106. 'list' : ['sha3', 'sha3-salt', 'sha3-512', 'sha3-512-salt']
  107. }
  108. }
  109. if need == 'all':
  110. return init_set_list
  111. else:
  112. return init_set_list[need]
  113. class get_db_connect:
  114. def __init__(self, db_type = ''):
  115. global global_db_set
  116. self.db_set = global_db_set
  117. if db_type != '':
  118. self.db_set['type'] = db_type
  119. def __enter__(self):
  120. if self.db_set['type'] == 'sqlite':
  121. self.conn = sqlite3.connect(
  122. self.db_set['name'] + '.db',
  123. check_same_thread = False,
  124. isolation_level = None
  125. )
  126. self.conn.execute('pragma journal_mode = wal')
  127. else:
  128. self.conn = pymysql.connect(
  129. host = self.db_set['mysql_host'],
  130. user = self.db_set['mysql_user'],
  131. password = self.db_set['mysql_pw'],
  132. charset = 'utf8mb4',
  133. port = int(self.db_set['mysql_port']),
  134. autocommit = True
  135. )
  136. try:
  137. self.conn.select_db(self.db_set['name'])
  138. except:
  139. pass
  140. return self.conn
  141. def __exit__(self, exc_type, exc_value, traceback):
  142. self.conn.commit()
  143. self.conn.close()
  144. # class get_whoosh_connect:
  145. class class_check_json:
  146. def do_check_set_json(self):
  147. if os.getenv('NAMU_DB') or os.getenv('NAMU_DB_TYPE'):
  148. set_data = {}
  149. set_data['db'] = os.getenv('NAMU_DB') if os.getenv('NAMU_DB') else 'data'
  150. set_data['db_type'] = os.getenv('NAMU_DB_TYPE') if os.getenv('NAMU_DB_TYPE') else 'sqlite'
  151. else:
  152. if os.path.exists(os.path.join('data', 'set.json')):
  153. db_set_list = ['db', 'db_type']
  154. with open(os.path.join('data', 'set.json'), encoding = 'utf8') as file_data:
  155. set_data = json.loads(file_data.read())
  156. for i in db_set_list:
  157. if not i in set_data:
  158. os.remove(os.path.join('data', 'set.json'))
  159. break
  160. if not os.path.exists(os.path.join('data', 'set.json')):
  161. set_data = {}
  162. normal_db_type = ['sqlite', 'mysql']
  163. print('DB type (' + normal_db_type[0] + ') [' + ', '.join(normal_db_type) + '] : ', end = '')
  164. data_get = str(input())
  165. if data_get == '' or not data_get in normal_db_type:
  166. set_data['db_type'] = 'sqlite'
  167. else:
  168. set_data['db_type'] = data_get
  169. all_src = []
  170. if set_data['db_type'] == 'sqlite':
  171. for i_data in os.listdir("."):
  172. f_src = re.search(r"(.+)\.db$", i_data)
  173. if f_src:
  174. all_src += [f_src.group(1)]
  175. print('DB name (data) [' + ', '.join(all_src) + '] : ', end = '')
  176. data_get = str(input())
  177. if data_get == '':
  178. set_data['db'] = 'data'
  179. else:
  180. set_data['db'] = data_get
  181. with open(os.path.join('data', 'set.json'), 'w', encoding = 'utf8') as f:
  182. f.write(json.dumps(set_data))
  183. print('DB name : ' + set_data['db'])
  184. print('DB type : ' + set_data['db_type'])
  185. data_db_set = {}
  186. data_db_set['name'] = set_data['db']
  187. data_db_set['type'] = set_data['db_type']
  188. return data_db_set
  189. def do_check_mysql_json(self, data_db_set):
  190. if os.path.exists(os.path.join('data', 'mysql.json')):
  191. db_set_list = ['user', 'password', 'host', 'port']
  192. with open(os.path.join('data', 'mysql.json'), encoding = 'utf8') as file_data:
  193. set_data = json.loads(file_data.read())
  194. for i in db_set_list:
  195. if not i in set_data:
  196. os.remove(os.path.join('data', 'mysql.json'))
  197. break
  198. set_data_mysql = set_data
  199. if not os.path.exists(os.path.join('data', 'mysql.json')):
  200. set_data_mysql = {}
  201. print('DB user ID : ', end = '')
  202. set_data_mysql['user'] = str(input())
  203. print('DB password : ', end = '')
  204. set_data_mysql['password'] = str(input())
  205. print('DB host (localhost) : ', end = '')
  206. set_data_mysql['host'] = str(input())
  207. if set_data_mysql['host'] == '':
  208. set_data_mysql['host'] = 'localhost'
  209. print('DB port (3306) : ', end = '')
  210. set_data_mysql['port'] = str(input())
  211. if set_data_mysql['port'] == '':
  212. set_data_mysql['port'] = '3306'
  213. with open(
  214. os.path.join('data', 'mysql.json'),
  215. 'w',
  216. encoding = 'utf8'
  217. ) as f:
  218. f.write(json.dumps(set_data_mysql))
  219. data_db_set['mysql_user'] = set_data_mysql['user']
  220. data_db_set['mysql_pw'] = set_data_mysql['password']
  221. if 'host' in set_data_mysql:
  222. data_db_set['mysql_host'] = set_data_mysql['host']
  223. else:
  224. data_db_set['mysql_host'] = 'localhost'
  225. if 'port' in set_data_mysql:
  226. data_db_set['mysql_port'] = set_data_mysql['port']
  227. else:
  228. data_db_set['mysql_port'] = '3306'
  229. return data_db_set
  230. def __init__(self):
  231. self.data_db_set = {}
  232. def __new__(self):
  233. self.data_db_set = self.do_check_set_json(self)
  234. if self.data_db_set['type'] == 'mysql':
  235. self.data_db_set = self.do_check_mysql_json(self, self.data_db_set)
  236. return self.data_db_set
  237. def get_db_table_list():
  238. # DB table
  239. # Init-Create_DB
  240. # --이거 개편한다더니 도대체 언제?--
  241. create_data = {}
  242. # 폐지 예정 (data_set으로 통합)
  243. create_data['data_set'] = ['doc_name', 'doc_rev', 'set_name', 'set_data']
  244. create_data['data'] = ['title', 'data', 'type']
  245. create_data['history'] = ['id', 'title', 'data', 'date', 'ip', 'send', 'leng', 'hide', 'type']
  246. create_data['rc'] = ['id', 'title', 'date', 'type']
  247. create_data['acl'] = ['title', 'data', 'type']
  248. # 개편 예정 (data_link로 변경)
  249. create_data['back'] = ['title', 'link', 'type', 'data']
  250. # 폐지 예정 (topic_set으로 통합) [가장 시급]
  251. create_data['topic_set'] = ['thread_code', 'set_name', 'set_id', 'set_data']
  252. create_data['rd'] = ['title', 'sub', 'code', 'date', 'band', 'stop', 'agree', 'acl']
  253. create_data['topic'] = ['id', 'data', 'date', 'ip', 'block', 'top', 'code']
  254. # 폐지 예정 (user_set으로 통합)
  255. create_data['rb'] = ['block', 'end', 'today', 'blocker', 'why', 'band', 'login', 'ongoing']
  256. create_data['scan'] = ['user', 'title', 'type']
  257. # 개편 예정 (wiki_set과 wiki_filter과 wiki_vote으로 변경)
  258. create_data['other'] = ['name', 'data', 'coverage']
  259. create_data['html_filter'] = ['html', 'kind', 'plus', 'plus_t']
  260. create_data['vote'] = ['name', 'id', 'subject', 'data', 'user', 'type', 'acl']
  261. # 개편 예정 (auth_list와 auth_log로 변경)
  262. create_data['alist'] = ['name', 'acl']
  263. create_data['re_admin'] = ['who', 'what', 'time']
  264. # 개편 예정 (user_notice와 user_agent로 변경)
  265. create_data['ua_d'] = ['name', 'ip', 'ua', 'today', 'sub']
  266. create_data['user_set'] = ['name', 'id', 'data']
  267. create_data['user_notice'] = ['id', 'name', 'data', 'date', 'readme']
  268. create_data['bbs_set'] = ['set_name', 'set_code', 'set_id', 'set_data']
  269. create_data['bbs_data'] = ['set_name', 'set_code', 'set_id', 'set_data']
  270. return create_data
  271. def update(ver_num, set_data):
  272. with get_db_connect() as conn:
  273. curs = conn.cursor()
  274. print('----')
  275. # 업데이트 하위 호환 유지 함수
  276. if ver_num < 3160027:
  277. print('Add init set')
  278. set_init()
  279. if ver_num < 3170002:
  280. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  281. if not curs.fetchall():
  282. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  283. curs.execute(db_change("insert into html_filter (html, kind) values (?, 'extension')"), [i])
  284. if ver_num < 3170400:
  285. curs.execute(db_change("select title, sub, code from topic where id = '1'"))
  286. for i in curs.fetchall():
  287. curs.execute(db_change("update topic set code = ? where title = ? and sub = ?"), [i[2], i[0], i[1]])
  288. curs.execute(db_change("update rd set code = ? where title = ? and sub = ?"), [i[2], i[0], i[1]])
  289. if ver_num < 3171800:
  290. curs.execute(db_change("select data from other where name = 'recaptcha'"))
  291. change_rec = curs.fetchall()
  292. if change_rec and change_rec[0][0] != '':
  293. new_rec = re.search(r'data-sitekey="([^"]+)"', change_rec[0][0])
  294. if new_rec:
  295. curs.execute(db_change("update other set data = ? where name = 'recaptcha'"), [new_rec.group(1)])
  296. else:
  297. curs.execute(db_change("update other set data = '' where name = 'recaptcha'"))
  298. curs.execute(db_change("update other set data = '' where name = 'sec_re'"))
  299. if ver_num < 3172800 and \
  300. set_data['db_type'] == 'mysql':
  301. get_data_mysql = json.loads(open('data/mysql.json', encoding = 'utf8').read())
  302. with open('data/mysql.json', 'w') as f:
  303. f.write('{ "user" : "' + get_data_mysql['user'] + '", "password" : "' + get_data_mysql['password'] + '", "host" : "localhost" }')
  304. if ver_num < 3183603:
  305. curs.execute(db_change("select block from ban where band = 'O'"))
  306. for i in curs.fetchall():
  307. curs.execute(db_change("update ban set block = ?, band = 'regex' where block = ? and band = 'O'"), ['^' + i[0].replace('.', '\\.'), i[0]])
  308. curs.execute(db_change("select block from rb where band = 'O'"))
  309. for i in curs.fetchall():
  310. curs.execute(db_change("update rb set block = ?, band = 'regex' where block = ? and band = 'O'"), ['^' + i[0].replace('.', '\\.'), i[0]])
  311. if ver_num < 3190201:
  312. today_time = get_time()
  313. curs.execute(db_change("select block, end, why, band, login from ban"))
  314. for i in curs.fetchall():
  315. curs.execute(db_change("insert into rb (block, end, today, why, band, login, ongoing) values (?, ?, ?, ?, ?, ?, ?)"), [i[0], i[1], today_time, i[2], i[3], i[4], '1'])
  316. if ver_num < 3191301:
  317. curs.execute(db_change('select id, title, date from history where not title like "user:%" order by date desc limit 50'))
  318. data_list = curs.fetchall()
  319. for get_data in data_list:
  320. curs.execute(db_change("insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"), [get_data[0], get_data[1], get_data[2]])
  321. if ver_num < 3202400:
  322. curs.execute(db_change("select data from other where name = 'update'"))
  323. get_data = curs.fetchall()
  324. if get_data and get_data[0][0] == 'master':
  325. curs.execute(db_change("update other set data = 'beta' where name = 'update'"), [])
  326. if ver_num < 3202600:
  327. curs.execute(db_change("select name, regex, sub from filter"))
  328. for i in curs.fetchall():
  329. curs.execute(db_change("insert into html_filter (html, kind, plus, plus_t) values (?, 'regex_filter', ?, ?)"), [i[0], i[1], i[2]])
  330. curs.execute(db_change("select title, link, icon from inter"))
  331. for i in curs.fetchall():
  332. curs.execute(db_change("insert into html_filter (html, kind, plus, plus_t) values (?, 'inter_wiki', ?, ?)"), [i[0], i[1], i[2]])
  333. if ver_num < 3203400:
  334. curs.execute(db_change("select user, css from custom"))
  335. for i in curs.fetchall():
  336. curs.execute(db_change("insert into user_set (name, id, data) values ('custom_css', ?, ?)"), [re.sub(r' \(head\)$', '', i[0]), i[1]])
  337. if ver_num < 3205500:
  338. curs.execute(db_change("select title, decu, dis, view, why from acl"))
  339. for i in curs.fetchall():
  340. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[1], 'decu'])
  341. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[2], 'dis'])
  342. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[3], 'view'])
  343. curs.execute(db_change("insert into acl (title, data, type) values (?, ?, ?)"), [i[0], i[4], 'why'])
  344. if ver_num < 3300101:
  345. # 캐시 초기화
  346. curs.execute(db_change('delete from cache_data'))
  347. if ver_num < 3300301:
  348. # regex_filter 오류 해결
  349. curs.execute(db_change('delete from html_filter where kind = "regex_filter" and html is null'))
  350. if ver_num < 3302302:
  351. # user이랑 user_set 테이블의 통합
  352. curs.execute(db_change('select id, pw, acl, date, encode from user'))
  353. for i in curs.fetchall():
  354. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['pw', i[0], i[1]])
  355. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['acl', i[0], i[2]])
  356. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['date', i[0], i[3]])
  357. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['encode', i[0], i[4]])
  358. if ver_num < 3400101:
  359. # user_set이랑 user_application 테이블의 통합
  360. curs.execute(db_change('select id, pw, date, encode, question, answer, ip, ua, email from user_application'))
  361. for i in curs.fetchall():
  362. sql_data = {}
  363. sql_data['id'] = i[0]
  364. sql_data['pw'] = i[1]
  365. sql_data['date'] = i[2]
  366. sql_data['encode'] = i[3]
  367. sql_data['question'] = i[4]
  368. sql_data['answer'] = i[5]
  369. sql_data['ip'] = i[6]
  370. sql_data['ua'] = i[7]
  371. sql_data['email'] = i[8]
  372. curs.execute(db_change("insert into user_set (name, id, data) values (?, ?, ?)"), ['application', i[0], json.dumps(sql_data)])
  373. if ver_num < 3500105:
  374. curs.execute(db_change('delete from acl where title like "file:%" and data = "admin" and type like "decu%"'))
  375. if ver_num < 3500106:
  376. curs.execute(db_change("select data from other where name = 'domain'"))
  377. db_data = curs.fetchall()
  378. if db_data and db_data[0][0] != '':
  379. db_data = db_data[0][0]
  380. db_data = re.match(r'[^/]+\/\/([^/]+)', db_data)
  381. if db_data:
  382. db_data = db_data.group(1)
  383. curs.execute(db_change("update other set data = ? where name = 'domain'"), [db_data])
  384. else:
  385. curs.execute(db_change("update other set data = '' where name = 'domain'"))
  386. if ver_num < 3500107:
  387. db_table_list = get_db_table_list()
  388. for for_a in db_table_list:
  389. for for_b in db_table_list[for_a]:
  390. curs.execute(db_change("update " + for_a + " set " + for_b + " = '' where " + for_b + " is null"))
  391. if ver_num < 3500113:
  392. db_table_list = get_db_table_list()
  393. for for_a in db_table_list:
  394. for for_b in db_table_list[for_a]:
  395. curs.execute(db_change("update " + for_a + " set " + for_b + " = '' where " + for_b + " is null"))
  396. if ver_num < 3500114:
  397. curs.execute(db_change('delete from alarm'))
  398. if ver_num < 3500354:
  399. curs.execute(db_change("select data from other where name = 'robot'"))
  400. db_data = curs.fetchall()
  401. if db_data:
  402. robot_default = '' + \
  403. 'User-agent: *\n' + \
  404. 'Disallow: /\n' + \
  405. 'Allow: /$\n' + \
  406. 'Allow: /image/\n' + \
  407. 'Allow: /views/\n' + \
  408. 'Allow: /w/' + \
  409. ''
  410. if db_data[0][0] == robot_default:
  411. curs.execute(db_change("insert into other (name, data, coverage) values ('robot_default', 'on', '')"))
  412. if ver_num < 3500355:
  413. # other coverage 오류 해결
  414. curs.execute(db_change("update other set coverage = '' where coverage is null"))
  415. if ver_num < 3500358:
  416. curs.execute(db_change("drop index history_index"))
  417. curs.execute(db_change("create index history_index on history (title, ip)"))
  418. if ver_num < 3500360:
  419. # 마지막 편집 따로 기록하도록
  420. # create_data['data_set'] = ['doc_name', 'doc_rev', 'set_name', 'set_data']
  421. print("Update 3500360...")
  422. curs.execute(db_change('delete from data_set where set_name = "last_edit"'))
  423. curs.execute(db_change("select title from data"))
  424. db_data = curs.fetchall()
  425. for for_a in db_data:
  426. curs.execute(db_change("select date from history where title = ? order by date desc limit 1"), [for_a[0]])
  427. db_data_2 = curs.fetchall()
  428. if db_data_2:
  429. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, '', 'last_edit', ?)"), [for_a[0], db_data_2[0][0]])
  430. curs.execute(db_change('delete from acl where title like "file:%" and data = "admin" and type like "decu%"'))
  431. print("Update 3500360 complete")
  432. if ver_num < 3500361:
  433. # curs.execute(db_change('select id from user_set where name = "email" and data = ?'), [user_email])
  434. curs.execute(db_change('select id from user_set where name = "email"'))
  435. for db_data in curs.fetchall():
  436. if ip_or_user(db_data[0]) == 1:
  437. curs.execute(db_change('delete from user_set where id = ? and name = "email"'), [db_data[0]])
  438. # create_data['history'] = ['id', 'title', 'data', 'date', 'ip', 'send', 'leng', 'hide', 'type']
  439. # create_data['rc'] = ['id', 'title', 'date', 'type']
  440. if ver_num == 3500362:
  441. curs.execute(db_change("drop index history_index"))
  442. curs.execute(db_change("create index history_index on history (title, ip)"))
  443. if ver_num < 3500365:
  444. curs.execute(db_change("update back set data = '' where data is null"))
  445. if ver_num < 3500371:
  446. curs.execute(db_change("delete from user_notice"))
  447. user_alarm_count = {}
  448. curs.execute(db_change("select name, data, date from alarm"))
  449. for db_data in curs.fetchall():
  450. if db_data[0] in user_alarm_count:
  451. user_alarm_count[db_data[0]] += 1
  452. else:
  453. user_alarm_count[db_data[0]] = 1
  454. curs.execute(db_change('insert into user_notice (id, name, data, date, readme) values (?, ?, ?, ?, "")'), [str(user_alarm_count[db_data[0]]), db_data[0], db_data[1], db_data[2]])
  455. if ver_num < 3500372:
  456. # ID 글자 확인 호환용
  457. curs.execute(db_change('insert into html_filter (html, kind, plus, plus_t) values (?, ?, ?, ?)'), [r'(?:[^A-Za-zㄱ-힣0-9])', 'name', '', ''])
  458. if ver_num < 3500373:
  459. select_data = {}
  460. curs.execute(db_change("select name, id, data from user_set where name = 'application'"))
  461. for db_data in curs.fetchall():
  462. select_data[db_data[1]] = db_data
  463. curs.execute(db_change("delete from user_set where name = 'application'"))
  464. for db_data in select_data:
  465. curs.execute(db_change("insert into user_set (id, name, data) values (?, ?, ?)"), [select_data[db_data][1], select_data[db_data][0], select_data[db_data][2]])
  466. conn.commit()
  467. print('Update completed')
  468. def set_init_always(ver_num):
  469. global global_wiki_set
  470. with get_db_connect() as conn:
  471. curs = conn.cursor()
  472. curs.execute(db_change('delete from other where name = "ver"'))
  473. curs.execute(db_change('insert into other (name, data, coverage) values ("ver", ?, "")'), [ver_num])
  474. curs.execute(db_change('delete from alist where name = "owner"'))
  475. curs.execute(db_change('insert into alist (name, acl) values ("owner", "owner")'))
  476. if not os.path.exists(load_image_url()):
  477. os.makedirs(load_image_url())
  478. curs.execute(db_change('select data from other where name = "key"'))
  479. if not curs.fetchall():
  480. curs.execute(db_change('insert into other (name, data, coverage) values ("key", ?, "")'), [load_random_key()])
  481. curs.execute(db_change('select data from other where name = "salt_key"'))
  482. if not curs.fetchall():
  483. curs.execute(db_change('insert into other (name, data, coverage) values ("salt_key", ?, "")'), [load_random_key(4)])
  484. curs.execute(db_change('select data from other where name = "count_all_title"'))
  485. if not curs.fetchall():
  486. curs.execute(db_change('insert into other (name, data, coverage) values ("count_all_title", "0", "")'))
  487. curs.execute(db_change('select data from other where name = "wiki_access_password_need"'))
  488. db_data = curs.fetchall()
  489. if db_data and db_data[0][0] != '':
  490. curs.execute(db_change('select data from other where name = "wiki_access_password"'))
  491. db_data = curs.fetchall()
  492. if db_data:
  493. global_wiki_set['wiki_access_password'] = db_data[0][0]
  494. def set_init():
  495. with get_db_connect() as conn:
  496. curs = conn.cursor()
  497. # 초기값 설정 함수
  498. curs.execute(db_change("select html from html_filter where kind = 'email'"))
  499. if not curs.fetchall():
  500. for i in ['naver.com', 'gmail.com', 'daum.net', 'kakao.com']:
  501. curs.execute(db_change(
  502. "insert into html_filter (html, kind, plus, plus_t) values (?, 'email', '', '')"
  503. ), [i])
  504. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  505. if not curs.fetchall():
  506. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  507. curs.execute(db_change(
  508. "insert into html_filter (html, kind, plus, plus_t) values (?, 'extension', '', '')"
  509. ), [i])
  510. curs.execute(db_change(
  511. 'select data from other ' + \
  512. 'where name = "smtp_server" or name = "smtp_port" or name = "smtp_security"'
  513. ))
  514. if not curs.fetchall():
  515. for i in [
  516. ['smtp_server', 'smtp.gmail.com'],
  517. ['smtp_port', '587'],
  518. ['smtp_security', 'starttls']
  519. ]:
  520. curs.execute(db_change("insert into other (name, data, coverage) values (?, ?, '')"), [i[0], i[1]])
  521. curs.execute(db_change('insert into html_filter (html, kind, plus, plus_t) values (?, ?, ?, ?)'), [
  522. r'(?:[^A-Za-zㄱ-힣0-9])',
  523. 'name',
  524. '',
  525. ''
  526. ])
  527. # Func-simple
  528. ## Func-simple-without_DB
  529. def get_default_admin_group():
  530. return ['owner', 'user', 'ban']
  531. def get_default_robots_txt():
  532. data = '' + \
  533. 'User-agent: *\n' + \
  534. 'Disallow: /\n' + \
  535. 'Allow: /$\n' + \
  536. 'Allow: /w/\n' + \
  537. 'Allow: /sitemap.xml$\n' + \
  538. 'Allow: /sitemap_*.xml$' + \
  539. ''
  540. if os.path.exists('sitemap.xml'):
  541. data += '' + \
  542. '\n' + \
  543. 'Sitemap: ' + load_domain('full') + '/sitemap.xml' + \
  544. ''
  545. return data
  546. def load_random_key(long = 128):
  547. return ''.join(
  548. random.choice(
  549. "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  550. ) for i in range(long)
  551. )
  552. def http_warning():
  553. return '''
  554. <div id="opennamu_http_warning_text"></div>
  555. <span style="display: none;" id="opennamu_http_warning_text_lang">''' + load_lang('http_warning') + '''</span>
  556. '''
  557. def get_next_page_bottom(link, num, page, end = 50):
  558. list_data = ''
  559. if num == 1:
  560. if len(page) == end:
  561. list_data += '' + \
  562. '<hr class="main_hr">' + \
  563. '<a href="' + link.format(str(num + 1)) + '">(' + load_lang('next') + ')</a>' + \
  564. ''
  565. elif len(page) != end:
  566. list_data += '' + \
  567. '<hr class="main_hr">' + \
  568. '<a href="' + link.format(str(num - 1)) + '">(' + load_lang('previous') + ')</a>' + \
  569. ''
  570. else:
  571. list_data += '' + \
  572. '<hr class="main_hr">' + \
  573. '<a href="' + link.format(str(num - 1)) + '">(' + load_lang('previous') + ')</a> ' + \
  574. '<a href="' + link.format(str(num + 1)) + '">(' + load_lang('next') + ')</a>' + \
  575. ''
  576. return list_data
  577. def next_fix(link, num, page, end = 50):
  578. list_data = ''
  579. if num == 1:
  580. if len(page) == end:
  581. list_data += '' + \
  582. '<hr class="main_hr">' + \
  583. '<a href="' + link + str(num + 1) + '">(' + load_lang('next') + ')</a>' + \
  584. ''
  585. elif len(page) != end:
  586. list_data += '' + \
  587. '<hr class="main_hr">' + \
  588. '<a href="' + link + str(num - 1) + '">(' + load_lang('previous') + ')</a>' + \
  589. ''
  590. else:
  591. list_data += '' + \
  592. '<hr class="main_hr">' + \
  593. '<a href="' + link + str(num - 1) + '">(' + load_lang('previous') + ')</a> <a href="' + link + str(num + 1) + '">(' + load_lang('next') + ')</a>' + \
  594. ''
  595. return list_data
  596. def leng_check(A, B):
  597. # B -> new
  598. # A -> old
  599. return '0' if A == B else (('-' + str(A - B)) if A > B else ('+' + str(B - A)))
  600. def number_check(data):
  601. try:
  602. int(data)
  603. return data
  604. except:
  605. return '1'
  606. def check_int(data):
  607. try:
  608. int(data)
  609. return data
  610. except:
  611. return ''
  612. def redirect(data = '/'):
  613. return flask.redirect(load_domain('full') + data)
  614. def get_acl_list(type_d = 'normal'):
  615. if type_d == 'user':
  616. return ['', 'user', 'all']
  617. else:
  618. return ['', 'all', 'user', 'admin', 'owner', '50_edit', 'email', 'ban', 'before', '30_day', 'ban_admin', 'not_all']
  619. ## Func-simple-with_DB
  620. def get_user_title_list(ip = ''):
  621. with get_db_connect() as conn:
  622. curs = conn.cursor()
  623. ip = ip_check() if ip == '' else ip
  624. # default
  625. user_title = {
  626. '' : load_lang('default'),
  627. '🌳' : '🌳 namu',
  628. }
  629. # admin
  630. if admin_check('all', None, ip) == 1:
  631. user_title['✅'] = '✅ admin'
  632. curs.execute(db_change('select name from user_set where id = ? and name = ?'), [ip, 'get_🥚'])
  633. if curs.fetchall():
  634. user_title['🥚'] = '🥚 easter_egg'
  635. return user_title
  636. def load_image_url():
  637. with get_db_connect() as conn:
  638. curs = conn.cursor()
  639. curs.execute(db_change('select data from other where name = "image_where"'))
  640. image_where = curs.fetchall()
  641. image_where = image_where[0][0] if image_where else os.path.join('data', 'images')
  642. return image_where
  643. def load_domain(data_type = 'normal'):
  644. with get_db_connect() as conn:
  645. curs = conn.cursor()
  646. domain = ''
  647. if data_type == 'full':
  648. curs.execute(db_change("select data from other where name = 'http_select'"))
  649. db_data = curs.fetchall()
  650. domain += db_data[0][0] if db_data and db_data[0][0] != '' else 'http'
  651. domain += '://'
  652. curs.execute(db_change("select data from other where name = 'domain'"))
  653. db_data = curs.fetchall()
  654. domain += db_data[0][0] if db_data and db_data[0][0] != '' else flask.request.host
  655. else:
  656. curs.execute(db_change("select data from other where name = 'domain'"))
  657. db_data = curs.fetchall()
  658. domain += db_data[0][0] if db_data and db_data[0][0] != '' else flask.request.host
  659. return domain
  660. def get_tool_js_safe(data):
  661. data = data.replace('\n', '\\\\n')
  662. data = data.replace('\\', '\\\\')
  663. data = data.replace("'", "\\'")
  664. data = data.replace('"', '\\"')
  665. return data
  666. def edit_button(ob_name = 'opennamu_edit_textarea', monaco_ob_name = 'opennamu_monaco_editor'):
  667. with get_db_connect() as conn:
  668. curs = conn.cursor()
  669. insert_list = []
  670. curs.execute(db_change("select html, plus from html_filter where kind = 'edit_top'"))
  671. db_data = curs.fetchall()
  672. for get_data in db_data:
  673. insert_list += [[get_data[1], get_data[0]]]
  674. data = ''
  675. for insert_data in insert_list:
  676. data += '<a href="javascript:do_insert_data(\'' + ob_name + '\', \'' + get_tool_js_safe(insert_data[0]) + '\', \'' + monaco_ob_name + '\');">(' + html.escape(insert_data[1]) + ')</a> '
  677. data += (' ' if data != '' else '') + '<a href="/edit_top">(' + load_lang('add') + ')</a>'
  678. data += '<hr class="main_hr">'
  679. return data
  680. def ip_warning():
  681. with get_db_connect() as conn:
  682. curs = conn.cursor()
  683. if ip_or_user() != 0:
  684. curs.execute(db_change('select data from other where name = "no_login_warning"'))
  685. data = curs.fetchall()
  686. if data and data[0][0] != '':
  687. text_data = '' + \
  688. '<span>' + data[0][0] + '</span>' + \
  689. '<hr class="main_hr">' + \
  690. ''
  691. else:
  692. text_data = '' + \
  693. '<span>' + load_lang('no_login_warning') + '</span>' + \
  694. '<hr class="main_hr">' + \
  695. ''
  696. else:
  697. text_data = ''
  698. return text_data
  699. # Func-login
  700. def pw_encode(data, db_data_encode = ''):
  701. with get_db_connect() as conn:
  702. curs = conn.cursor()
  703. if db_data_encode == '':
  704. curs.execute(db_change('select data from other where name = "encode"'))
  705. db_data = curs.fetchall()
  706. db_data_encode = db_data[0][0] if db_data else 'sha3'
  707. if db_data_encode == 'sha256':
  708. return hashlib.sha256(bytes(data, 'utf-8')).hexdigest()
  709. elif db_data_encode == 'sha3':
  710. return hashlib.sha3_256(bytes(data, 'utf-8')).hexdigest()
  711. elif db_data_encode == 'sha3-512':
  712. return hashlib.sha3_512(bytes(data, 'utf-8')).hexdigest()
  713. else:
  714. curs.execute(db_change('select data from other where name = "salt_key"'))
  715. db_data = curs.fetchall()
  716. db_data_salt = db_data[0][0] if db_data else ''
  717. if db_data_encode == 'sha3-salt':
  718. return hashlib.sha3_256(bytes(data + db_data_salt, 'utf-8')).hexdigest()
  719. else:
  720. return hashlib.sha3_512(bytes(data + db_data_salt, 'utf-8')).hexdigest()
  721. def pw_check(data, data2, type_d = 'no', id_d = ''):
  722. with get_db_connect() as conn:
  723. curs = conn.cursor()
  724. curs.execute(db_change('select data from other where name = "encode"'))
  725. db_data = curs.fetchall()
  726. load_set_data = db_data[0][0] if db_data and db_data[0][0] != '' else 'sha3'
  727. set_data = db_data[0][0] if db_data and db_data[0][0] != '' else 'sha3'
  728. if type_d != 'no':
  729. if type_d == '':
  730. set_data = 'sha3'
  731. else:
  732. set_data = type_d
  733. re_data = 1 if pw_encode(data, set_data) == data2 else 0
  734. if load_set_data != set_data and re_data == 1 and id_d != '':
  735. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'pw'"), [
  736. pw_encode(data),
  737. id_d
  738. ])
  739. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'encode'"), [
  740. load_set_data,
  741. id_d
  742. ])
  743. return re_data
  744. # Func-skin
  745. def easy_minify(data, tool = None):
  746. # without_DB
  747. if 'wiki_access_password' in global_wiki_set:
  748. access_password = global_wiki_set['wiki_access_password']
  749. input_password = flask.request.cookies.get('opennamu_wiki_access', ' ')
  750. if url_pas(access_password) == input_password:
  751. return data
  752. return '''
  753. <script src="/views/main_css/js/route/wiki_access_password.js"></script>
  754. <h2>''' + load_lang('error_password_require_for_wiki_access') + '''</h2>
  755. <input type="password" id="wiki_access">
  756. <input type="submit" onclick="opennamu_do_wiki_access();">
  757. '''
  758. else:
  759. return data
  760. def load_lang(data, safe = 0):
  761. global global_lang
  762. with get_db_connect() as conn:
  763. curs = conn.cursor()
  764. ip = ip_check()
  765. if ip_or_user(ip) == 0:
  766. curs.execute(db_change('select data from user_set where name = "lang" and id = ?'), [ip])
  767. rep_data = curs.fetchall()
  768. elif 'lang' in flask.session:
  769. rep_data = [[flask.session['lang']]]
  770. else:
  771. curs.execute(db_change("select data from other where name = 'language'"))
  772. rep_data = curs.fetchall()
  773. if not rep_data or rep_data[0][0] in ('', 'default'):
  774. curs.execute(db_change("select data from other where name = 'language'"))
  775. rep_data = curs.fetchall()
  776. if rep_data:
  777. lang_name = rep_data[0][0]
  778. else:
  779. lang_name = 'en-US'
  780. if lang_name in global_lang:
  781. lang = global_lang[lang_name]
  782. else:
  783. lang_list = os.listdir('lang')
  784. if (lang_name + '.json') in lang_list:
  785. lang = json.loads(open(
  786. os.path.join('lang', lang_name + '.json'),
  787. encoding = 'utf8'
  788. ).read())
  789. global_lang[lang_name] = lang
  790. else:
  791. lang = {}
  792. if data in lang:
  793. if safe == 1:
  794. return lang[data]
  795. else:
  796. return html.escape(lang[data])
  797. return html.escape(data + ' (' + lang_name + ')')
  798. def skin_check(set_n = 0):
  799. with get_db_connect() as conn:
  800. curs = conn.cursor()
  801. # 개편 필요?
  802. skin_list = load_skin('ringo', 1)
  803. skin = skin_list[0]
  804. ip = ip_check()
  805. user_need_skin = ''
  806. if ip_or_user(ip) == 0:
  807. curs.execute(db_change('select data from user_set where name = "skin" and id = ?'), [ip])
  808. skin_exist = curs.fetchall()
  809. if skin_exist:
  810. user_need_skin = skin_exist[0][0]
  811. else:
  812. if 'skin' in flask.session:
  813. user_need_skin = flask.session['skin']
  814. user_need_skin = '' if user_need_skin == 'default' else user_need_skin
  815. if user_need_skin == '':
  816. curs.execute(db_change('select data from other where name = "skin"'))
  817. skin_exist = curs.fetchall()
  818. if skin_exist:
  819. user_need_skin = skin_exist[0][0]
  820. if user_need_skin != '' and user_need_skin in skin_list:
  821. skin = user_need_skin
  822. if set_n == 0:
  823. return './views/' + skin + '/index.html'
  824. else:
  825. return skin
  826. def wiki_css(data):
  827. global global_wiki_set
  828. # without_DB
  829. data += ['' for _ in range(0, 3 - len(data))]
  830. data_css = ''
  831. data_css_add = ''
  832. if 'main_css' in global_wiki_set:
  833. data_css = global_wiki_set['main_css']
  834. else:
  835. data_css += '<meta http-equiv="Cache-Control" content="max-age=3600">'
  836. # Func JS
  837. data_css += '<script src="/views/main_css/js/func/func.js"></script>'
  838. data_css += '<script defer src="/views/main_css/js/func/insert_version.js"></script>'
  839. data_css += '<script defer src="/views/main_css/js/func/insert_user_info.js"></script>'
  840. data_css += '<script defer src="/views/main_css/js/func/insert_version_skin.js"></script>'
  841. data_css += '<script defer src="/views/main_css/js/func/insert_http_warning_text.js"></script>'
  842. data_css += '<script defer src="/views/main_css/js/func/ie_end_of_life.js"></script>'
  843. data_css += '<script defer src="/views/main_css/js/func/shortcut.js"></script>'
  844. # Route JS
  845. data_css += '<script src="/views/main_css/js/route/editor.js"></script>'
  846. data_css += '<script src="/views/main_css/js/route/editor_sub.js"></script>'
  847. data_css += '<script src="/views/main_css/js/route/render.js"></script>'
  848. data_css += '<script src="/views/main_css/js/route/topic.js"></script>'
  849. # Main CSS
  850. data_css += '<link rel="stylesheet" href="/views/main_css/css/main.css">'
  851. # External
  852. data_css += '<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script>'
  853. data_css += '<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js" integrity="sha512-rdhY3cbXURo13l/WU9VlaRyaIYeJ/KBakckXIvJNAQde8DgpOmE+eZf7ha4vdqVjTtwQt69bD2wH2LXob/LB7Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>'
  854. data_css += '<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/languages/x86asm.min.js" integrity="sha512-HeAchnWb+wLjUb2njWKqEXNTDlcd1QcyOVxb+Mc9X0bWY0U5yNHiY5hTRUt/0twG8NEZn60P3jttqBvla/i2gA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>'
  855. # External CSS
  856. data_css += '<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous">'
  857. global_wiki_set['main_css'] = data_css
  858. # Darkmode
  859. if flask.request.cookies.get('main_css_darkmode', '0') == '0':
  860. data_css += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/default.min.css" integrity="sha512-hasIneQUHlh06VNBe7f6ZcHmeRTLIaQWFd43YriJ0UND19bvYRauxthDg8E4eVNPm9bRUhr5JGeqH7FRFXQu5g==" crossorigin="anonymous" referrerpolicy="no-referrer" />'
  861. else:
  862. data_css += '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/dark.min.css" integrity="sha512-bfLTSZK4qMP/TWeS1XJAR/VDX0Uhe84nN5YmpKk5x8lMkV0D+LwbuxaJMYTPIV13FzEv4CUOhHoc+xZBDgG9QA==" crossorigin="anonymous" referrerpolicy="no-referrer" />'
  863. data = data[0:2] + ['', data_css_add + data_css] + data[2:]
  864. return data
  865. def cut_100(data):
  866. # without_DB
  867. if re.search(r'<div class="opennamu_render_complete">', data):
  868. data = re.sub(r'(.|\r|\n)*<div class="opennamu_render_complete">', '', data, 1)
  869. data = data.replace('<br>', ' ')
  870. data = data.replace('\r', '')
  871. data = data.replace('\n', ' ')
  872. data = re.sub(r'<[^<>]+>', ' ', data)
  873. data = data.replace('\n', ' ')
  874. data = re.sub(r' {2,}', ' ', data)
  875. data = re.sub(r'(^ +| +$)', '', data)
  876. data_len = len(data)
  877. if data_len > 100:
  878. return data[0:100]
  879. else:
  880. return data[0:data_len]
  881. else:
  882. return ''
  883. def wiki_set(num = 1):
  884. with get_db_connect() as conn:
  885. curs = conn.cursor()
  886. ip = ip_check()
  887. skin_name = skin_check(1)
  888. data_list = []
  889. curs.execute(db_change('select data from other where name = ?'), ['name'])
  890. db_data = curs.fetchall()
  891. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else ['Wiki']
  892. curs.execute(db_change('select data from other where name = "license"'))
  893. db_data = curs.fetchall()
  894. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else ['ARR']
  895. data_list += ['', '']
  896. curs.execute(db_change('select data from other where name = "logo" and coverage = ?'), [skin_name])
  897. db_data = curs.fetchall()
  898. if db_data and db_data[0][0] != '':
  899. data_list += [db_data[0][0]]
  900. else:
  901. curs.execute(db_change('select data from other where name = "logo" and coverage = ""'))
  902. db_data = curs.fetchall()
  903. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else [data_list[0]]
  904. head_data = ''
  905. curs.execute(db_change("select data from other where name = 'head' and coverage = ''"))
  906. db_data = curs.fetchall()
  907. head_data += db_data[0][0] if db_data and db_data[0][0] != '' else ''
  908. curs.execute(db_change("select data from other where name = 'head' and coverage = ?"), [skin_name])
  909. db_data = curs.fetchall()
  910. head_data += db_data[0][0] if db_data and db_data[0][0] != '' else ''
  911. data_list += [head_data]
  912. curs.execute(db_change("select data from other where name = 'top_menu'"))
  913. db_data = curs.fetchall()
  914. db_data = db_data[0][0] if db_data else ''
  915. db_data = db_data.replace('\r', '')
  916. curs.execute(db_change("select data from user_set where name = '' and id = ?"), [ip])
  917. db_data_2 = curs.fetchall()
  918. db_data_2 = db_data_2[0][0] if db_data_2 else ''
  919. db_data += db_data_2.replace('\r', '')
  920. if db_data != '':
  921. db_data = db_data.split('\n')
  922. if len(db_data) % 2 != 0:
  923. db_data += ['']
  924. db_data = [[db_data[for_a], db_data[for_a + 1]] for for_a in range(0, len(db_data), 2)]
  925. data_list += [db_data]
  926. return data_list
  927. def wiki_custom():
  928. with get_db_connect() as conn:
  929. curs = conn.cursor()
  930. ip = ip_check()
  931. skin_name = '_' + skin_check(1)
  932. if ip_or_user(ip) == 0:
  933. user_icon = 1
  934. user_name = ip
  935. if 'head' in flask.session:
  936. user_head = flask.session['head']
  937. else:
  938. curs.execute(db_change("select data from user_set where id = ? and name = 'custom_css'"), [ip])
  939. db_data = curs.fetchall()
  940. user_head = db_data[0][0] if db_data else ''
  941. flask.session['head'] = db_data[0][0] if db_data else ''
  942. if 'head' + skin_name in flask.session:
  943. user_head += flask.session['head' + skin_name]
  944. else:
  945. curs.execute(db_change("select data from user_set where id = ? and name = ?"), [ip, 'custom_css' + skin_name])
  946. db_data = curs.fetchall()
  947. user_head += db_data[0][0] if db_data else ''
  948. flask.session['head' + skin_name] = db_data[0][0] if db_data else ''
  949. curs.execute(db_change('select data from user_set where name = "email" and id = ?'), [ip])
  950. email = curs.fetchall()
  951. email = email[0][0] if email else ''
  952. if admin_check('all') == 1:
  953. user_admin = '1'
  954. user_acl_list = []
  955. curs.execute(db_change("select data from user_set where id = ? and name = 'acl'"), [ip])
  956. curs.execute(db_change('select acl from alist where name = ?'), [curs.fetchall()[0][0]])
  957. user_acl = curs.fetchall()
  958. for i in user_acl:
  959. user_acl_list += [i[0]]
  960. user_acl_list = user_acl_list if user_acl != [] else '0'
  961. else:
  962. user_admin = '0'
  963. user_acl_list = '0'
  964. curs.execute(db_change("select count(*) from user_notice where name = ? and readme = ''"), [ip])
  965. count = curs.fetchall()
  966. user_notice = str(count[0][0]) if count else '0'
  967. else:
  968. user_icon = 0
  969. user_name = load_lang('user')
  970. email = ''
  971. user_admin = '0'
  972. user_acl_list = '0'
  973. user_notice = '0'
  974. user_head = flask.session['head'] if 'head' in flask.session else ''
  975. user_head += flask.session['head' + skin_name] if 'head' + skin_name in flask.session else ''
  976. curs.execute(db_change("select title from rd where title = ? and stop = ''"), ['user:' + ip])
  977. user_topic = '1' if curs.fetchall() else '0'
  978. split_path = flask.request.path.split('/')
  979. if len(split_path) > 1:
  980. split_path = split_path[1]
  981. else:
  982. split_path = 0
  983. return [
  984. '',
  985. '',
  986. user_icon,
  987. user_head,
  988. email,
  989. user_name,
  990. user_admin,
  991. str(ban_check()),
  992. user_notice,
  993. user_acl_list,
  994. ip,
  995. user_topic,
  996. split_path
  997. ]
  998. def load_skin(data = '', set_n = 0, default = 0):
  999. # without_DB
  1000. # data -> 가장 앞에 있을 스킨 이름
  1001. # set_n == 0 -> 스트링으로 반환
  1002. # set_n == 1 -> 리스트로 반환
  1003. # default == 0 -> 디폴트 미포함
  1004. # default == 1 -> 디폴트 포함
  1005. if set_n == 0:
  1006. skin_return_data = ''
  1007. else:
  1008. skin_return_data = []
  1009. skin_list_get = os.listdir('views')
  1010. if default == 1:
  1011. skin_list_get = ['default'] + skin_list_get
  1012. for skin_data in skin_list_get:
  1013. if skin_data != 'default':
  1014. see_data = skin_data
  1015. else:
  1016. see_data = load_lang('default')
  1017. if skin_data != 'main_css':
  1018. if set_n == 0:
  1019. if skin_data == data:
  1020. skin_return_data = '' + \
  1021. '<option value="' + skin_data + '">' + \
  1022. see_data + \
  1023. '</option>' + \
  1024. '' + skin_return_data
  1025. else:
  1026. skin_return_data += '' + \
  1027. '<option value="' + skin_data + '">' + \
  1028. see_data + \
  1029. '</option>' + \
  1030. ''
  1031. else:
  1032. if skin_data == data:
  1033. skin_return_data = [skin_data] + skin_return_data
  1034. else:
  1035. skin_return_data += [skin_data]
  1036. return skin_return_data
  1037. # Func-markup
  1038. def render_set(doc_name = '', doc_data = '', data_type = 'view', data_in = '', doc_acl = ''):
  1039. with get_db_connect() as conn:
  1040. curs = conn.cursor()
  1041. # data_type in ['view', 'from', 'thread', 'raw', 'api_view', 'api_thread', 'backlink']
  1042. # data_type을 list 형식으로 개편 필요할 듯
  1043. if doc_name != '':
  1044. doc_acl = acl_check(doc_name, 'render') if doc_acl == '' else doc_acl
  1045. else:
  1046. doc_acl = 0
  1047. data_type = 'view' if data_type == '' else data_type
  1048. doc_data = 0 if doc_data == None else doc_data
  1049. acl_dict = {}
  1050. acl_dict[doc_name] = doc_acl
  1051. ip = ip_check()
  1052. if doc_acl == 1:
  1053. return 'HTTP Request 401.3'
  1054. else:
  1055. if data_type == 'raw':
  1056. return doc_data
  1057. if doc_data != 0:
  1058. render_lang_data = {
  1059. 'toc' : load_lang('toc'),
  1060. 'category' : load_lang('category')
  1061. }
  1062. get_class_render = class_do_render(conn, render_lang_data).do_render(doc_name, doc_data, data_type, data_in)
  1063. if 'include' in get_class_render[2]:
  1064. for_a = 0
  1065. while len(get_class_render[2]['include']) > for_a:
  1066. include_data = get_class_render[2]['include'][for_a]
  1067. if include_data[1] in acl_dict:
  1068. acl_result = acl_dict[include_data[1]]
  1069. else:
  1070. acl_result = acl_check(include_data[1], 'render')
  1071. acl_dict[include_data[1]] = acl_result
  1072. if acl_result == 0:
  1073. include_regex = re.compile('<div id="' + include_data[0] + '"><\\/div>')
  1074. if re.search(include_regex, get_class_render[0]):
  1075. include_data_render = class_do_render(conn, render_lang_data).do_render(include_data[1], include_data[2], data_type, include_data[0] + data_in)
  1076. if len(include_data) > 3:
  1077. include_data_render[0] = '<div id="' + include_data[0] + '" ' + include_data[3] + '>' + include_data_render[0] + '</div>'
  1078. else:
  1079. include_data_render[0] = '<div id="' + include_data[0] + '">' + include_data_render[0] + '</div>'
  1080. get_class_render[0] = re.sub(include_regex, include_data_render[0], get_class_render[0])
  1081. get_class_render[1] += include_data_render[1]
  1082. get_class_render[2]['include'] += include_data_render[2]['include']
  1083. for_a += 1
  1084. if data_type == 'backlink':
  1085. return ''
  1086. get_class_render[0] = '<div class="opennamu_render_complete">' + get_class_render[0] + '</div>'
  1087. curs.execute(db_change("select data from other where name = 'namumark_compatible'"))
  1088. db_data = curs.fetchall()
  1089. if db_data and db_data[0][0] != '':
  1090. get_class_render[0] = '''
  1091. <style>
  1092. .opennamu_render_complete {
  1093. font-size: 14.4px !important;
  1094. }
  1095. .opennamu_render_complete td {
  1096. padding: 5px 10px !important;
  1097. }
  1098. .opennamu_render_complete summary {
  1099. list-style: none !important;
  1100. font-weight: bold !important;
  1101. }
  1102. </style>
  1103. ''' + get_class_render[0]
  1104. table_set_data = get_main_skin_set(curs, flask.session, 'main_css_table_scroll', ip)
  1105. if table_set_data == 'on':
  1106. get_class_render[0] = '<style>.table_safe { overflow-x: scroll; white-space: nowrap; }</style>' + get_class_render[0]
  1107. joke_set_data = get_main_skin_set(curs, flask.session, 'main_css_view_joke', ip)
  1108. if joke_set_data == 'off':
  1109. get_class_render[0] = '<style>.opennamu_joke { display: none; }</style>' + get_class_render[0]
  1110. math_set_data = get_main_skin_set(curs, flask.session, 'main_css_math_scroll', ip)
  1111. if math_set_data == 'on':
  1112. get_class_render[0] = '<style>.katex .base { overflow-x: scroll; }</style>' + get_class_render[0]
  1113. if data_type == 'api_view' or data_type == 'api_thread':
  1114. return [
  1115. get_class_render[0],
  1116. get_class_render[1]
  1117. ]
  1118. else:
  1119. return get_class_render[0] + '<script>' + get_class_render[1] + '</script>'
  1120. else:
  1121. return 'HTTP Request 404'
  1122. def render_simple_set(data):
  1123. # without_DB
  1124. toc_data = ''
  1125. toc_regex = r'<h([1-6])>([^<>]+)<\/h[1-6]>'
  1126. toc_search_data = re.findall(toc_regex, data)
  1127. heading_stack = [0, 0, 0, 0, 0, 0]
  1128. if toc_search_data:
  1129. toc_data += '''
  1130. <div class="opennamu_TOC" id="toc">
  1131. <span class="opennamu_TOC_title">''' + load_lang('toc') + '''</span>
  1132. <br>
  1133. '''
  1134. for toc_search_in in toc_search_data:
  1135. heading_level = int(toc_search_in[0])
  1136. heading_level_str = str(heading_level)
  1137. heading_stack[heading_level - 1] += 1
  1138. for for_a in range(heading_level, 6):
  1139. heading_stack[for_a] = 0
  1140. heading_stack_str = ''.join([str(for_a) + '.' if for_a != 0 else '' for for_a in heading_stack])
  1141. heading_stack_str = re.sub(r'\.$', '', heading_stack_str)
  1142. toc_data += '''
  1143. <br>
  1144. <span class="opennamu_TOC_list">
  1145. ''' + ('<span style="margin-left: 10px;"></span>' * (heading_stack_str.count('.'))) + '''
  1146. <a href="#s-''' + heading_stack_str + '''">''' + heading_stack_str + '''.</a>
  1147. ''' + toc_search_in[1] + '''
  1148. </span>
  1149. '''
  1150. data = re.sub(toc_regex, '<h' + toc_search_in[0] + ' id="s-' + heading_stack_str + '"><a href="#toc">' + heading_stack_str + '.</a> ' + toc_search_in[1] + '</h' + toc_search_in[0] + '>', data, 1)
  1151. if toc_data != '':
  1152. toc_data += '</div>'
  1153. footnote_data = ''
  1154. footnote_regex = r'<sup>((?:(?!<sup>|<\/sup>).)+)<\/sup>'
  1155. footnote_search_data = re.findall(footnote_regex, data)
  1156. footnote_count = 1
  1157. if footnote_search_data:
  1158. footnote_data += '<div class="opennamu_footnote">'
  1159. for footnote_search in footnote_search_data:
  1160. footnote_count_str = str(footnote_count)
  1161. if footnote_count != 1:
  1162. footnote_data += '<br>'
  1163. footnote_data += '<a id="fn-' + footnote_count_str + '" href="#rfn-' + footnote_count_str + '">(' + footnote_count_str + ')</a> ' + footnote_search
  1164. data = re.sub(footnote_regex, '<sup id="rfn-' + footnote_count_str + '"><a href="#fn-' + footnote_count_str + '">(' + footnote_count_str + ')</a></sup>', data, 1)
  1165. footnote_count += 1
  1166. if footnote_data != '':
  1167. footnote_data += '</div>'
  1168. data = toc_data + data + footnote_data
  1169. return data
  1170. # Func-request
  1171. def send_email(who, title, data):
  1172. with get_db_connect() as conn:
  1173. curs = conn.cursor()
  1174. curs.execute(db_change('' + \
  1175. 'select name, data from other ' + \
  1176. 'where name = "smtp_email" or name = "smtp_pass" or name = "smtp_server" or name = "smtp_port" or name = "smtp_security"' + \
  1177. ''))
  1178. rep_data = curs.fetchall()
  1179. smtp_email = ''
  1180. smtp_pass = ''
  1181. smtp_server = ''
  1182. smtp_security = ''
  1183. smtp_port = ''
  1184. smtp = ''
  1185. for i in rep_data:
  1186. if i[0] == 'smtp_email':
  1187. smtp_email = i[1]
  1188. elif i[0] == 'smtp_pass':
  1189. smtp_pass = i[1]
  1190. elif i[0] == 'smtp_server':
  1191. smtp_server = i[1]
  1192. elif i[0] == 'smtp_security':
  1193. smtp_security = i[1]
  1194. elif i[0] == 'smtp_port':
  1195. smtp_port = i[1]
  1196. smtp_port = int(number_check(smtp_port))
  1197. if smtp_security == 'plain':
  1198. smtp = smtplib.SMTP(smtp_server, smtp_port)
  1199. elif smtp_security == 'starttls':
  1200. smtp = smtplib.SMTP(smtp_server, smtp_port)
  1201. smtp.starttls()
  1202. else:
  1203. # if smtp_security == 'tls':
  1204. smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
  1205. domain = load_domain()
  1206. wiki_name = wiki_set()[0]
  1207. msg = email.mime.text.MIMEText(data)
  1208. msg['Subject'] = title
  1209. msg['From'] = wiki_name + ' <noreply@' + domain + '>'
  1210. msg['To'] = who
  1211. try:
  1212. smtp.login(smtp_email, smtp_pass)
  1213. smtp.sendmail('openNAMU@' + domain, who, msg.as_string())
  1214. smtp.quit()
  1215. return 1
  1216. except Exception as e:
  1217. print('----')
  1218. print('Error : email send error')
  1219. print(e)
  1220. return 0
  1221. def captcha_get():
  1222. with get_db_connect() as conn:
  1223. curs = conn.cursor()
  1224. data = ''
  1225. if ip_or_user() != 0:
  1226. curs.execute(db_change('select data from other where name = "recaptcha"'))
  1227. recaptcha = curs.fetchall()
  1228. curs.execute(db_change('select data from other where name = "sec_re"'))
  1229. sec_re = curs.fetchall()
  1230. curs.execute(db_change('select data from other where name = "recaptcha_ver"'))
  1231. rec_ver = curs.fetchall()
  1232. if recaptcha and recaptcha[0][0] != '' and sec_re and sec_re[0][0] != '':
  1233. if not rec_ver or rec_ver[0][0] == '':
  1234. data += '' + \
  1235. '<script src="https://www.google.com/recaptcha/api.js" async defer></script>' + \
  1236. '<div class="g-recaptcha" data-sitekey="' + recaptcha[0][0] + '"></div>' + \
  1237. '<hr class="main_hr">' + \
  1238. ''
  1239. elif rec_ver[0][0] == 'v3':
  1240. data += '' + \
  1241. '<script src="https://www.google.com/recaptcha/api.js?render=' + recaptcha[0][0] + '"></script>' + \
  1242. '<input type="hidden" id="g-recaptcha" name="g-recaptcha">' + \
  1243. '<script type="text/javascript">' + \
  1244. 'grecaptcha.ready(function() {' + \
  1245. 'grecaptcha.execute(\'' + recaptcha[0][0] + '\', {action: \'homepage\'}).then(function(token) {' + \
  1246. 'document.getElementById(\'g-recaptcha\').value = token;' + \
  1247. '});' + \
  1248. '});' + \
  1249. '</script>' + \
  1250. ''
  1251. elif rec_ver[0][0] == 'cf':
  1252. data += '' + \
  1253. '<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?compat=recaptcha" async defer></script>' + \
  1254. '<div class="g-recaptcha" data-sitekey="' + recaptcha[0][0] + '"></div>' + \
  1255. '<hr class="main_hr">' + \
  1256. ''
  1257. else:
  1258. # rec_ver[0][0] == 'h'
  1259. data += '''
  1260. <script src="https://js.hcaptcha.com/1/api.js" async defer></script>
  1261. <div class="h-captcha" data-sitekey="''' + recaptcha[0][0] + '''"></div>
  1262. <hr class="main_hr">
  1263. '''
  1264. return data
  1265. def captcha_post(re_data, num = 1):
  1266. with get_db_connect() as conn:
  1267. curs = conn.cursor()
  1268. if num == 1 and ip_or_user() != 0:
  1269. curs.execute(db_change('select data from other where name = "sec_re"'))
  1270. sec_re = curs.fetchall()
  1271. curs.execute(db_change('select data from other where name = "recaptcha_ver"'))
  1272. rec_ver = curs.fetchall()
  1273. if captcha_get() != '':
  1274. if not rec_ver or rec_ver[0][0] in ('', 'v3'):
  1275. data = requests.post(
  1276. 'https://www.google.com/recaptcha/api/siteverify',
  1277. data = {
  1278. "secret" : sec_re[0][0],
  1279. "response" : re_data
  1280. }
  1281. )
  1282. elif rec_ver[0][0] == 'cf':
  1283. data = requests.post(
  1284. 'https://challenges.cloudflare.com/turnstile/v0/siteverify',
  1285. data = {
  1286. "secret" : sec_re[0][0],
  1287. "response" : re_data
  1288. }
  1289. )
  1290. else:
  1291. # rec_ver[0][0] == 'h'
  1292. data = requests.post(
  1293. 'https://hcaptcha.com/siteverify',
  1294. data = {
  1295. "secret" : sec_re[0][0],
  1296. "response" : re_data
  1297. }
  1298. )
  1299. if data.status_code == 200:
  1300. json_data = json.loads(data.text)
  1301. if json_data['success'] != True:
  1302. return 1
  1303. return 0
  1304. # Func-user
  1305. def do_user_name_check(user_name):
  1306. with get_db_connect() as conn:
  1307. curs = conn.cursor()
  1308. # XSS 필터
  1309. if html.escape(user_name) != user_name:
  1310. return 1
  1311. # IP와 혼동 방지
  1312. if ip_or_user(user_name) == 1:
  1313. return 1
  1314. # ID 필터
  1315. curs.execute(db_change('select html from html_filter where kind = "name"'))
  1316. set_d = curs.fetchall()
  1317. for i in set_d:
  1318. check_r = re.compile(i[0], re.I)
  1319. if check_r.search(user_name):
  1320. return 1
  1321. # ID 길이 제한 (128글자)
  1322. if len(user_name) > 128:
  1323. return 1
  1324. # 중복 확인
  1325. curs.execute(db_change("select id from user_set where name = 'user_name' and data = ?"), [user_name])
  1326. if curs.fetchall():
  1327. return 1
  1328. curs.execute(db_change("select id from user_set where id = ?"), [user_name])
  1329. if curs.fetchall():
  1330. return 1
  1331. return 0
  1332. def get_admin_auth_list(num = None):
  1333. # without_DB
  1334. check = {
  1335. 0 : 'owner',
  1336. 1 : 'ban',
  1337. 2 : 'nothing',
  1338. 3 : 'toron',
  1339. 4 : 'check',
  1340. 5 : 'acl',
  1341. 6 : 'hidel',
  1342. 7 : 'give'
  1343. }
  1344. if not num:
  1345. check = check[0]
  1346. elif num == 'all':
  1347. check = [check[i] for i in check]
  1348. else:
  1349. check = check[num]
  1350. return check
  1351. def get_admin_list(num = None):
  1352. with get_db_connect() as conn:
  1353. curs = conn.cursor()
  1354. if num == 'all':
  1355. curs.execute(db_change(
  1356. "select data from user_set where data != 'user' and name = 'acl'"
  1357. ))
  1358. db_data = curs.fetchall()
  1359. db_data = [db_data_in[0] for db_data_in in db_data] if db_data else []
  1360. return db_data
  1361. else:
  1362. check = get_admin_auth_list(num)
  1363. admin_list = []
  1364. curs.execute(db_change(
  1365. 'select name from alist where acl = ?'
  1366. ), [check])
  1367. db_data = curs.fetchall()
  1368. for db_data_in in db_data:
  1369. curs.execute(db_change(
  1370. "select id from user_set where data = ? and name = 'acl'"
  1371. ), [db_data_in[0]])
  1372. db_data_2 = curs.fetchall()
  1373. admin_list += [db_data_2_in[0] for db_data_2_in in db_data_2] if db_data_2 else []
  1374. return admin_list
  1375. def admin_check(num = None, what = None, name = ''):
  1376. with get_db_connect() as conn:
  1377. curs = conn.cursor()
  1378. ip = ip_check() if name == '' else name
  1379. time_data = get_time()
  1380. pass_ok = 0
  1381. if ip_or_user(ip) == 0:
  1382. curs.execute(db_change(
  1383. "select data from user_set where id = ? and name = 'acl'"
  1384. ), [ip])
  1385. user_auth = curs.fetchall()
  1386. if user_auth:
  1387. user_auth = user_auth[0][0]
  1388. check = get_admin_auth_list(num)
  1389. curs.execute(db_change(
  1390. 'select name from alist where name = ? and acl = "owner"'
  1391. ), [user_auth])
  1392. if curs.fetchall():
  1393. pass_ok = 1
  1394. else:
  1395. if num == 'all':
  1396. curs.execute(db_change(
  1397. 'select name from alist where name = ?'
  1398. ), [user_auth])
  1399. else:
  1400. curs.execute(db_change(
  1401. 'select name from alist where name = ? and acl = ?'
  1402. ), [user_auth, check])
  1403. if curs.fetchall():
  1404. pass_ok = 1
  1405. if pass_ok == 1:
  1406. if what:
  1407. curs.execute(db_change(
  1408. "insert into re_admin (who, what, time) values (?, ?, ?)"
  1409. ), [ip, what, time_data])
  1410. return 1
  1411. return 0
  1412. def acl_check(name = 'test', tool = '', topic_num = '1'):
  1413. with get_db_connect() as conn:
  1414. curs = conn.cursor()
  1415. ip = ip_check()
  1416. get_ban = ban_check()
  1417. if tool == '' and name:
  1418. if acl_check(name, 'render') == 1:
  1419. return 1
  1420. user_page = re.search(r"^user:((?:(?!\/).)*)", name)
  1421. if user_page:
  1422. user_page = user_page.group(1)
  1423. if admin_check(5) == 1:
  1424. return 0
  1425. if get_ban == 1:
  1426. return 1
  1427. curs.execute(db_change(
  1428. "select data from acl where title = ? and type = 'decu'"
  1429. ), [name])
  1430. acl_data = curs.fetchall()
  1431. if acl_data:
  1432. if acl_data[0][0] == 'all':
  1433. return 0
  1434. elif acl_data[0][0] == 'user' and not ip_or_user(ip) == 1:
  1435. return 0
  1436. if ip == user_page and not ip_or_user(ip) == 1:
  1437. return 0
  1438. return 1
  1439. elif tool in ['document_edit', 'document_move', 'document_delete']:
  1440. if acl_check(name, '') == 1:
  1441. return 1
  1442. elif tool in ['bbs_edit', 'bbs_comment']:
  1443. if acl_check(name, 'bbs_view') == 1:
  1444. return 1
  1445. elif tool == 'topic':
  1446. curs.execute(db_change("select title from rd where code = ?"), [topic_num])
  1447. name = curs.fetchall()
  1448. name = name[0][0] if name else 'test'
  1449. if tool in ['topic']:
  1450. end = 3
  1451. elif tool in ['render', 'vote', '', 'document_edit', 'document_move', 'document_delete', 'document_edit', 'bbs_edit', 'bbs_comment']:
  1452. end = 2
  1453. else:
  1454. end = 1
  1455. for i in range(0, end):
  1456. if tool == '':
  1457. if i == 0:
  1458. curs.execute(db_change(
  1459. "select data from acl where title = ? and type = 'decu'"
  1460. ), [name])
  1461. '''
  1462. elif i == 1:
  1463. curs.execute(db_change(
  1464. "select plus from html_filter where kind = 'document'"
  1465. ))
  1466. '''
  1467. else:
  1468. curs.execute(db_change(
  1469. 'select data from other where name = "edit"'
  1470. ))
  1471. num = 5
  1472. elif tool == 'document_move':
  1473. if i == 0:
  1474. curs.execute(db_change(
  1475. "select data from acl where title = ? and type = 'document_move_acl'"
  1476. ), [name])
  1477. else:
  1478. curs.execute(db_change(
  1479. 'select data from other where name = "document_move_acl"'
  1480. ))
  1481. num = 5
  1482. elif tool == 'document_edit':
  1483. if i == 0:
  1484. curs.execute(db_change(
  1485. "select data from acl where title = ? and type = 'document_edit_acl'"
  1486. ), [name])
  1487. else:
  1488. curs.execute(db_change(
  1489. 'select data from other where name = "document_edit_acl"'
  1490. ))
  1491. num = 5
  1492. elif tool == 'document_delete':
  1493. if i == 0:
  1494. curs.execute(db_change(
  1495. "select data from acl where title = ? and type = 'document_delete_acl'"
  1496. ), [name])
  1497. else:
  1498. curs.execute(db_change(
  1499. 'select data from other where name = "document_delete_acl"'
  1500. ))
  1501. num = 5
  1502. elif tool == 'topic':
  1503. if i == 0:
  1504. curs.execute(db_change(
  1505. "select acl from rd where code = ?"
  1506. ), [topic_num])
  1507. elif i == 1:
  1508. curs.execute(db_change(
  1509. "select data from acl where title = ? and type = 'dis'"
  1510. ), [name])
  1511. else:
  1512. curs.execute(db_change(
  1513. 'select data from other where name = "discussion"'
  1514. ))
  1515. num = 3
  1516. elif tool == 'topic_view':
  1517. curs.execute(db_change("select set_data from topic_set where thread_code = ? and set_name = 'thread_view_acl'"), [
  1518. topic_num
  1519. ])
  1520. num = 3
  1521. elif tool == 'upload':
  1522. curs.execute(db_change(
  1523. "select data from other where name = 'upload_acl'"
  1524. ))
  1525. num = 5
  1526. elif tool == 'many_upload':
  1527. curs.execute(db_change(
  1528. "select data from other where name = 'many_upload_acl'"
  1529. ))
  1530. num = 5
  1531. elif tool == 'vote':
  1532. if i == 0:
  1533. curs.execute(db_change(
  1534. 'select acl from vote where id = ? and user = ""'
  1535. ), [topic_num])
  1536. else:
  1537. curs.execute(db_change(
  1538. 'select data from other where name = "vote_acl"'
  1539. ))
  1540. num = None
  1541. elif tool == 'slow_edit':
  1542. curs.execute(db_change(
  1543. 'select data from other where name = "slow_edit_acl"'
  1544. ))
  1545. num = 'all'
  1546. elif tool == 'edit_bottom_compulsion':
  1547. curs.execute(db_change(
  1548. 'select data from other where name = "edit_bottom_compulsion_acl"'
  1549. ))
  1550. num = 'all'
  1551. elif tool == 'bbs_edit':
  1552. if i == 0:
  1553. curs.execute(db_change('select set_data from bbs_set where set_name = "bbs_edit_acl" and set_id = ?'), [name])
  1554. else:
  1555. curs.execute(db_change('select set_data from bbs_set where set_name = "bbs_acl" and set_id = ?'), [name])
  1556. num = 'all'
  1557. elif tool == 'bbs_comment':
  1558. if i == 0:
  1559. curs.execute(db_change('select set_data from bbs_set where set_name = "bbs_comment_acl" and set_id = ?'), [name])
  1560. else:
  1561. curs.execute(db_change('select set_data from bbs_set where set_name = "bbs_acl" and set_id = ?'), [name])
  1562. num = 'all'
  1563. elif tool == 'bbs_view':
  1564. curs.execute(db_change('select set_data from bbs_set where set_name = "bbs_view_acl" and set_id = ?'), [name])
  1565. num = 'all'
  1566. else:
  1567. # tool == 'render'
  1568. if i == 0:
  1569. curs.execute(db_change(
  1570. "select data from acl where title = ? and type = 'view'"
  1571. ), [name])
  1572. else:
  1573. curs.execute(db_change("select data from other where name = 'all_view_acl'"))
  1574. num = 5
  1575. acl_data = curs.fetchall()
  1576. if not acl_data or acl_data[0][0] == '':
  1577. if tool == 'slow_edit' or tool == 'edit_bottom_compulsion':
  1578. acl_data = [['not_all']]
  1579. else:
  1580. acl_data = [['normal']]
  1581. except_ban_tool_list = ['render', 'topic_view', 'bbs_view']
  1582. if acl_data[0][0] != 'normal':
  1583. if not acl_data[0][0] in ['ban', 'ban_admin'] and not tool in except_ban_tool_list:
  1584. if get_ban == 1:
  1585. return 1
  1586. if acl_data[0][0] in ['all', 'ban']:
  1587. return 0
  1588. elif acl_data[0][0] == 'user':
  1589. if ip_or_user(ip) != 1:
  1590. return 0
  1591. elif acl_data[0][0] == 'admin':
  1592. if ip_or_user(ip) != 1:
  1593. if admin_check(num) == 1:
  1594. return 0
  1595. elif acl_data[0][0] == '50_edit':
  1596. if ip_or_user(ip) != 1:
  1597. if admin_check(num) == 1:
  1598. return 0
  1599. else:
  1600. curs.execute(db_change(
  1601. "select count(*) from history where ip = ?"
  1602. ), [ip])
  1603. count = curs.fetchall()
  1604. count = count[0][0] if count else 0
  1605. if count >= 50:
  1606. return 0
  1607. elif acl_data[0][0] == 'before':
  1608. if ip_or_user(ip) != 1:
  1609. if admin_check(num) == 1:
  1610. return 0
  1611. curs.execute(db_change(
  1612. "select ip from history where title = ? and ip = ?"
  1613. ), [name, ip])
  1614. if curs.fetchall():
  1615. return 0
  1616. elif acl_data[0][0] == '30_day' or acl_data[0][0] == '90_day':
  1617. if ip_or_user(ip) != 1:
  1618. if admin_check(num) == 1:
  1619. return 0
  1620. else:
  1621. curs.execute(db_change(
  1622. "select data from user_set where id = ? and name = 'date'"
  1623. ), [ip])
  1624. user_date = curs.fetchall()[0][0]
  1625. if acl_data[0][0] == '30_day':
  1626. time_1 = datetime.datetime.strptime(
  1627. user_date,
  1628. '%Y-%m-%d %H:%M:%S'
  1629. ) + datetime.timedelta(days = 30)
  1630. else:
  1631. time_1 = datetime.datetime.strptime(
  1632. user_date,
  1633. '%Y-%m-%d %H:%M:%S'
  1634. ) + datetime.timedelta(days = 90)
  1635. time_2 = datetime.datetime.strptime(
  1636. get_time(),
  1637. '%Y-%m-%d %H:%M:%S'
  1638. )
  1639. if time_2 > time_1:
  1640. return 0
  1641. elif acl_data[0][0] == 'email':
  1642. if ip_or_user(ip) != 1:
  1643. if admin_check(num) == 1:
  1644. return 0
  1645. else:
  1646. curs.execute(db_change(
  1647. "select data from user_set where id = ? and name = 'email'"
  1648. ), [ip])
  1649. if curs.fetchall():
  1650. return 0
  1651. elif acl_data[0][0] == 'owner':
  1652. if admin_check() == 1:
  1653. return 0
  1654. elif acl_data[0][0] == 'ban_admin':
  1655. if admin_check(1) == 1 or get_ban == 1:
  1656. return 0
  1657. elif acl_data[0][0] == 'not_all':
  1658. return 1
  1659. return 1
  1660. elif i == (end - 1):
  1661. if not tool in except_ban_tool_list:
  1662. if get_ban == 1:
  1663. return 1
  1664. if tool == 'topic':
  1665. curs.execute(db_change(
  1666. "select title from rd where code = ? and stop != ''"
  1667. ), [topic_num])
  1668. if curs.fetchall():
  1669. if admin_check(3, 'topic (code ' + topic_num + ')') == 1:
  1670. return 0
  1671. else:
  1672. return 1
  1673. else:
  1674. return 0
  1675. else:
  1676. return 0
  1677. return 1
  1678. def ban_check(ip = None, tool = ''):
  1679. with get_db_connect() as conn:
  1680. curs = conn.cursor()
  1681. ip = ip_check() if not ip else ip
  1682. tool = '' if not tool else tool
  1683. if admin_check(None, None, ip) == 1:
  1684. return 0
  1685. curs.execute(db_change(
  1686. "update rb set ongoing = '' " + \
  1687. "where end < ? and end != '' and ongoing = '1'"
  1688. ), [get_time()])
  1689. curs.execute(db_change("" + \
  1690. "select login, block from rb " + \
  1691. "where band = 'regex' and ongoing = '1'" + \
  1692. ""))
  1693. regex_d = curs.fetchall()
  1694. for test_r in regex_d:
  1695. g_regex = re.compile(test_r[1])
  1696. if g_regex.search(ip):
  1697. if tool == 'login':
  1698. if test_r[0] != 'O':
  1699. return 1
  1700. else:
  1701. return 1
  1702. curs.execute(db_change("" + \
  1703. "select login from rb " + \
  1704. "where block = ? and band = '' and ongoing = '1'" + \
  1705. "" + \
  1706. ""), [ip])
  1707. ban_d = curs.fetchall()
  1708. if ban_d:
  1709. if tool == 'login':
  1710. if ban_d[0][0] != 'O':
  1711. return 1
  1712. else:
  1713. return 1
  1714. return 0
  1715. def ip_pas(raw_ip, type_data = 0):
  1716. with get_db_connect() as conn:
  1717. curs = conn.cursor()
  1718. end_ip = {}
  1719. return_data = 0
  1720. if type(raw_ip) != type([]):
  1721. get_ip = [raw_ip]
  1722. return_data = 1
  1723. else:
  1724. get_ip = raw_ip
  1725. admin_auth = admin_check(1)
  1726. curs.execute(db_change("select data from other where name = 'ip_view'"))
  1727. db_data = curs.fetchall()
  1728. ip_view = db_data[0][0] if db_data else ''
  1729. ip_view = '' if admin_auth == 1 else ip_view
  1730. curs.execute(db_change("select data from other where name = 'user_name_view'"))
  1731. db_data = curs.fetchall()
  1732. user_name_view = db_data[0][0] if db_data else ''
  1733. user_name_view = '' if admin_auth == 1 else user_name_view
  1734. get_ip = list(set(get_ip))
  1735. for raw_ip in get_ip:
  1736. change_ip = 0
  1737. is_this_ip = ip_or_user(raw_ip)
  1738. if is_this_ip != 0:
  1739. # ip user
  1740. if ip_view != '':
  1741. try:
  1742. ip = ipaddress.ip_address(raw_ip)
  1743. if type(ip) == ipaddress.IPv6Address:
  1744. ip = ip.exploded
  1745. ip = re.sub(r':([^:]*):([^:]*)$', ':*:*', ip)
  1746. else:
  1747. ip = ip.exploded
  1748. ip = re.sub(r'\.([^.]*)\.([^.]*)$', '.*.*', ip)
  1749. # ip = hashlib.sha3_224(bytes(raw_ip, 'utf-8')).hexdigest()
  1750. # ip = ip[0:4] + '-' + ip[4:8] + '-' + ip[8:12] + '-' + ip[12:16]
  1751. change_ip = 1
  1752. except:
  1753. ip = raw_ip
  1754. else:
  1755. ip = raw_ip
  1756. else:
  1757. # not ip user
  1758. if user_name_view != '':
  1759. curs.execute(db_change("select data from user_set where id = ? and name = 'sub_user_name'"), [raw_ip])
  1760. db_data = curs.fetchall()
  1761. if db_data and db_data[0][0] != '':
  1762. ip = db_data[0][0]
  1763. else:
  1764. ip = load_lang('member')
  1765. change_ip = 1
  1766. else:
  1767. curs.execute(db_change('select data from user_set where name = "user_name" and id = ?'), [raw_ip])
  1768. db_data = curs.fetchall()
  1769. ip = db_data[0][0] if db_data and db_data[0][0] != '' else raw_ip
  1770. if type_data == 0 and change_ip == 0:
  1771. if is_this_ip == 0:
  1772. ip = '<a href="/w/' + url_pas('user:' + raw_ip) + '">' + ip + '</a>'
  1773. if admin_check('all', None, raw_ip) == 1:
  1774. ip = '<b>' + ip + '</b>'
  1775. curs.execute(db_change('select data from user_set where name = "user_title" and id = ?'), [raw_ip])
  1776. db_data = curs.fetchall()
  1777. if db_data:
  1778. ip = db_data[0][0] + ip
  1779. if ban_check(raw_ip) == 1:
  1780. ip = '<s>' + ip + '</s>'
  1781. if ban_check(raw_ip, 'login') == 1:
  1782. ip = '<i>' + ip + '</i>'
  1783. ip = ip + ' <a href="/user/' + url_pas(raw_ip) + '">(' + load_lang('tool') + ')</a>'
  1784. end_ip[raw_ip] = ip
  1785. if return_data == 1:
  1786. return end_ip[raw_ip]
  1787. else:
  1788. return end_ip
  1789. # Func-edit
  1790. def get_edit_text_bottom():
  1791. with get_db_connect() as conn:
  1792. curs = conn.cursor()
  1793. b_text = ''
  1794. curs.execute(db_change('select data from other where name = "edit_bottom_text"'))
  1795. db_data= curs.fetchall()
  1796. if db_data and db_data[0][0] != '':
  1797. b_text = '' + \
  1798. db_data[0][0] + \
  1799. '<hr class="main_hr">' + \
  1800. ''
  1801. return b_text
  1802. def get_edit_text_bottom_check_box():
  1803. with get_db_connect() as conn:
  1804. curs = conn.cursor()
  1805. cccb_text = ''
  1806. curs.execute(db_change('select data from other where name = "copyright_checkbox_text"'))
  1807. sql_d = curs.fetchall()
  1808. if sql_d and sql_d[0][0] != '':
  1809. cccb_text = '' + \
  1810. '<input type="checkbox" name="copyright_agreement" value="yes"> ' + sql_d[0][0] + \
  1811. '<hr class="main_hr">' + \
  1812. ''
  1813. return cccb_text
  1814. def do_edit_text_bottom_check_box_check(data):
  1815. with get_db_connect() as conn:
  1816. curs = conn.cursor()
  1817. curs.execute(db_change('select data from other where name = "copyright_checkbox_text"'))
  1818. db_data = curs.fetchall()
  1819. if db_data and db_data[0][0] != '':
  1820. if data != 'yes':
  1821. return 1
  1822. return 0
  1823. def do_edit_send_check(data):
  1824. with get_db_connect() as conn:
  1825. curs = conn.cursor()
  1826. curs.execute(db_change('select data from other where name = "edit_bottom_compulsion"'))
  1827. db_data = curs.fetchall()
  1828. if db_data and db_data[0][0] != '':
  1829. if acl_check(None, 'edit_bottom_compulsion') == 1:
  1830. if data == '':
  1831. return 1
  1832. return 0
  1833. def do_edit_slow_check(do_type = 'edit'):
  1834. with get_db_connect() as conn:
  1835. curs = conn.cursor()
  1836. if do_type == 'edit':
  1837. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1838. else:
  1839. # do_type == 'thread'
  1840. curs.execute(db_change("select data from other where name = 'slow_thread'"))
  1841. slow_edit = curs.fetchall()
  1842. if slow_edit and slow_edit[0][0] != '':
  1843. if acl_check(None, 'slow_edit') == 1:
  1844. slow_edit = int(number_check(slow_edit[0][0]))
  1845. if do_type == 'edit':
  1846. curs.execute(db_change("select date from history where ip = ? order by date desc limit 1"), [ip_check()])
  1847. else:
  1848. curs.execute(db_change("select date from topic where ip = ? order by date desc limit 1"), [ip_check()])
  1849. last_edit_data = curs.fetchall()
  1850. if last_edit_data:
  1851. last_edit_data = int(re.sub(' |:|-', '', last_edit_data[0][0]))
  1852. now_edit_data = int((
  1853. datetime.datetime.now() - datetime.timedelta(seconds = slow_edit)
  1854. ).strftime("%Y%m%d%H%M%S"))
  1855. if last_edit_data > now_edit_data:
  1856. return 1
  1857. return 0
  1858. def do_edit_filter(data):
  1859. with get_db_connect() as conn:
  1860. curs = conn.cursor()
  1861. if admin_check(1) != 1:
  1862. curs.execute(db_change(
  1863. "select plus, plus_t from html_filter where kind = 'regex_filter' and plus != ''"
  1864. ))
  1865. for data_list in curs.fetchall():
  1866. match = re.compile(data_list[0], re.I)
  1867. if match.search(data):
  1868. ban_insert(
  1869. ip_check(),
  1870. '0' if data_list[1] == 'X' else data_list[1],
  1871. 'edit filter',
  1872. None,
  1873. 'tool:edit filter'
  1874. )
  1875. return 1
  1876. return 0
  1877. def do_title_length_check(name, check_type = 'document'):
  1878. with get_db_connect() as conn:
  1879. curs = conn.cursor()
  1880. if check_type == 'topic':
  1881. curs.execute(db_change('select data from other where name = "title_topic_max_length"'))
  1882. db_data = curs.fetchall()
  1883. if db_data and db_data[0][0] != '':
  1884. db_data = int(number_check(db_data[0][0]))
  1885. if len(name) > db_data:
  1886. return 1
  1887. else:
  1888. curs.execute(db_change('select data from other where name = "title_max_length"'))
  1889. db_data = curs.fetchall()
  1890. if db_data and db_data[0][0] != '':
  1891. db_data = int(number_check(db_data[0][0]))
  1892. if len(name) > db_data:
  1893. return 1
  1894. return 0
  1895. # Func-insert
  1896. def do_add_thread(thread_code, thread_data, thread_top = '', thread_id = ''):
  1897. with get_db_connect() as conn:
  1898. curs = conn.cursor()
  1899. if thread_id == '':
  1900. curs.execute(db_change("select id from topic where code = ? order by id + 0 desc limit 1"), [thread_code])
  1901. db_data = curs.fetchall()
  1902. if db_data:
  1903. thread_id = str(int(db_data[0][0]) + 1)
  1904. else:
  1905. thread_id = '1'
  1906. curs.execute(db_change("insert into topic (id, data, date, ip, block, top, code) values (?, ?, ?, ?, ?, '', ?)"), [
  1907. thread_id,
  1908. thread_data,
  1909. get_time(),
  1910. ip_check(),
  1911. thread_top,
  1912. thread_code
  1913. ])
  1914. def do_reload_recent_thread(topic_num, date, name = None, sub = None):
  1915. with get_db_connect() as conn:
  1916. curs = conn.cursor()
  1917. curs.execute(db_change("select code from rd where code = ?"), [topic_num])
  1918. if curs.fetchall():
  1919. curs.execute(db_change("update rd set date = ? where code = ?"), [
  1920. date,
  1921. topic_num
  1922. ])
  1923. else:
  1924. curs.execute(db_change(
  1925. "insert into rd (title, sub, code, date, band, stop, agree, acl) values (?, ?, ?, ?, '', '', '', '')"
  1926. ), [
  1927. name,
  1928. sub,
  1929. topic_num,
  1930. date
  1931. ])
  1932. def add_alarm(to_user, from_user, context):
  1933. with get_db_connect() as conn:
  1934. curs = conn.cursor()
  1935. if to_user != from_user:
  1936. context = from_user + ' | ' + context
  1937. count = '1'
  1938. curs.execute(db_change("select id from user_notice where name = ? order by id + 0 desc"), [to_user])
  1939. db_data = curs.fetchall()
  1940. if db_data:
  1941. count = str(int(db_data[0][0]) + 1)
  1942. curs.execute(db_change(
  1943. 'insert into user_notice (id, name, data, date, readme) values (?, ?, ?, ?, "")'
  1944. ), [count, to_user, context, get_time()])
  1945. def add_user(user_name, user_pw, user_email = '', user_encode = ''):
  1946. with get_db_connect() as conn:
  1947. curs = conn.cursor()
  1948. if user_encode == '':
  1949. user_pw_hash = pw_encode(user_pw)
  1950. curs.execute(db_change('select data from other where name = "encode"'))
  1951. data_encode = curs.fetchall()
  1952. data_encode = data_encode[0][0]
  1953. else:
  1954. user_pw_hash = user_pw
  1955. data_encode = user_encode
  1956. curs.execute(db_change("select id from user_set limit 1"))
  1957. if not curs.fetchall():
  1958. user_auth = 'owner'
  1959. else:
  1960. user_auth = 'user'
  1961. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'pw', ?)"), [
  1962. user_name,
  1963. user_pw_hash
  1964. ])
  1965. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'acl', ?)"), [
  1966. user_name,
  1967. user_auth
  1968. ])
  1969. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'date', ?)"), [
  1970. user_name,
  1971. get_time()
  1972. ])
  1973. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'encode', ?)"), [
  1974. user_name,
  1975. data_encode
  1976. ])
  1977. if user_email != '':
  1978. curs.execute(db_change("insert into user_set (name, id, data) values ('email', ?, ?)"), [
  1979. user_name,
  1980. user_email
  1981. ])
  1982. def ua_plus(u_id, u_ip, u_agent, time):
  1983. with get_db_connect() as conn:
  1984. curs = conn.cursor()
  1985. curs.execute(db_change("select data from other where name = 'ua_get'"))
  1986. rep_data = curs.fetchall()
  1987. if rep_data and rep_data[0][0] != '':
  1988. pass
  1989. else:
  1990. curs.execute(db_change(
  1991. "insert into ua_d (name, ip, ua, today, sub) values (?, ?, ?, ?, '')"
  1992. ), [
  1993. u_id,
  1994. u_ip,
  1995. u_agent,
  1996. time
  1997. ])
  1998. def ban_insert(name, end, why, login, blocker, type_d = None):
  1999. with get_db_connect() as conn:
  2000. curs = conn.cursor()
  2001. now_time = get_time()
  2002. band = type_d if type_d else ''
  2003. curs.execute(db_change(
  2004. "update rb set ongoing = '' where end < ? and end != '' and ongoing = '1'"
  2005. ), [now_time])
  2006. curs.execute(db_change("" + \
  2007. "select block from rb " + \
  2008. "where ((end > ? and end != '') or end = '') and block = ? and " + \
  2009. "band = ? and ongoing = '1'" + \
  2010. ""), [now_time, name, band])
  2011. if curs.fetchall():
  2012. curs.execute(db_change(
  2013. "insert into rb (block, end, today, blocker, why, band) values (?, ?, ?, ?, ?, ?)"
  2014. ), [
  2015. name,
  2016. 'release',
  2017. now_time,
  2018. blocker,
  2019. '',
  2020. band
  2021. ])
  2022. curs.execute(db_change(
  2023. "update rb set ongoing = '' where block = ? and band = ? and ongoing = '1'"
  2024. ), [name, band])
  2025. else:
  2026. login = 'O' if login != '' else ''
  2027. if end != '0':
  2028. end = int(number_check(end))
  2029. time = datetime.datetime.now()
  2030. plus = datetime.timedelta(seconds = end)
  2031. r_time = (time + plus).strftime("%Y-%m-%d %H:%M:%S")
  2032. else:
  2033. r_time = ''
  2034. curs.execute(db_change(
  2035. "insert into rb (block, end, today, blocker, why, band, ongoing, login) " + \
  2036. "values (?, ?, ?, ?, ?, ?, '1', ?)"
  2037. ), [
  2038. name,
  2039. r_time,
  2040. now_time,
  2041. blocker,
  2042. why,
  2043. band,
  2044. login
  2045. ])
  2046. def history_plus(title, data, date, ip, send, leng, t_check = '', mode = ''):
  2047. with get_db_connect() as conn:
  2048. curs = conn.cursor()
  2049. # 여기 좀 느린 듯
  2050. curs.execute(db_change('select data from other where name = "history_recording_off"'))
  2051. db_data = curs.fetchall()
  2052. if db_data and db_data[0][0] != '':
  2053. return 0
  2054. if mode == 'add':
  2055. curs.execute(db_change(
  2056. "select id from history where title = ? order by id + 0 asc limit 1"
  2057. ), [title])
  2058. id_data = curs.fetchall()
  2059. id_data = str(int(id_data[0][0]) - 1) if id_data else '0'
  2060. else:
  2061. curs.execute(db_change(
  2062. "select id from history where title = ? order by id + 0 desc limit 1"
  2063. ), [title])
  2064. id_data = curs.fetchall()
  2065. id_data = str(int(id_data[0][0]) + 1) if id_data else '1'
  2066. mode = mode if not re.search('^user:', title) else 'user'
  2067. send = re.sub(r'\(|\)|<|>', '', send)
  2068. send = send[:128] if len(send) > 128 else send
  2069. send = send + ' (' + t_check + ')' if t_check != '' else send
  2070. if mode != 'add' and mode != 'user':
  2071. curs.execute(db_change("select count(*) from rc where type = 'normal'"))
  2072. if curs.fetchall()[0][0] >= 200:
  2073. curs.execute(db_change(
  2074. "select id, title from rc where type = 'normal' order by date asc limit 1"
  2075. ))
  2076. rc_data = curs.fetchall()
  2077. if rc_data:
  2078. curs.execute(db_change(
  2079. 'delete from rc where id = ? and title = ? and type = "normal"'
  2080. ), [
  2081. rc_data[0][0],
  2082. rc_data[0][1]
  2083. ])
  2084. curs.execute(db_change(
  2085. "insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"
  2086. ), [
  2087. id_data,
  2088. title,
  2089. date
  2090. ])
  2091. if mode != 'add':
  2092. curs.execute(db_change("select count(*) from rc where type = ?"), [mode])
  2093. if curs.fetchall()[0][0] >= 200:
  2094. curs.execute(db_change(
  2095. "select id, title from rc where type = ? order by date asc limit 1"
  2096. ), [mode])
  2097. rc_data = curs.fetchall()
  2098. if rc_data:
  2099. curs.execute(db_change(
  2100. 'delete from rc where id = ? and title = ? and type = ?'
  2101. ), [
  2102. rc_data[0][0],
  2103. rc_data[0][1],
  2104. mode
  2105. ])
  2106. curs.execute(db_change(
  2107. "insert into rc (id, title, date, type) values (?, ?, ?, ?)"
  2108. ), [
  2109. id_data,
  2110. title,
  2111. date,
  2112. mode
  2113. ])
  2114. curs.execute(db_change(
  2115. "insert into history (id, title, data, date, ip, send, leng, hide, type) " + \
  2116. "values (?, ?, ?, ?, ?, ?, ?, '', ?)"
  2117. ), [
  2118. id_data,
  2119. title,
  2120. data,
  2121. date,
  2122. ip,
  2123. send,
  2124. leng,
  2125. mode
  2126. ])
  2127. data_set_exist = '' if t_check != 'delete' else '1'
  2128. curs.execute(db_change("select doc_name from data_set where doc_name = ? and set_name = 'last_edit'"), [title])
  2129. db_data = curs.fetchall()
  2130. if db_data:
  2131. curs.execute(db_change("update data_set set set_data = ?, doc_rev = ? where doc_name = ? and set_name = 'last_edit'"), [date, data_set_exist, title])
  2132. else:
  2133. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, ?, 'last_edit', ?)"), [title, data_set_exist, date])
  2134. curs.execute(db_change("select doc_name from data_set where doc_name = ? and set_name = 'length'"), [title])
  2135. db_data = curs.fetchall()
  2136. if db_data:
  2137. curs.execute(db_change("update data_set set set_data = ?, doc_rev = ? where doc_name = ? and set_name = 'length'"), [len(data), data_set_exist, title])
  2138. else:
  2139. curs.execute(db_change("insert into data_set (doc_name, doc_rev, set_name, set_data) values (?, ?, 'length', ?)"), [title, data_set_exist, len(data)])
  2140. # Func-error
  2141. def re_error(data):
  2142. with get_db_connect() as conn:
  2143. curs = conn.cursor()
  2144. if data == '/ban':
  2145. if ban_check() == 1:
  2146. end = '<div id="opennamu_get_user_info">' + ip_check() + '</div>'
  2147. else:
  2148. end = '<ul class="opennamu_ul"><li>' + load_lang('authority_error') + '</li></ul>'
  2149. return easy_minify(flask.render_template(skin_check(),
  2150. imp = [load_lang('error'), wiki_set(), wiki_custom(), wiki_css([0, 0])],
  2151. data = '<h2>' + load_lang('error') + '</h2>' + end,
  2152. menu = 0
  2153. )), 401
  2154. else:
  2155. title = load_lang('error')
  2156. sub_title = title
  2157. num = int(number_check(data.replace('/error/', '')))
  2158. if num == 1:
  2159. data = load_lang('no_login_error')
  2160. elif num == 2:
  2161. data = load_lang('no_exist_user_error')
  2162. elif num == 3:
  2163. data = load_lang('authority_error')
  2164. elif num == 4:
  2165. data = load_lang('no_admin_block_error')
  2166. elif num == 5:
  2167. data = load_lang('error_skin_set')
  2168. elif num == 8:
  2169. data = '' + \
  2170. load_lang('long_id_error') + '<br>' + \
  2171. load_lang('id_char_error') + ' <a href="/name_filter">(' + load_lang('id_filter_list') + ')</a><br>' + \
  2172. load_lang('same_id_exist_error') + \
  2173. ''
  2174. elif num == 9:
  2175. data = load_lang('file_exist_error')
  2176. elif num == 10:
  2177. data = load_lang('password_error')
  2178. elif num == 11:
  2179. data = load_lang('topic_long_error')
  2180. elif num == 12:
  2181. data = load_lang('email_error')
  2182. elif num == 13:
  2183. data = load_lang('recaptcha_error')
  2184. elif num == 14:
  2185. data = load_lang('file_extension_error') + ' <a href="/extension_filter">(' + load_lang('extension_filter_list') + ')</a>'
  2186. elif num == 15:
  2187. data = load_lang('edit_record_error')
  2188. elif num == 16:
  2189. data = load_lang('same_file_error')
  2190. elif num == 17:
  2191. curs.execute(db_change('select data from other where name = "upload"'))
  2192. db_data = curs.fetchall()
  2193. file_max = number_check(db_data[0][0]) if db_data and db_data[0][0] != '' else '2'
  2194. data = load_lang('file_capacity_error') + file_max
  2195. elif num == 18:
  2196. data = load_lang('email_send_error')
  2197. elif num == 19:
  2198. data = load_lang('move_error')
  2199. elif num == 20:
  2200. data = load_lang('password_diffrent_error')
  2201. elif num == 21:
  2202. data = load_lang('edit_filter_error')
  2203. elif num == 22:
  2204. data = load_lang('file_name_error')
  2205. elif num == 23:
  2206. data = load_lang('regex_error')
  2207. elif num == 24:
  2208. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  2209. db_data = curs.fetchall()
  2210. db_data = '' if not db_data else db_data[0][0]
  2211. data = load_lang('fast_edit_error') + db_data
  2212. elif num == 25:
  2213. data = load_lang('too_many_dec_error')
  2214. elif num == 26:
  2215. data = load_lang('application_not_found')
  2216. elif num == 27:
  2217. data = load_lang("invalid_password_error")
  2218. elif num == 28:
  2219. data = load_lang('watchlist_overflow_error')
  2220. elif num == 29:
  2221. data = load_lang('copyright_disagreed')
  2222. elif num == 30:
  2223. data = load_lang('ie_wrong_callback')
  2224. elif num == 33:
  2225. data = load_lang('restart_fail_error')
  2226. elif num == 34:
  2227. data = load_lang("update_error") + ' <a href="https://github.com/opennamu/opennamu">(Github)</a>'
  2228. elif num == 35:
  2229. data = load_lang('same_email_error')
  2230. elif num == 36:
  2231. data = load_lang('input_email_error')
  2232. elif num == 37:
  2233. data = load_lang('error_edit_send_request')
  2234. elif num == 38:
  2235. curs.execute(db_change("select data from other where name = 'title_max_length'"))
  2236. db_data = curs.fetchall()
  2237. db_data = '' if not db_data else db_data[0][0]
  2238. data = load_lang('error_title_length_too_long') + db_data
  2239. elif num == 39:
  2240. curs.execute(db_change("select data from other where name = 'title_topic_max_length'"))
  2241. db_data = curs.fetchall()
  2242. db_data = '' if not db_data else db_data[0][0]
  2243. data = load_lang('error_title_length_too_long') + db_data
  2244. elif num == 40:
  2245. curs.execute(db_change("select data from other where name = 'password_min_length'"))
  2246. db_data = curs.fetchall()
  2247. password_min_length = '' if not db_data else db_data[0][0]
  2248. data = load_lang('error_password_length_too_short') + password_min_length
  2249. elif num == 41:
  2250. curs.execute(db_change("select data from other where name = 'edit_timeout'"))
  2251. db_data = curs.fetchall()
  2252. db_data = '' if not db_data else db_data[0][0]
  2253. data = load_lang('timeout_error') + db_data
  2254. elif num == 42:
  2255. curs.execute(db_change("select data from other where name = 'slow_thread'"))
  2256. db_data = curs.fetchall()
  2257. db_data = '' if not db_data else db_data[0][0]
  2258. data = load_lang('fast_edit_error') + db_data
  2259. elif num == 43:
  2260. title = load_lang('application_submitted')
  2261. sub_title = title
  2262. data = load_lang('waiting_for_approval')
  2263. else:
  2264. data = '???'
  2265. if num == 5:
  2266. if flask.request.path != '/skin_set':
  2267. data += '<br>' + load_lang('error_skin_set_old') + ' <a href="/skin_set">(' + load_lang('go') + ')</a>'
  2268. return easy_minify(flask.render_template(skin_check(),
  2269. imp = [load_lang('skin_set'), wiki_set(), wiki_custom(), wiki_css([0, 0])],
  2270. data = '' + \
  2271. '<div id="main_skin_set">' + \
  2272. '<h2>' + load_lang('error') + '</h2>' + \
  2273. '<ul class="opennamu_ul">' + \
  2274. '<li>' + data + '</a></li>' + \
  2275. '</ul>' + \
  2276. '</div>' + \
  2277. '',
  2278. menu = [['change', load_lang('user_setting')], ['change/skin_set/main', load_lang('main_skin_set')]]
  2279. ))
  2280. else:
  2281. return easy_minify(flask.render_template(skin_check(),
  2282. imp = [title, wiki_set(), wiki_custom(), wiki_css([0, 0])],
  2283. data = '' + \
  2284. '<h2>' + sub_title + '</h2>' + \
  2285. '<ul class="opennamu_ul">' + \
  2286. '<li>' + data + '</li>' + \
  2287. '</ul>' + \
  2288. '',
  2289. menu = 0
  2290. )), 400