func.py 107 KB

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