func.py 105 KB

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