func.py 102 KB

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