func.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  1. # Init
  2. import os
  3. import sys
  4. import platform
  5. import json
  6. import smtplib
  7. import zipfile
  8. import shutil
  9. import logging
  10. import random
  11. import email.mime.text
  12. import email.utils
  13. import email.header
  14. import urllib.request
  15. # Init-Version
  16. version_list = json.loads(open('version.json', encoding = 'utf8').read())
  17. print('Version : ' + version_list['beta']['r_ver'])
  18. print('DB set version : ' + version_list['beta']['c_ver'])
  19. print('Skin set version : ' + version_list['beta']['s_ver'])
  20. print('----')
  21. # Init-PIP_Install
  22. data_up_date = 1
  23. if os.path.exists(os.path.join('data', 'version.json')):
  24. data_load_ver = open(os.path.join('data', 'version.json'), encoding = 'utf8').read()
  25. if data_load_ver == version_list['beta']['r_ver']:
  26. data_up_date = 0
  27. if data_up_date == 1:
  28. with open(os.path.join('data', 'version.json'), 'w', encoding = 'utf8') as f:
  29. f.write(version_list['beta']['r_ver'])
  30. if platform.system() in ('Linux', 'Windows'):
  31. os.system(
  32. 'python' + ('3' if platform.system() != 'Windows' else '') + ' ' + \
  33. '-m pip install --upgrade --user -r requirements.txt'
  34. )
  35. print('----')
  36. try:
  37. os.execl(sys.executable, sys.executable, *sys.argv)
  38. except:
  39. pass
  40. try:
  41. os.execl(sys.executable, '"' + sys.executable + '"', *sys.argv)
  42. except:
  43. print('Error : restart failed')
  44. raise
  45. else:
  46. print('Error : automatic installation is not supported.')
  47. print('Help : try "python3 -m pip install -r requirements.txt"')
  48. else:
  49. print('PIP check pass')
  50. print('----')
  51. # Init-Load
  52. from .func_mark import *
  53. from diff_match_patch import diff_match_patch
  54. import netius.servers
  55. import waitress
  56. import werkzeug.routing
  57. import werkzeug.debug
  58. import flask
  59. import requests
  60. import pymysql
  61. if sys.version_info < (3, 6):
  62. import sha3
  63. # Init-Global
  64. global_lang = {}
  65. global_wiki_set = {}
  66. global_db_set = ''
  67. data_css_ver = '123'
  68. data_css = ''
  69. conn = ''
  70. # Func
  71. # Func-main
  72. def load_conn(data):
  73. global conn
  74. conn = data
  75. def do_db_set(db_set):
  76. global global_db_set
  77. global_db_set = db_set
  78. # Func-init
  79. class get_db_connect_old:
  80. def __init__(self, db_set):
  81. self.db_set = db_set
  82. self.conn = ''
  83. def db_load(self):
  84. if self.db_set['type'] == 'sqlite':
  85. self.conn = sqlite3.connect(
  86. self.db_set['name'] + '.db',
  87. check_same_thread = False,
  88. isolation_level = None
  89. )
  90. self.conn.execute('pragma journal_mode = wal')
  91. else:
  92. self.conn = pymysql.connect(
  93. host = self.db_set['mysql_host'],
  94. user = self.db_set['mysql_user'],
  95. password = self.db_set['mysql_pw'],
  96. charset = 'utf8mb4',
  97. port = int(self.db_set['mysql_port']),
  98. )
  99. curs = self.conn.cursor()
  100. try:
  101. curs.execute(db_change(
  102. 'create database ' + self.db_set['name'] + ' ' + \
  103. 'default character set utf8mb4;'
  104. ))
  105. except:
  106. pass
  107. self.conn.select_db(self.db_set['name'])
  108. load_conn(self.conn)
  109. return self.conn
  110. def db_get(self):
  111. # if self.db_set['type'] != 'sqlite':
  112. # self.conn.ping(reconnect = True)
  113. return self.conn
  114. class get_db_connect:
  115. # 임시 DB 커넥션 동작 구조
  116. # Init 파트
  117. # DB 커넥트(get_db_connect_old) -> func.py로 conn 넘겨줌
  118. # route 파트
  119. # DB 새로 커넥트 -> func.py에서 쓰던 conn은 conn_sub로 보관 ->
  120. # func.py로 conn 넘겨줌 -> 모든 라우터 과정이 끝나면 conn_sub를 다시 func.py에 conn으로 넘겨줌 ->
  121. # DB 커넥트 종료
  122. def __init__(self):
  123. global global_db_set
  124. global conn
  125. self.conn_sub = conn
  126. self.db_set = global_db_set
  127. def __enter__(self):
  128. if self.db_set['type'] == 'sqlite':
  129. self.conn = sqlite3.connect(
  130. self.db_set['name'] + '.db',
  131. check_same_thread = False,
  132. isolation_level = None
  133. )
  134. self.conn.execute('pragma journal_mode = wal')
  135. else:
  136. self.conn = pymysql.connect(
  137. host = self.db_set['mysql_host'],
  138. user = self.db_set['mysql_user'],
  139. password = self.db_set['mysql_pw'],
  140. charset = 'utf8mb4',
  141. port = int(self.db_set['mysql_port']),
  142. )
  143. curs = self.conn.cursor()
  144. try:
  145. curs.execute(db_change(
  146. 'create database ' + self.db_set['name'] + ' ' + \
  147. 'default character set utf8mb4;'
  148. ))
  149. except:
  150. pass
  151. self.conn.select_db(self.db_set['name'])
  152. load_conn(self.conn)
  153. return self.conn
  154. def __exit__(self, exc_type, exc_value, traceback):
  155. load_conn(self.conn_sub)
  156. self.conn.close()
  157. def update(ver_num, set_data):
  158. curs = conn.cursor()
  159. print('----')
  160. # 업데이트 하위 호환 유지 함수
  161. if ver_num < 3160027:
  162. print('Add init set')
  163. set_init()
  164. if ver_num < 3170002:
  165. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  166. if not curs.fetchall():
  167. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  168. curs.execute(db_change(
  169. "insert into html_filter (html, kind) values (?, 'extension')"
  170. ), [i])
  171. if ver_num < 3170400:
  172. curs.execute(db_change("select title, sub, code from topic where id = '1'"))
  173. for i in curs.fetchall():
  174. curs.execute(db_change(
  175. "update topic set code = ? where title = ? and sub = ?"
  176. ), [
  177. i[2],
  178. i[0],
  179. i[1]
  180. ])
  181. curs.execute(db_change(
  182. "update rd set code = ? where title = ? and sub = ?"
  183. ), [
  184. i[2],
  185. i[0],
  186. i[1]
  187. ])
  188. if ver_num < 3171800:
  189. curs.execute(db_change("select data from other where name = 'recaptcha'"))
  190. change_rec = curs.fetchall()
  191. if change_rec and change_rec[0][0] != '':
  192. new_rec = re.search(r'data-sitekey="([^"]+)"', change_rec[0][0])
  193. if new_rec:
  194. curs.execute(db_change(
  195. "update other set data = ? where name = 'recaptcha'"
  196. ), [new_rec.group(1)])
  197. else:
  198. curs.execute(db_change("update other set data = '' where name = 'recaptcha'"))
  199. curs.execute(db_change("update other set data = '' where name = 'sec_re'"))
  200. if ver_num < 3172800 and \
  201. set_data['db_type'] == 'mysql':
  202. get_data_mysql = json.loads(open('data/mysql.json', encoding = 'utf8').read())
  203. with open('data/mysql.json', 'w') as f:
  204. f.write('{ "user" : "' + get_data_mysql['user'] + '", "password" : "' + get_data_mysql['password'] + '", "host" : "localhost" }')
  205. if ver_num < 3183603:
  206. curs.execute(db_change("select block from ban where band = 'O'"))
  207. for i in curs.fetchall():
  208. curs.execute(db_change(
  209. "update ban set block = ?, band = 'regex' where block = ? and band = 'O'"
  210. ), [
  211. '^' + i[0].replace('.', '\\.'),
  212. i[0]
  213. ])
  214. curs.execute(db_change("select block from rb where band = 'O'"))
  215. for i in curs.fetchall():
  216. curs.execute(db_change(
  217. "update rb set block = ?, band = 'regex' where block = ? and band = 'O'"
  218. ), [
  219. '^' + i[0].replace('.', '\\.'),
  220. i[0]
  221. ])
  222. if ver_num < 3190201:
  223. today_time = get_time()
  224. curs.execute(db_change("select block, end, why, band, login from ban"))
  225. for i in curs.fetchall():
  226. curs.execute(db_change(
  227. "insert into rb (block, end, today, why, band, login, ongoing) " + \
  228. "values (?, ?, ?, ?, ?, ?, ?)"
  229. ), [
  230. i[0],
  231. i[1],
  232. today_time,
  233. i[2],
  234. i[3],
  235. i[4],
  236. '1'
  237. ])
  238. if ver_num < 3191301:
  239. curs.execute(db_change('' + \
  240. 'select id, title, date from history ' + \
  241. 'where not title like "user:%" ' + \
  242. 'order by date desc ' + \
  243. 'limit 50' + \
  244. ''))
  245. data_list = curs.fetchall()
  246. for get_data in data_list:
  247. curs.execute(db_change(
  248. "insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"
  249. ), [
  250. get_data[0],
  251. get_data[1],
  252. get_data[2]
  253. ])
  254. if ver_num < 3202400:
  255. curs.execute(db_change("select data from other where name = 'update'"))
  256. get_data = curs.fetchall()
  257. if get_data and get_data[0][0] == 'master':
  258. curs.execute(db_change("update other set data = 'beta' where name = 'update'"), [])
  259. if ver_num < 3202600:
  260. curs.execute(db_change("select name, regex, sub from filter"))
  261. for i in curs.fetchall():
  262. curs.execute(db_change(
  263. "insert into html_filter (html, kind, plus, plus_t) " + \
  264. "values (?, 'regex_filter', ?, ?)"
  265. ), [
  266. i[0],
  267. i[1],
  268. i[2]
  269. ])
  270. curs.execute(db_change("select title, link, icon from inter"))
  271. for i in curs.fetchall():
  272. curs.execute(db_change(
  273. "insert into html_filter (html, kind, plus, plus_t) " + \
  274. "values (?, 'inter_wiki', ?, ?)"), [
  275. i[0],
  276. i[1],
  277. i[2]
  278. ])
  279. if ver_num < 3203400:
  280. curs.execute(db_change("select user, css from custom"))
  281. for i in curs.fetchall():
  282. curs.execute(db_change(
  283. "insert into user_set (name, id, data) values ('custom_css', ?, ?)"
  284. ), [
  285. re.sub(r' \(head\)$', '', i[0]),
  286. i[1]
  287. ])
  288. if ver_num < 3205500:
  289. curs.execute(db_change("select title, decu, dis, view, why from acl"))
  290. for i in curs.fetchall():
  291. curs.execute(db_change(
  292. "insert into acl (title, data, type) values (?, ?, ?)"
  293. ), [i[0], i[1], 'decu'])
  294. curs.execute(db_change(
  295. "insert into acl (title, data, type) values (?, ?, ?)"
  296. ), [i[0], i[2], 'dis'])
  297. curs.execute(db_change(
  298. "insert into acl (title, data, type) values (?, ?, ?)"
  299. ), [i[0], i[3], 'view'])
  300. curs.execute(db_change(
  301. "insert into acl (title, data, type) values (?, ?, ?)"
  302. ), [i[0], i[4], 'why'])
  303. if ver_num < 3300101:
  304. # 캐시 초기화
  305. curs.execute(db_change('delete from cache_data'))
  306. if ver_num < 3300301:
  307. # regex_filter 오류 해결
  308. curs.execute(db_change(
  309. 'delete from html_filter where kind = "regex_filter" and html is null'
  310. ))
  311. if ver_num < 3302302:
  312. # user이랑 user_set 테이블의 통합
  313. curs.execute(db_change('select id, pw, acl, date, encode from user'))
  314. for i in curs.fetchall():
  315. curs.execute(db_change(
  316. "insert into user_set (name, id, data) values (?, ?, ?)"
  317. ), ['pw', i[0], i[1]])
  318. curs.execute(db_change(
  319. "insert into user_set (name, id, data) values (?, ?, ?)"
  320. ), ['acl', i[0], i[2]])
  321. curs.execute(db_change(
  322. "insert into user_set (name, id, data) values (?, ?, ?)"
  323. ), ['date', i[0], i[3]])
  324. curs.execute(db_change(
  325. "insert into user_set (name, id, data) values (?, ?, ?)"
  326. ), ['encode', i[0], i[4]])
  327. if ver_num < 3400101:
  328. # user_set이랑 user_application 테이블의 통합
  329. curs.execute(db_change('' + \
  330. 'select id, pw, date, encode, question, answer, ip, ua, email ' + \
  331. 'from user_application' + \
  332. ''))
  333. for i in curs.fetchall():
  334. sql_data = {}
  335. sql_data['id'] = i[0]
  336. sql_data['pw'] = i[1]
  337. sql_data['date'] = i[2]
  338. sql_data['encode'] = i[3]
  339. sql_data['question'] = i[4]
  340. sql_data['answer'] = i[5]
  341. sql_data['ip'] = i[6]
  342. sql_data['ua'] = i[7]
  343. sql_data['email'] = i[8]
  344. curs.execute(db_change(
  345. "insert into user_set (name, id, data) values (?, ?, ?)"
  346. ), ['application', i[0], json.dumps(sql_data)])
  347. conn.commit()
  348. print('Update completed')
  349. def set_init_always(ver_num):
  350. curs = conn.cursor()
  351. curs.execute(db_change('delete from other where name = "ver"'))
  352. curs.execute(db_change('insert into other (name, data) values ("ver", ?)'), [ver_num])
  353. curs.execute(db_change('delete from alist where name = "owner"'))
  354. curs.execute(db_change('insert into alist (name, acl) values ("owner", "owner")'))
  355. if not os.path.exists(load_image_url()):
  356. os.makedirs(load_image_url())
  357. conn.commit()
  358. def set_init():
  359. curs = conn.cursor()
  360. # 초기값 설정 함수
  361. curs.execute(db_change("select html from html_filter where kind = 'email'"))
  362. if not curs.fetchall():
  363. for i in ['naver.com', 'gmail.com', 'daum.net', 'kakao.com']:
  364. curs.execute(db_change(
  365. "insert into html_filter (html, kind, plus, plus_t) values (?, 'email', '', '')"
  366. ), [i])
  367. curs.execute(db_change("select html from html_filter where kind = 'extension'"))
  368. if not curs.fetchall():
  369. for i in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
  370. curs.execute(db_change(
  371. "insert into html_filter (html, kind, plus, plus_t) values (?, 'extension', '', '')"
  372. ), [i])
  373. curs.execute(db_change(
  374. 'select data from other ' + \
  375. 'where name = "smtp_server" or name = "smtp_port" or name = "smtp_security"'
  376. ))
  377. if not curs.fetchall():
  378. for i in [
  379. ['smtp_server', 'smtp.gmail.com'],
  380. ['smtp_port', '587'],
  381. ['smtp_security', 'starttls']
  382. ]:
  383. curs.execute(db_change(
  384. "insert into other (name, data) values (?, ?)"
  385. ), [i[0], i[1]])
  386. curs.execute(db_change('select data from other where name = "key"'))
  387. rep_data = curs.fetchall()
  388. if not rep_data:
  389. curs.execute(db_change('insert into other (name, data) values ("key", ?)'), [load_random_key()])
  390. curs.execute(db_change('select data from other where name = "count_all_title"'))
  391. if not curs.fetchall():
  392. curs.execute(db_change('insert into other (name, data) values ("count_all_title", "0")'))
  393. conn.commit()
  394. # Func-simple
  395. ## Func-simple-without_DB
  396. def get_default_admin_group():
  397. return ['owner', 'ban']
  398. def load_random_key(long = 128):
  399. return ''.join(
  400. random.choice(
  401. "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  402. ) for i in range(long)
  403. )
  404. def http_warning():
  405. return '''
  406. <div id="http_warning_text"></div>
  407. <script>
  408. if(window.location.protocol !== 'https:') {
  409. document.getElementById('http_warning_text').innerHTML = "''' + \
  410. load_lang('http_warning') + \
  411. '''";
  412. document.getElementById('http_warning_text').style.margin = "10px 0px 0px 0px";
  413. }
  414. </script>
  415. '''
  416. def next_fix(link, num, page, end = 50):
  417. list_data = ''
  418. if num == 1:
  419. if len(page) == end:
  420. list_data += '' + \
  421. '<hr class="main_hr">' + \
  422. '<a href="' + link + str(num + 1) + '">(' + load_lang('next') + ')</a>' + \
  423. ''
  424. elif len(page) != end:
  425. list_data += '' + \
  426. '<hr class="main_hr">' + \
  427. '<a href="' + link + str(num - 1) + '">(' + load_lang('previous') + ')</a>' + \
  428. ''
  429. else:
  430. list_data += '' + \
  431. '<hr class="main_hr">' + \
  432. '<a href="' + link + str(num - 1) + '">(' + load_lang('previous') + ')</a> <a href="' + link + str(num + 1) + '">(' + load_lang('next') + ')</a>' + \
  433. ''
  434. return list_data
  435. def leng_check(A, B):
  436. # B -> new
  437. # A -> old
  438. return '0' if A == B else (('-' + str(A - B)) if A > B else ('+' + str(B - A)))
  439. def number_check(data):
  440. try:
  441. int(data)
  442. return data
  443. except:
  444. return '1'
  445. def check_int(data):
  446. try:
  447. int(data)
  448. return data
  449. except:
  450. return ''
  451. def redirect(data = '/'):
  452. return flask.redirect(flask.request.host_url[:-1] + data)
  453. def get_acl_list(type_d = 'normal'):
  454. if type_d == 'user':
  455. return ['', 'user', 'all']
  456. else:
  457. return ['', 'all', 'user', 'admin', 'owner', '50_edit', 'email', 'ban', 'before', '30_day', 'ban_admin']
  458. ## Func-simple-with_DB
  459. def load_image_url():
  460. curs = conn.cursor()
  461. curs.execute(db_change('select data from other where name = "image_where"'))
  462. image_where = curs.fetchall()
  463. image_where = image_where[0][0] if image_where else os.path.join('data', 'images')
  464. return image_where
  465. def load_domain():
  466. curs = conn.cursor()
  467. curs.execute(db_change("select data from other where name = 'domain'"))
  468. domain = curs.fetchall()
  469. domain = domain[0][0] if domain and domain[0][0] != '' else flask.request.host_url
  470. return domain
  471. def edit_button(editor_display = '0'):
  472. curs = conn.cursor()
  473. insert_list = []
  474. curs.execute(db_change("select html, plus from html_filter where kind = 'edit_top'"))
  475. db_data = curs.fetchall()
  476. for get_data in db_data:
  477. insert_list += [[get_data[1], get_data[0]]]
  478. data = ''
  479. for insert_data in insert_list:
  480. data += '' + \
  481. '<a href="' + \
  482. 'javascript:do_insert_data(\'textarea_edit_view\', \'' + insert_data[0] + '\', ' + editor_display + ')' + \
  483. '">(' + insert_data[1] + ')</a> ' + \
  484. ''
  485. data += (' ' if data != '' else '') + '<a href="/edit_top">(' + load_lang('add') + ')</a>'
  486. data += '<hr class="main_hr">'
  487. return data
  488. def ip_warning():
  489. curs = conn.cursor()
  490. if ip_or_user() != 0:
  491. curs.execute(db_change('select data from other where name = "no_login_warning"'))
  492. data = curs.fetchall()
  493. if data and data[0][0] != '':
  494. text_data = '' + \
  495. '<span>' + data[0][0] + '</span>' + \
  496. '<hr class="main_hr">' + \
  497. ''
  498. else:
  499. text_data = '' + \
  500. '<span>' + load_lang('no_login_warning') + '</span>' + \
  501. '<hr class="main_hr">' + \
  502. ''
  503. else:
  504. text_data = ''
  505. return text_data
  506. # Func-login
  507. def pw_encode(data, type_d = ''):
  508. curs = conn.cursor()
  509. if type_d == '':
  510. curs.execute(db_change('select data from other where name = "encode"'))
  511. set_data = curs.fetchall()
  512. type_d = set_data[0][0]
  513. if type_d == 'sha256':
  514. return hashlib.sha256(bytes(data, 'utf-8')).hexdigest()
  515. else:
  516. if sys.version_info < (3, 6):
  517. return sha3.sha3_256(bytes(data, 'utf-8')).hexdigest()
  518. else:
  519. return hashlib.sha3_256(bytes(data, 'utf-8')).hexdigest()
  520. def pw_check(data, data2, type_d = 'no', id_d = ''):
  521. curs = conn.cursor()
  522. curs.execute(db_change('select data from other where name = "encode"'))
  523. db_data = curs.fetchall()
  524. if type_d != 'no':
  525. if type_d == '':
  526. set_data = 'sha3'
  527. else:
  528. set_data = type_d
  529. else:
  530. set_data = db_data[0][0]
  531. re_data = 1 if pw_encode(data, set_data) == data2 else 0
  532. if db_data[0][0] != set_data and re_data == 1 and id_d != '':
  533. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'pw'"), [
  534. pw_encode(data),
  535. id_d
  536. ])
  537. curs.execute(db_change("update user_set set data = ? where id = ? and name = 'encode'"), [
  538. db_data[0][0],
  539. id_d
  540. ])
  541. return re_data
  542. # Func-skin
  543. def easy_minify(data, tool = None):
  544. # without_DB
  545. return data
  546. def load_lang(data, safe = 0):
  547. curs = conn.cursor()
  548. global global_lang
  549. ip = ip_check()
  550. if ip_or_user(ip) == 0:
  551. curs.execute(db_change('select data from user_set where name = "lang" and id = ?'), [ip])
  552. rep_data = curs.fetchall()
  553. elif 'lang' in flask.session:
  554. rep_data = [[flask.session['lang']]]
  555. else:
  556. curs.execute(db_change("select data from other where name = 'language'"))
  557. rep_data = curs.fetchall()
  558. if not rep_data or rep_data[0][0] in ('', 'default'):
  559. curs.execute(db_change("select data from other where name = 'language'"))
  560. rep_data = curs.fetchall()
  561. if rep_data:
  562. lang_name = rep_data[0][0]
  563. else:
  564. lang_name = 'en-US'
  565. if lang_name in global_lang:
  566. lang = global_lang[lang_name]
  567. else:
  568. lang_list = os.listdir('lang')
  569. if (lang_name + '.json') in lang_list:
  570. lang = json.loads(open(
  571. os.path.join('lang', lang_name + '.json'),
  572. encoding = 'utf8'
  573. ).read())
  574. global_lang[lang_name] = lang
  575. else:
  576. lang = {}
  577. if data in lang:
  578. if safe == 1:
  579. return lang[data]
  580. else:
  581. return html.escape(lang[data])
  582. return html.escape(data + ' (' + lang_name + ')')
  583. def skin_check(set_n = 0):
  584. curs = conn.cursor()
  585. # 개편 필요?
  586. skin_list = load_skin('tenshi', 1)
  587. skin = skin_list[0]
  588. ip = ip_check()
  589. user_need_skin = ''
  590. if ip_or_user(ip) == 0:
  591. curs.execute(db_change('select data from user_set where name = "skin" and id = ?'), [ip])
  592. skin_exist = curs.fetchall()
  593. if skin_exist:
  594. user_need_skin = skin_exist[0][0]
  595. else:
  596. if 'skin' in flask.session:
  597. user_need_skin = flask.session['skin']
  598. if user_need_skin == '':
  599. curs.execute(db_change('select data from other where name = "skin"'))
  600. skin_exist = curs.fetchall()
  601. if skin_exist:
  602. user_need_skin = skin_exist[0][0]
  603. if user_need_skin != '' and user_need_skin in skin_list:
  604. skin = user_need_skin
  605. if set_n == 0:
  606. return './views/' + skin + '/index.html'
  607. else:
  608. return skin
  609. def wiki_css(data):
  610. # without_DB
  611. global data_css
  612. global data_css_ver
  613. data += ['' for _ in range(0, 3 - len(data))]
  614. if data_css == '':
  615. for i_data in os.listdir(os.path.join("views", "main_css", "css")):
  616. if i_data != 'sub':
  617. data_css += '<link rel="stylesheet" href="/views/main_css/css/' + i_data + '?ver=' + data_css_ver + '">'
  618. for i_data in os.listdir(os.path.join("views", "main_css", "js")):
  619. if i_data != 'sub':
  620. data_css += '<script src="/views/main_css/js/' + i_data + '?ver=' + data_css_ver + '"></script>'
  621. data = data[0:2] + ['', '''
  622. <link rel="stylesheet"
  623. href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.2.0/build/styles/default.min.css">
  624. <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.2.0/build/highlight.min.js"></script>
  625. <link defer rel="stylesheet"
  626. href="https://cdn.jsdelivr.net/npm/katex@0.13.2/dist/katex.min.css"
  627. integrity="sha384-Cqd8ihRLum0CCg8rz0hYKPoLZ3uw+gES2rXQXycqnL5pgVQIflxAUDS7ZSjITLb5"
  628. crossorigin="anonymous">
  629. <script src="https://cdn.jsdelivr.net/npm/katex@0.13.2/dist/katex.min.js"
  630. integrity="sha384-1Or6BdeNQb0ezrmtGeqQHFpppNd7a/gw29xeiSikBbsb44xu3uAo8c7FwbF5jhbd"
  631. crossorigin="anonymous"></script>
  632. ''' + data_css + '<script>window.addEventListener(\'DOMContentLoaded\', main_css_skin_load);</script>'] + data[2:]
  633. return data
  634. def cut_100(data):
  635. # without_DB
  636. data = re.search(r'<pre style="display: none;" id="render_content_load">([^<>]+)<\/pre>', data)
  637. if data:
  638. data = data.group(1)
  639. if len(data) > 100:
  640. return data[0:100] + '...'
  641. else:
  642. return data[0:len(data)]
  643. else:
  644. return ''
  645. def wiki_set(num = 1):
  646. curs = conn.cursor()
  647. if num == 1:
  648. skin_name = skin_check(1)
  649. data_list = []
  650. curs.execute(db_change('select data from other where name = ?'), ['name'])
  651. db_data = curs.fetchall()
  652. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else ['Wiki']
  653. curs.execute(db_change('select data from other where name = "license"'))
  654. db_data = curs.fetchall()
  655. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else ['ARR']
  656. data_list += ['', '']
  657. curs.execute(db_change('select data from other where name = "logo" and coverage = ?'), [skin_name])
  658. db_data = curs.fetchall()
  659. if db_data and db_data[0][0] != '':
  660. data_list += [db_data[0][0]]
  661. else:
  662. curs.execute(db_change('select data from other where name = "logo" and coverage = ""'))
  663. db_data = curs.fetchall()
  664. data_list += [db_data[0][0]] if db_data and db_data[0][0] != '' else [data_list[0]]
  665. head_data = ''
  666. curs.execute(db_change("select data from other where name = 'head' and coverage = ''"))
  667. db_data = curs.fetchall()
  668. head_data += db_data[0][0] if db_data and db_data[0][0] != '' else ''
  669. curs.execute(db_change("select data from other where name = 'head' and coverage = ?"), [skin_name])
  670. db_data = curs.fetchall()
  671. head_data += db_data[0][0] if db_data and db_data[0][0] != '' else ''
  672. data_list += [head_data]
  673. elif num == 2:
  674. curs.execute(db_change('select data from other where name = "frontpage"'))
  675. db_data = curs.fetchall()
  676. data_list = db_data[0][0] if db_data and db_data[0][0] != '' else 'FrontPage'
  677. elif num == 3:
  678. curs.execute(db_change('select data from other where name = "upload"'))
  679. db_data = curs.fetchall()
  680. data_list = db_data[0][0] if db_data and db_data[0][0] != '' else '2'
  681. else:
  682. data_list = ''
  683. return data_list
  684. def wiki_custom():
  685. curs = conn.cursor()
  686. ip = ip_check()
  687. if ip_or_user(ip) == 0:
  688. user_icon = 1
  689. user_name = ip
  690. curs.execute(db_change("select data from user_set where id = ? and name = 'custom_css'"), [ip])
  691. user_head = curs.fetchall()
  692. user_head = user_head[0][0] if user_head else ''
  693. curs.execute(db_change('select data from user_set where name = "email" and id = ?'), [ip])
  694. email = curs.fetchall()
  695. email = email[0][0] if email else ''
  696. if admin_check('all') == 1:
  697. user_admin = '1'
  698. user_acl_list = []
  699. curs.execute(db_change("select data from user_set where id = ? and name = 'acl'"), [ip])
  700. curs.execute(db_change('select acl from alist where name = ?'), [curs.fetchall()[0][0]])
  701. user_acl = curs.fetchall()
  702. for i in user_acl:
  703. user_acl_list += [i[0]]
  704. user_acl_list = user_acl_list if user_acl != [] else '0'
  705. else:
  706. user_admin = '0'
  707. user_acl_list = '0'
  708. curs.execute(db_change("select count(*) from alarm where name = ?"), [ip])
  709. count = curs.fetchall()
  710. user_notice = str(count[0][0]) if count else '0'
  711. else:
  712. user_icon = 0
  713. user_name = load_lang('user')
  714. email = ''
  715. user_admin = '0'
  716. user_acl_list = '0'
  717. user_notice = '0'
  718. user_head = flask.session['head'] if 'head' in flask.session else ''
  719. curs.execute(db_change("select title from rd where title = ? and stop = ''"), ['user:' + ip])
  720. user_topic = '1' if curs.fetchall() else '0'
  721. split_path = flask.request.path.split('/')
  722. if len(split_path) > 1:
  723. split_path = split_path[1]
  724. else:
  725. split_path = 0
  726. return [
  727. '',
  728. '',
  729. user_icon,
  730. user_head,
  731. email,
  732. user_name,
  733. user_admin,
  734. str(ban_check()),
  735. user_notice,
  736. user_acl_list,
  737. ip,
  738. user_topic,
  739. split_path
  740. ]
  741. def load_skin(data = '', set_n = 0, default = 0):
  742. # without_DB
  743. # data -> 가장 앞에 있을 스킨 이름
  744. # set_n == 0 -> 스트링으로 반환
  745. # set_n == 1 -> 리스트로 반환
  746. # default == 0 -> 디폴트 미포함
  747. # default == 1 -> 디폴트 포함
  748. if set_n == 0:
  749. skin_return_data = ''
  750. else:
  751. skin_return_data = []
  752. skin_list_get = os.listdir('views')
  753. if default == 1:
  754. skin_list_get = ['default'] + skin_list_get
  755. for skin_data in skin_list_get:
  756. if skin_data != 'default':
  757. see_data = skin_data
  758. else:
  759. see_data = load_lang('default')
  760. if skin_data != 'main_css':
  761. if set_n == 0:
  762. if skin_data == data:
  763. skin_return_data = '' + \
  764. '<option value="' + skin_data + '">' + \
  765. see_data + \
  766. '</option>' + \
  767. '' + skin_return_data
  768. else:
  769. skin_return_data += '' + \
  770. '<option value="' + skin_data + '">' + \
  771. see_data + \
  772. '</option>' + \
  773. ''
  774. else:
  775. if skin_data == data:
  776. skin_return_data = [skin_data] + skin_return_data
  777. else:
  778. skin_return_data += [skin_data]
  779. return skin_return_data
  780. # Func-markup
  781. def render_set(doc_name = '', doc_data = '', data_type = 'view', data_in = '', doc_acl = ''):
  782. # without_DB
  783. # data_type in ['view', 'raw', 'api_view', 'backlink']
  784. doc_acl = acl_check(doc_name, 'render') if doc_acl == '' else doc_acl
  785. doc_data = 0 if doc_data == None else doc_data
  786. if doc_acl == 1:
  787. return 'HTTP Request 401.3'
  788. else:
  789. if data_type == 'raw':
  790. return doc_data
  791. else:
  792. if doc_data != 0:
  793. get_class_render = class_do_render(conn)
  794. return get_class_render.do_render(doc_name, doc_data, data_type, data_in)
  795. else:
  796. return 'HTTP Request 404'
  797. # Func-request
  798. def send_email(who, title, data):
  799. curs = conn.cursor()
  800. try:
  801. curs.execute(db_change('' + \
  802. 'select name, data from other ' + \
  803. 'where name = "smtp_email" or name = "smtp_pass" or name = "smtp_server" or name = "smtp_port" or name = "smtp_security"' + \
  804. ''))
  805. rep_data = curs.fetchall()
  806. smtp_email = ''
  807. smtp_pass = ''
  808. smtp_server = ''
  809. smtp_security = ''
  810. smtp_port = ''
  811. smtp = ''
  812. for i in rep_data:
  813. if i[0] == 'smtp_email':
  814. smtp_email = i[1]
  815. elif i[0] == 'smtp_pass':
  816. smtp_pass = i[1]
  817. elif i[0] == 'smtp_server':
  818. smtp_server = i[1]
  819. elif i[0] == 'smtp_security':
  820. smtp_security = i[1]
  821. elif i[0] == 'smtp_port':
  822. smtp_port = i[1]
  823. smtp_port = int(smtp_port)
  824. if smtp_security == 'plain':
  825. smtp = smtplib.SMTP(smtp_server, smtp_port)
  826. elif smtp_security == 'starttls':
  827. smtp = smtplib.SMTP(smtp_server, smtp_port)
  828. smtp.starttls()
  829. else:
  830. # if smtp_security == 'tls':
  831. smtp = smtplib.SMTP_SSL(smtp_server, smtp_port)
  832. smtp.login(smtp_email, smtp_pass)
  833. domain = load_domain()
  834. wiki_name = wiki_set()[0]
  835. msg = email.mime.text.MIMEText(data)
  836. msg['Subject'] = title
  837. msg['From'] = 'openNAMU <noreply@' + domain + '>'
  838. msg['To'] = who
  839. smtp.sendmail('openNAMU@' + domain, who, msg.as_string())
  840. smtp.quit()
  841. return 1
  842. except Exception as e:
  843. print('----')
  844. print('Error : email send error')
  845. print(e)
  846. return 0
  847. def captcha_get():
  848. curs = conn.cursor()
  849. data = ''
  850. if ip_or_user() != 0:
  851. curs.execute(db_change('select data from other where name = "recaptcha"'))
  852. recaptcha = curs.fetchall()
  853. curs.execute(db_change('select data from other where name = "sec_re"'))
  854. sec_re = curs.fetchall()
  855. curs.execute(db_change('select data from other where name = "recaptcha_ver"'))
  856. rec_ver = curs.fetchall()
  857. if recaptcha and recaptcha[0][0] != '' and \
  858. sec_re and sec_re[0][0] != '':
  859. if not rec_ver or rec_ver[0][0] == '':
  860. data += '' + \
  861. '<script src="https://www.google.com/recaptcha/api.js" async defer></script>' + \
  862. '<div class="g-recaptcha" data-sitekey="' + recaptcha[0][0] + '"></div>' + \
  863. '<hr class="main_hr">' + \
  864. ''
  865. else:
  866. data += '' + \
  867. '<script src="https://www.google.com/recaptcha/api.js?render=' + recaptcha[0][0] + '"></script>' + \
  868. '<input type="hidden" id="g-recaptcha" name="g-recaptcha">' + \
  869. '<script type="text/javascript">' + \
  870. 'grecaptcha.ready(function() {' + \
  871. 'grecaptcha.execute(\'' + recaptcha[0][0] + '\', {action: \'homepage\'}).then(function(token) {' + \
  872. 'document.getElementById(\'g-recaptcha\').value = token;' + \
  873. '});' + \
  874. '});' + \
  875. '</script>' + \
  876. ''
  877. return data
  878. def captcha_post(re_data, num = 1):
  879. curs = conn.cursor()
  880. if num == 1:
  881. curs.execute(db_change('select data from other where name = "sec_re"'))
  882. sec_re = curs.fetchall()
  883. if sec_re and sec_re[0][0] != '' and \
  884. ip_or_user() != 0 and captcha_get() != '':
  885. data = requests.get(
  886. 'https://www.google.com/recaptcha/api/siteverify' + \
  887. '?secret=' + sec_re[0][0] + '&response=' + re_data
  888. )
  889. if data.status_code == 200:
  890. json_data = json.loads(data.text)
  891. if json_data['success'] != True:
  892. return 1
  893. return 0
  894. # Func-user
  895. def ip_or_user(data = ''):
  896. # without_DB
  897. # 1 == ip
  898. # 0 == reg
  899. if data == '':
  900. data = ip_check()
  901. if re.search(r'(\.|:)', data):
  902. return 1
  903. else:
  904. return 0
  905. def admin_check(num = None, what = None, name = ''):
  906. curs = conn.cursor()
  907. ip = ip_check() if name == '' else name
  908. time_data = get_time()
  909. pass_ok = 0
  910. if ip_or_user(ip) == 0:
  911. curs.execute(db_change(
  912. "select data from user_set where id = ? and name = 'acl'"
  913. ), [ip])
  914. user_auth = curs.fetchall()
  915. if user_auth:
  916. user_auth = user_auth[0][0]
  917. check = {
  918. 0 : 'owner',
  919. 1 : 'ban',
  920. 2 : 'nothing',
  921. 3 : 'toron',
  922. 4 : 'check',
  923. 5 : 'acl',
  924. 6 : 'hidel',
  925. 7 : 'give'
  926. }
  927. if not num:
  928. check = check[0]
  929. elif num == 'all':
  930. check = [check[i] for i in check]
  931. else:
  932. check = check[num]
  933. curs.execute(db_change(
  934. 'select name from alist where name = ? and acl = "owner"'
  935. ), [user_auth])
  936. if curs.fetchall():
  937. pass_ok = 1
  938. else:
  939. if num == 'all':
  940. curs.execute(db_change(
  941. 'select name from alist where name = ?'
  942. ), [user_auth])
  943. else:
  944. curs.execute(db_change(
  945. 'select name from alist where name = ? and acl = ?'
  946. ), [user_auth, check])
  947. if curs.fetchall():
  948. pass_ok = 1
  949. if pass_ok == 1:
  950. if what:
  951. curs.execute(db_change(
  952. "insert into re_admin (who, what, time) values (?, ?, ?)"
  953. ), [ip, what, time_data])
  954. conn.commit()
  955. return 1
  956. return 0
  957. def acl_check(name = 'test', tool = '', topic_num = '1'):
  958. curs = conn.cursor()
  959. ip = ip_check()
  960. get_ban = ban_check()
  961. if tool == '' and name:
  962. if tool == '' and acl_check(name, 'render') == 1:
  963. return 1
  964. user_page = re.search(r"^user:((?:(?!\/).)*)", name)
  965. if user_page:
  966. user_page = user_page.group(1)
  967. if admin_check(5) == 1:
  968. return 0
  969. if get_ban == 1:
  970. return 1
  971. curs.execute(db_change(
  972. "select data from acl where title = ? and type = 'decu'"
  973. ), [name])
  974. acl_data = curs.fetchall()
  975. if acl_data:
  976. if acl_data[0][0] == 'all':
  977. return 0
  978. elif acl_data[0][0] == 'user' and not ip_or_user(ip) == 1:
  979. return 0
  980. if ip == user_page and not ip_or_user(ip) == 1:
  981. return 0
  982. return 1
  983. elif tool == 'topic':
  984. curs.execute(db_change("select title from rd where code = ?"), [topic_num])
  985. name = curs.fetchall()
  986. name = name[0][0] if name else 'test'
  987. if tool in ['topic']:
  988. end = 3
  989. elif tool in ['render', 'vote', '']:
  990. end = 2
  991. else:
  992. end = 1
  993. for i in range(0, end):
  994. if tool == '':
  995. if i == 0:
  996. curs.execute(db_change(
  997. "select data from acl where title = ? and type = 'decu'"
  998. ), [name])
  999. '''
  1000. elif i == 1:
  1001. curs.execute(db_change(
  1002. "select plus from html_filter where kind = 'document'"
  1003. ))
  1004. '''
  1005. else:
  1006. curs.execute(db_change(
  1007. 'select data from other where name = "edit"'
  1008. ))
  1009. num = 5
  1010. elif tool == 'topic':
  1011. if i == 0:
  1012. curs.execute(db_change(
  1013. "select acl from rd where code = ?"
  1014. ), [topic_num])
  1015. elif i == 1:
  1016. curs.execute(db_change(
  1017. "select data from acl where title = ? and type = 'dis'"
  1018. ), [name])
  1019. else:
  1020. curs.execute(db_change(
  1021. 'select data from other where name = "discussion"'
  1022. ))
  1023. num = 3
  1024. elif tool == 'upload':
  1025. curs.execute(db_change(
  1026. "select data from other where name = 'upload_acl'"
  1027. ))
  1028. num = 5
  1029. elif tool == 'many_upload':
  1030. curs.execute(db_change(
  1031. "select data from other where name = 'many_upload_acl'"
  1032. ))
  1033. num = 5
  1034. elif tool == 'vote':
  1035. if i == 0:
  1036. curs.execute(db_change(
  1037. 'select acl from vote where id = ? and user = ""'
  1038. ), [topic_num])
  1039. else:
  1040. curs.execute(db_change(
  1041. 'select data from other where name = "vote_acl"'
  1042. ))
  1043. num = None
  1044. else:
  1045. # tool == 'render'
  1046. if i == 0:
  1047. curs.execute(db_change(
  1048. "select data from acl where title = ? and type = 'view'"
  1049. ), [name])
  1050. else:
  1051. curs.execute(db_change("select data from other where name = 'all_view_acl'"))
  1052. num = 5
  1053. acl_data = curs.fetchall()
  1054. if not acl_data:
  1055. acl_data = [['normal']]
  1056. elif acl_data and acl_data[0][0] == '':
  1057. acl_data = [['normal']]
  1058. if acl_data[0][0] != 'normal':
  1059. if not acl_data[0][0] in ['ban', 'ban_admin'] and get_ban == 1 and tool != 'render':
  1060. return 1
  1061. if acl_data[0][0] in ['all', 'ban']:
  1062. return 0
  1063. elif acl_data[0][0] == 'user':
  1064. if ip_or_user(ip) != 1:
  1065. return 0
  1066. elif acl_data[0][0] == 'admin':
  1067. if ip_or_user(ip) != 1:
  1068. if admin_check(num) == 1:
  1069. return 0
  1070. elif acl_data[0][0] == '50_edit':
  1071. if ip_or_user(ip) != 1:
  1072. if admin_check(num) == 1:
  1073. return 0
  1074. else:
  1075. curs.execute(db_change(
  1076. "select count(*) from history where ip = ?"
  1077. ), [ip])
  1078. count = curs.fetchall()
  1079. count = count[0][0] if count else 0
  1080. if count >= 50:
  1081. return 0
  1082. elif acl_data[0][0] == 'before':
  1083. if ip_or_user(ip) != 1:
  1084. if admin_check(num) == 1:
  1085. return 0
  1086. curs.execute(db_change(
  1087. "select ip from history where title = ? and ip = ?"
  1088. ), [name, ip])
  1089. if curs.fetchall():
  1090. return 0
  1091. elif acl_data[0][0] == '30_day':
  1092. if ip_or_user(ip) != 1:
  1093. if admin_check(num) == 1:
  1094. return 0
  1095. else:
  1096. curs.execute(db_change(
  1097. "select data from user_set where id = ? and name = 'date'"
  1098. ), [ip])
  1099. user_date = curs.fetchall()[0][0]
  1100. time_1 = datetime.datetime.strptime(
  1101. user_date,
  1102. '%Y-%m-%d %H:%M:%S'
  1103. ) + datetime.timedelta(days = 30)
  1104. time_2 = datetime.datetime.strptime(
  1105. get_time(),
  1106. '%Y-%m-%d %H:%M:%S'
  1107. )
  1108. if time_2 > time_1:
  1109. return 0
  1110. elif acl_data[0][0] == 'email':
  1111. if ip_or_user(ip) != 1:
  1112. if admin_check(num) == 1:
  1113. return 0
  1114. else:
  1115. curs.execute(db_change(
  1116. "select data from user_set where id = ? and name = 'email'"
  1117. ), [ip])
  1118. if curs.fetchall():
  1119. return 0
  1120. elif acl_data[0][0] == 'owner':
  1121. if admin_check() == 1:
  1122. return 0
  1123. elif acl_data[0][0] == 'ban_admin':
  1124. if admin_check(1) == 1 or get_ban == 1:
  1125. return 0
  1126. return 1
  1127. elif i == (end - 1):
  1128. if get_ban == 1 and tool != 'render':
  1129. return 1
  1130. if tool == 'topic':
  1131. curs.execute(db_change(
  1132. "select title from rd where code = ? and stop != ''"
  1133. ), [topic_num])
  1134. if curs.fetchall():
  1135. if admin_check(3, 'topic (code ' + topic_num + ')') == 1:
  1136. return 0
  1137. else:
  1138. return 1
  1139. else:
  1140. return 0
  1141. else:
  1142. return 0
  1143. return 1
  1144. def ban_check(ip = None, tool = ''):
  1145. curs = conn.cursor()
  1146. ip = ip_check() if not ip else ip
  1147. tool = '' if not tool else tool
  1148. if admin_check(None, None, ip) == 1:
  1149. return 0
  1150. curs.execute(db_change(
  1151. "update rb set ongoing = '' " + \
  1152. "where end < ? and end != '' and ongoing = '1'"
  1153. ), [get_time()])
  1154. conn.commit()
  1155. curs.execute(db_change("" + \
  1156. "select login, block from rb " + \
  1157. "where band = 'regex' and ongoing = '1'" + \
  1158. ""))
  1159. regex_d = curs.fetchall()
  1160. for test_r in regex_d:
  1161. g_regex = re.compile(test_r[1])
  1162. if g_regex.search(ip):
  1163. if tool == 'login':
  1164. if test_r[0] != 'O':
  1165. return 1
  1166. else:
  1167. return 1
  1168. curs.execute(db_change("" + \
  1169. "select login from rb " + \
  1170. "where block = ? and band = '' and ongoing = '1'" + \
  1171. "" + \
  1172. ""), [ip])
  1173. ban_d = curs.fetchall()
  1174. if ban_d:
  1175. if tool == 'login':
  1176. if ban_d[0][0] != 'O':
  1177. return 1
  1178. else:
  1179. return 1
  1180. return 0
  1181. def ip_pas(raw_ip, type_d = 0):
  1182. curs = conn.cursor()
  1183. hide = 0
  1184. end_ip = {}
  1185. i = 0
  1186. return_data = 0
  1187. if type(raw_ip) != type([]):
  1188. get_ip = [raw_ip]
  1189. return_data = 1
  1190. else:
  1191. get_ip = raw_ip
  1192. curs.execute(db_change("select data from other where name = 'ip_view'"))
  1193. ip_view = curs.fetchall()
  1194. ip_view = ip_view[0][0] if ip_view else ''
  1195. ip_view = '' if admin_check(1) == 1 else ip_view
  1196. get_ip = list(set(get_ip))
  1197. for raw_ip in get_ip:
  1198. change_ip = 0
  1199. is_this_ip = ip_or_user(raw_ip)
  1200. if is_this_ip != 0 and ip_view != '':
  1201. ip = re.sub(r'\.([^.]*)\.([^.]*)$', '.*.*', raw_ip)
  1202. ip = re.sub(r':([^:]*):([^:]*)$', ':*:*', ip)
  1203. change_ip = 1
  1204. else:
  1205. ip = raw_ip
  1206. if type_d == 0:
  1207. if is_this_ip == 0:
  1208. ip = '<a href="/w/' + url_pas('user:' + raw_ip) + '">' + raw_ip + '</a>'
  1209. if change_ip == 0:
  1210. ip += ' <a href="/user/' + url_pas(raw_ip) + '">(' + load_lang('tool') + ')</a>'
  1211. end_ip[raw_ip] = ip
  1212. if return_data == 1:
  1213. return end_ip[raw_ip]
  1214. else:
  1215. return end_ip
  1216. # Func-edit
  1217. def slow_edit_check():
  1218. curs = conn.cursor()
  1219. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1220. slow_edit = curs.fetchall()
  1221. if slow_edit and slow_edit != '0' and admin_check(5) != 1:
  1222. slow_edit = slow_edit[0][0]
  1223. curs.execute(db_change(
  1224. "select date from history where ip = ? order by date desc limit 1"
  1225. ), [ip_check()])
  1226. last_edit_data = curs.fetchall()
  1227. if last_edit_data:
  1228. last_edit_data = int(re.sub(' |:|-', '', last_edit_data[0][0]))
  1229. now_edit_data = int(
  1230. (datetime.datetime.now() - datetime.timedelta(
  1231. seconds = int(slow_edit))
  1232. ).strftime("%Y%m%d%H%M%S")
  1233. )
  1234. if last_edit_data > now_edit_data:
  1235. return 1
  1236. return 0
  1237. def edit_filter_do(data):
  1238. curs = conn.cursor()
  1239. if admin_check(1) != 1:
  1240. curs.execute(db_change(
  1241. "select plus, plus_t from html_filter where kind = 'regex_filter' and plus != ''"
  1242. ))
  1243. for data_list in curs.fetchall():
  1244. match = re.compile(data_list[0], re.I)
  1245. if match.search(data):
  1246. ban_insert(
  1247. ip_check(),
  1248. '0' if data_list[1] == 'X' else data_list[1],
  1249. 'edit filter',
  1250. None,
  1251. 'tool:edit filter'
  1252. )
  1253. return 1
  1254. return 0
  1255. # Func-insert
  1256. def add_alarm(who, context):
  1257. curs = conn.cursor()
  1258. curs.execute(db_change(
  1259. 'insert into alarm (name, data, date) values (?, ?, ?)'
  1260. ), [who, context, get_time()])
  1261. conn.commit()
  1262. def add_user(user_name, user_pw, user_email = '', user_encode = ''):
  1263. curs = conn.cursor()
  1264. if user_encode == '':
  1265. user_pw_hash = pw_encode(user_pw)
  1266. curs.execute(db_change('select data from other where name = "encode"'))
  1267. data_encode = curs.fetchall()
  1268. data_encode = data_encode[0][0]
  1269. else:
  1270. user_pw_hash = user_pw
  1271. data_encode = user_encode
  1272. curs.execute(db_change("select id from user_set limit 1"))
  1273. if not curs.fetchall():
  1274. user_auth = 'owner'
  1275. else:
  1276. user_auth = 'user'
  1277. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'pw', ?)"), [
  1278. user_name,
  1279. user_pw_hash
  1280. ])
  1281. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'acl', ?)"), [
  1282. user_name,
  1283. user_auth
  1284. ])
  1285. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'date', ?)"), [
  1286. user_name,
  1287. get_time()
  1288. ])
  1289. curs.execute(db_change("insert into user_set (id, name, data) values (?, 'encode', ?)"), [
  1290. user_name,
  1291. data_encode
  1292. ])
  1293. if user_email != '':
  1294. curs.execute(db_change("insert into user_set (name, id, data) values ('email', ?, ?)"), [
  1295. user_name,
  1296. user_email
  1297. ])
  1298. conn.commit()
  1299. def ua_plus(u_id, u_ip, u_agent, time):
  1300. curs = conn.cursor()
  1301. curs.execute(db_change("select data from other where name = 'ua_get'"))
  1302. rep_data = curs.fetchall()
  1303. if rep_data and rep_data[0][0] != '':
  1304. pass
  1305. else:
  1306. curs.execute(db_change(
  1307. "insert into ua_d (name, ip, ua, today, sub) values (?, ?, ?, ?, '')"
  1308. ), [
  1309. u_id,
  1310. u_ip,
  1311. u_agent,
  1312. time
  1313. ])
  1314. conn.commit()
  1315. def ban_insert(name, end, why, login, blocker, type_d = None):
  1316. curs = conn.cursor()
  1317. now_time = get_time()
  1318. band = type_d if type_d else ''
  1319. curs.execute(db_change(
  1320. "update rb set ongoing = '' where end < ? and end != '' and ongoing = '1'"
  1321. ), [now_time])
  1322. curs.execute(db_change("" + \
  1323. "select block from rb " + \
  1324. "where ((end > ? and end != '') or end = '') and block = ? and " + \
  1325. "band = ? and ongoing = '1'" + \
  1326. ""), [now_time, name, band])
  1327. if curs.fetchall():
  1328. curs.execute(db_change(
  1329. "insert into rb (block, end, today, blocker, why, band) values (?, ?, ?, ?, ?, ?)"
  1330. ), [
  1331. name,
  1332. 'release',
  1333. now_time,
  1334. blocker,
  1335. '',
  1336. band
  1337. ])
  1338. curs.execute(db_change(
  1339. "update rb set ongoing = '' where block = ? and band = ? and ongoing = '1'"
  1340. ), [name, band])
  1341. else:
  1342. login = 'O' if login != '' else ''
  1343. if end != '0':
  1344. end = int(number_check(end))
  1345. time = datetime.datetime.now()
  1346. plus = datetime.timedelta(seconds = end)
  1347. r_time = (time + plus).strftime("%Y-%m-%d %H:%M:%S")
  1348. else:
  1349. r_time = ''
  1350. curs.execute(db_change(
  1351. "insert into rb (block, end, today, blocker, why, band, ongoing, login) " + \
  1352. "values (?, ?, ?, ?, ?, ?, '1', ?)"
  1353. ), [
  1354. name,
  1355. r_time,
  1356. now_time,
  1357. blocker,
  1358. why,
  1359. band,
  1360. login
  1361. ])
  1362. conn.commit()
  1363. def rd_plus(topic_num, date, name = None, sub = None):
  1364. curs = conn.cursor()
  1365. curs.execute(db_change("select code from rd where code = ?"), [topic_num])
  1366. if curs.fetchall():
  1367. curs.execute(db_change("update rd set date = ? where code = ?"), [date, topic_num])
  1368. else:
  1369. curs.execute(db_change(
  1370. "insert into rd (title, sub, code, date) values (?, ?, ?, ?)"
  1371. ), [name, sub, topic_num, date])
  1372. conn.commit()
  1373. def history_plus(title, data, date, ip, send, leng, t_check = '', mode = ''):
  1374. curs = conn.cursor()
  1375. if mode == 'add':
  1376. curs.execute(db_change(
  1377. "select id from history where title = ? order by id + 0 asc limit 1"
  1378. ), [title])
  1379. id_data = curs.fetchall()
  1380. id_data = str(int(id_data[0][0]) - 1) if id_data else '0'
  1381. else:
  1382. curs.execute(db_change(
  1383. "select id from history where title = ? order by id + 0 desc limit 1"
  1384. ), [title])
  1385. id_data = curs.fetchall()
  1386. id_data = str(int(id_data[0][0]) + 1) if id_data else '1'
  1387. mode = mode if not re.search('^user:', title) else 'user'
  1388. send = re.sub(r'\(|\)|<|>', '', send)
  1389. send = send[:128] if len(send) > 128 else send
  1390. send = send + ' (' + t_check + ')' if t_check != '' else send
  1391. if mode != 'add' and mode != 'user':
  1392. curs.execute(db_change("select count(*) from rc where type = 'normal'"))
  1393. if curs.fetchall()[0][0] >= 200:
  1394. curs.execute(db_change(
  1395. "select id, title from rc where type = 'normal' order by date asc limit 1"
  1396. ))
  1397. rc_data = curs.fetchall()
  1398. if rc_data:
  1399. curs.execute(db_change(
  1400. 'delete from rc where id = ? and title = ? and type = "normal"'
  1401. ), [
  1402. rc_data[0][0],
  1403. rc_data[0][1]
  1404. ])
  1405. curs.execute(db_change(
  1406. "insert into rc (id, title, date, type) values (?, ?, ?, 'normal')"
  1407. ), [
  1408. id_data,
  1409. title,
  1410. date
  1411. ])
  1412. if mode != 'add':
  1413. curs.execute(db_change("select count(*) from rc where type = ?"), [mode])
  1414. if curs.fetchall()[0][0] >= 200:
  1415. curs.execute(db_change(
  1416. "select id, title from rc where type = ? order by date asc limit 1"
  1417. ), [mode])
  1418. rc_data = curs.fetchall()
  1419. if rc_data:
  1420. curs.execute(db_change(
  1421. 'delete from rc where id = ? and title = ? and type = ?'
  1422. ), [
  1423. rc_data[0][0],
  1424. rc_data[0][1],
  1425. mode
  1426. ])
  1427. curs.execute(db_change(
  1428. "insert into rc (id, title, date, type) values (?, ?, ?, ?)"
  1429. ), [
  1430. id_data,
  1431. title,
  1432. date,
  1433. mode
  1434. ])
  1435. curs.execute(db_change(
  1436. "insert into history (id, title, data, date, ip, send, leng, hide, type) " + \
  1437. "values (?, ?, ?, ?, ?, ?, ?, '', ?)"
  1438. ), [
  1439. id_data,
  1440. title,
  1441. data,
  1442. date,
  1443. ip,
  1444. send,
  1445. leng,
  1446. mode
  1447. ])
  1448. # Func-error
  1449. def re_error(data):
  1450. curs = conn.cursor()
  1451. conn.commit()
  1452. if data == '/ban':
  1453. if ban_check() == 1:
  1454. end = '<div id="get_user_info"></div><script>load_user_info("' + ip_check() + '");</script>'
  1455. else:
  1456. end = '<ul class="inside_ul"><li>' + load_lang('authority_error') + '</li></ul>'
  1457. return easy_minify(flask.render_template(skin_check(),
  1458. imp = [load_lang('error'), wiki_set(1), wiki_custom(), wiki_css([0, 0])],
  1459. data = '<h2>' + load_lang('error') + '</h2>' + end,
  1460. menu = 0
  1461. )), 401
  1462. else:
  1463. num = int(number_check(data.replace('/error/', '')))
  1464. if num == 1:
  1465. data = load_lang('no_login_error')
  1466. elif num == 2:
  1467. data = load_lang('no_exist_user_error')
  1468. elif num == 3:
  1469. data = load_lang('authority_error')
  1470. elif num == 4:
  1471. data = load_lang('no_admin_block_error')
  1472. elif num == 5:
  1473. data = load_lang('skin_error')
  1474. elif num == 6:
  1475. data = load_lang('same_id_exist_error')
  1476. elif num == 7:
  1477. data = load_lang('long_id_error')
  1478. elif num == 8:
  1479. data = load_lang('id_char_error') + ' <a href="/name_filter">(' + load_lang('id_filter_list') + ')</a>'
  1480. elif num == 9:
  1481. data = load_lang('file_exist_error')
  1482. elif num == 10:
  1483. data = load_lang('password_error')
  1484. elif num == 11:
  1485. data = load_lang('topic_long_error')
  1486. elif num == 12:
  1487. data = load_lang('email_error')
  1488. elif num == 13:
  1489. data = load_lang('recaptcha_error')
  1490. elif num == 14:
  1491. data = load_lang('file_extension_error') + ' <a href="/extension_filter">(' + load_lang('extension_filter_list') + ')</a>'
  1492. elif num == 15:
  1493. data = load_lang('edit_record_error')
  1494. elif num == 16:
  1495. data = load_lang('same_file_error')
  1496. elif num == 17:
  1497. data = load_lang('file_capacity_error') + wiki_set(3)
  1498. elif num == 18:
  1499. data = load_lang('email_send_error')
  1500. elif num == 19:
  1501. data = load_lang('decument_exist_error')
  1502. elif num == 20:
  1503. data = load_lang('password_diffrent_error')
  1504. elif num == 21:
  1505. data = load_lang('edit_filter_error')
  1506. elif num == 22:
  1507. data = load_lang('file_name_error')
  1508. elif num == 23:
  1509. data = load_lang('regex_error')
  1510. elif num == 24:
  1511. curs.execute(db_change("select data from other where name = 'slow_edit'"))
  1512. slow_edit = curs.fetchall()
  1513. slow_edit = '' if not slow_edit else slow_edit[0][0]
  1514. data = load_lang('fast_edit_error') + slow_edit
  1515. elif num == 25:
  1516. data = load_lang('too_many_dec_error')
  1517. elif num == 26:
  1518. data = load_lang('application_not_found')
  1519. elif num == 27:
  1520. data = load_lang("invalid_password_error")
  1521. elif num == 28:
  1522. data = load_lang('watchlist_overflow_error')
  1523. elif num == 29:
  1524. data = load_lang('copyright_disagreed')
  1525. elif num == 30:
  1526. data = load_lang('ie_wrong_callback')
  1527. elif num == 33:
  1528. data = load_lang('restart_fail_error')
  1529. elif num == 34:
  1530. data = load_lang("update_error") + ' <a href="https://github.com/opennamu/opennamu">(Github)</a>'
  1531. elif num == 35:
  1532. data = load_lang('same_email_error')
  1533. elif num == 36:
  1534. data = load_lang('input_email_error')
  1535. else:
  1536. data = '???'
  1537. if num == 5:
  1538. if flask.request.path != '/main_skin_set':
  1539. title = load_lang('skin_set')
  1540. tool = [['main_skin_set', load_lang('main_skin_set')]]
  1541. load_skin_set = ''
  1542. else:
  1543. title = load_lang('main_skin_set')
  1544. tool = [['skin_set', load_lang('skin_set')]]
  1545. load_skin_set = '<script>main_css_skin_set();</script>'
  1546. return easy_minify(flask.render_template(skin_check(),
  1547. imp = [title, wiki_set(1), wiki_custom(), wiki_css([0, 0])],
  1548. data = '' + \
  1549. '<div id="main_skin_set">' + \
  1550. '<h2>' + load_lang('error') + '</h2>' + \
  1551. '<ul class="inside_ul">' + \
  1552. '<li>' + data + ' <a href="/main_skin_set">(' + load_lang('main_skin_set') + ')</a></li>' + \
  1553. '</ul>' + \
  1554. '</div>' + \
  1555. load_skin_set,
  1556. menu = tool
  1557. ))
  1558. else:
  1559. return easy_minify(flask.render_template(skin_check(),
  1560. imp = [load_lang('error'), wiki_set(1), wiki_custom(), wiki_css([0, 0])],
  1561. data = '' + \
  1562. '<h2>' + load_lang('error') + '</h2>' + \
  1563. '<ul class="inside_ul">' + \
  1564. '<li>' + data + '</li>' + \
  1565. '</ul>' + \
  1566. '',
  1567. menu = 0
  1568. )), 400