func.py 93 KB

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