func.py 102 KB

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