func.py 105 KB

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