api-functions.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. <?php /** @noinspection SqlResolve */
  2. /** @noinspection SqlResolve */
  3. /** @noinspection SqlResolve */
  4. /** @noinspection SqlResolve */
  5. /** @noinspection SyntaxError */
  6. function apiLogin()
  7. {
  8. $array = array(
  9. 'data' => array(
  10. array(
  11. 'name' => 'username',
  12. 'value' => (isset($_POST['username'])) ? $_POST['username'] : false
  13. ),
  14. array(
  15. 'name' => 'password',
  16. 'value' => (isset($_POST['password'])) ? $_POST['password'] : false
  17. ),
  18. array(
  19. 'name' => 'remember',
  20. 'value' => (isset($_POST['remember'])) ? true : false
  21. ),
  22. array(
  23. 'name' => 'oAuth',
  24. 'value' => (isset($_POST['oAuth'])) ? $_POST['oAuth'] : false
  25. ),
  26. array(
  27. 'name' => 'oAuthType',
  28. 'value' => (isset($_POST['oAuthType'])) ? $_POST['oAuthType'] : false
  29. ),
  30. array(
  31. 'name' => 'tfaCode',
  32. 'value' => (isset($_POST['tfaCode'])) ? $_POST['tfaCode'] : false
  33. ),
  34. array(
  35. 'name' => 'loginAttempts',
  36. 'value' => (isset($_POST['loginAttempts'])) ? $_POST['loginAttempts'] : false
  37. ),
  38. array(
  39. 'name' => 'output',
  40. 'value' => true
  41. ),
  42. )
  43. );
  44. return login($array);
  45. }
  46. function login($array)
  47. {
  48. // Grab username and Password from login form
  49. $username = $array['data']['username'] ?? null;
  50. $password = $array['data']['password'] ?? null;
  51. $oAuth = $array['data']['oAuth'] ?? null;
  52. $oAuthType = $array['data']['oAuthType'] ?? null;
  53. $remember = $array['data']['remember'] ?? null;
  54. $tfaCode = $array['data']['tfaCode'] ?? null;
  55. $loginAttempts = $array['data']['loginAttempts'] ?? null;
  56. $output = $array['data']['output'] ?? null;
  57. $username = (strpos($GLOBALS['authBackend'], 'emby') !== false) ? $username : strtolower($username);
  58. $days = (isset($remember)) ? $GLOBALS['rememberMeDays'] : 1;
  59. if ($loginAttempts > $GLOBALS['loginAttempts'] || isset($_COOKIE['lockout'])) {
  60. coookieSeconds('set', 'lockout', $GLOBALS['loginLockout'], $GLOBALS['loginLockout']);
  61. return 'lockout';
  62. }
  63. try {
  64. $database = new Dibi\Connection([
  65. 'driver' => 'sqlite3',
  66. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  67. ]);
  68. $authSuccess = false;
  69. $authProxy = false;
  70. if ($GLOBALS['authProxyEnabled'] && $GLOBALS['authProxyHeaderName'] !== '' && $GLOBALS['authProxyWhitelist'] !== '') {
  71. if (isset(getallheaders()[$GLOBALS['authProxyHeaderName']])) {
  72. $usernameHeader = isset(getallheaders()[$GLOBALS['authProxyHeaderName']]) ? getallheaders()[$GLOBALS['authProxyHeaderName']] : $username;
  73. writeLog('success', 'Auth Proxy Function - Starting Verification for IP: ' . userIP() . ' for request on: ' . $_SERVER['REMOTE_ADDR'] . ' against IP/Subnet: ' . $GLOBALS['authProxyWhitelist'], $usernameHeader);
  74. $whitelistRange = analyzeIP($GLOBALS['authProxyWhitelist']);
  75. $from = $whitelistRange['from'];
  76. $to = $whitelistRange['to'];
  77. $authProxy = authProxyRangeCheck($from, $to);
  78. $username = ($authProxy) ? $usernameHeader : $username;
  79. if ($authProxy) {
  80. writeLog('success', 'Auth Proxy Function - IP: ' . userIP() . ' has been verified', $usernameHeader);
  81. } else {
  82. writeLog('error', 'Auth Proxy Function - IP: ' . userIP() . ' has failed verification', $usernameHeader);
  83. }
  84. }
  85. }
  86. $function = 'plugin_auth_' . $GLOBALS['authBackend'];
  87. if (!$oAuth) {
  88. $result = $database->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE', $username, $username);
  89. $result['password'] = $result['password'] ?? '';
  90. switch ($GLOBALS['authType']) {
  91. case 'external':
  92. if (function_exists($function)) {
  93. $authSuccess = $function($username, $password);
  94. }
  95. break;
  96. /** @noinspection PhpMissingBreakStatementInspection */
  97. case 'both':
  98. if (function_exists($function)) {
  99. $authSuccess = $function($username, $password);
  100. }
  101. // no break
  102. default: // Internal
  103. if (!$authSuccess) {
  104. // perform the internal authentication step
  105. if (password_verify($password, $result['password'])) {
  106. $authSuccess = true;
  107. }
  108. }
  109. }
  110. $authSuccess = ($authProxy) ? true : $authSuccess;
  111. } else {
  112. // Has oAuth Token!
  113. switch ($oAuthType) {
  114. case 'plex':
  115. if ($GLOBALS['plexoAuth']) {
  116. $tokenInfo = checkPlexToken($oAuth);
  117. if ($tokenInfo) {
  118. $authSuccess = array(
  119. 'username' => $tokenInfo['user']['username'],
  120. 'email' => $tokenInfo['user']['email'],
  121. 'image' => $tokenInfo['user']['thumb'],
  122. 'token' => $tokenInfo['user']['authToken']
  123. );
  124. coookie('set', 'oAuth', 'true', $GLOBALS['rememberMeDays']);
  125. $authSuccess = ((!empty($GLOBALS['plexAdmin']) && strtolower($GLOBALS['plexAdmin']) == strtolower($tokenInfo['user']['username'])) || (!empty($GLOBALS['plexAdmin']) && strtolower($GLOBALS['plexAdmin']) == strtolower($tokenInfo['user']['email'])) || checkPlexUser($tokenInfo['user']['username'])) ? $authSuccess : false;
  126. }
  127. }
  128. break;
  129. default:
  130. return ($output) ? 'No oAuthType defined' : 'error';
  131. break;
  132. }
  133. $result = ($authSuccess) ? $database->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE', $authSuccess['username'], $authSuccess['email']) : '';
  134. }
  135. if ($authSuccess) {
  136. // Make sure user exists in database
  137. $userExists = false;
  138. $passwordMatches = ($oAuth || $authProxy) ? true : false;
  139. $token = (is_array($authSuccess) && isset($authSuccess['token']) ? $authSuccess['token'] : '');
  140. if ($result['username']) {
  141. $userExists = true;
  142. $username = $result['username'];
  143. if ($passwordMatches == false) {
  144. $passwordMatches = (password_verify($password, $result['password'])) ? true : false;
  145. }
  146. }
  147. if ($userExists) {
  148. //does org password need to be updated
  149. if (!$passwordMatches) {
  150. $database->query('
  151. UPDATE users SET', [
  152. 'password' => password_hash($password, PASSWORD_BCRYPT)
  153. ], '
  154. WHERE id=?', $result['id']);
  155. writeLog('success', 'Login Function - User Password updated from backend', $username);
  156. }
  157. if ($token !== '') {
  158. if ($token !== $result['plex_token']) {
  159. $database->query('
  160. UPDATE users SET', [
  161. 'plex_token' => $token
  162. ], '
  163. WHERE id=?', $result['id']);
  164. writeLog('success', 'Login Function - User Plex Token updated from backend', $username);
  165. }
  166. }
  167. // 2FA might go here
  168. if ($result['auth_service'] !== 'internal' && strpos($result['auth_service'], '::') !== false) {
  169. $tfaProceed = true;
  170. // Add check for local or not
  171. if ($GLOBALS['ignoreTFALocal'] !== false) {
  172. $tfaProceed = (isLocal()) ? false : true;
  173. }
  174. if ($tfaProceed) {
  175. $TFA = explode('::', $result['auth_service']);
  176. // Is code with login info?
  177. if ($tfaCode == '') {
  178. return '2FA';
  179. } else {
  180. if (!verify2FA($TFA[1], $tfaCode, $TFA[0])) {
  181. writeLoginLog($username, 'error');
  182. writeLog('error', 'Login Function - Wrong 2FA', $username);
  183. return '2FA-incorrect';
  184. }
  185. }
  186. }
  187. }
  188. // End 2FA
  189. // authentication passed - 1) mark active and update token
  190. $createToken = createToken($result['username'], $result['email'], $result['image'], $result['group'], $result['group_id'], $GLOBALS['organizrHash'], $days);
  191. if ($createToken) {
  192. writeLoginLog($username, 'success');
  193. writeLog('success', 'Login Function - A User has logged in', $username);
  194. $ssoUser = ((empty($result['email'])) ? $result['username'] : (strpos($result['email'], 'placeholder') !== false)) ? $result['username'] : $result['email'];
  195. ssoCheck($ssoUser, $password, $token); //need to work on this
  196. return ($output) ? array('name' => $GLOBALS['cookieName'], 'token' => (string)$createToken) : true;
  197. } else {
  198. return 'Token Creation Error';
  199. }
  200. } else {
  201. // Create User
  202. //ssoCheck($username, $password, $token);
  203. return authRegister((is_array($authSuccess) && isset($authSuccess['username']) ? $authSuccess['username'] : $username), $password, defaultUserGroup(), (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $token);
  204. }
  205. } else {
  206. // authentication failed
  207. writeLoginLog($username, 'error');
  208. writeLog('error', 'Login Function - Wrong Password', $username);
  209. if ($loginAttempts >= $GLOBALS['loginAttempts']) {
  210. coookieSeconds('set', 'lockout', $GLOBALS['loginLockout'], $GLOBALS['loginLockout']);
  211. return 'lockout';
  212. } else {
  213. return 'mismatch';
  214. }
  215. }
  216. } catch (Dibi\Exception $e) {
  217. return $e;
  218. }
  219. }
  220. function createDB($path, $filename)
  221. {
  222. try {
  223. if (!file_exists($path)) {
  224. mkdir($path, 0777, true);
  225. }
  226. $createDB = new Dibi\Connection([
  227. 'driver' => 'sqlite3',
  228. 'database' => $path . $filename,
  229. ]);
  230. // Create Users
  231. $createDB->query('CREATE TABLE `users` (
  232. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  233. `username` TEXT UNIQUE,
  234. `password` TEXT,
  235. `email` TEXT,
  236. `plex_token` TEXT,
  237. `group` TEXT,
  238. `group_id` INTEGER,
  239. `locked` INTEGER,
  240. `image` TEXT,
  241. `register_date` DATE,
  242. `auth_service` TEXT DEFAULT \'internal\'
  243. );');
  244. // Create Tokens
  245. $createDB->query('CREATE TABLE `chatroom` (
  246. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  247. `username` TEXT,
  248. `gravatar` TEXT,
  249. `uid` TEXT,
  250. `date` DATE,
  251. `ip` TEXT,
  252. `message` TEXT
  253. );');
  254. $createDB->query('CREATE TABLE `tokens` (
  255. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  256. `token` TEXT UNIQUE,
  257. `user_id` INTEGER,
  258. `browser` TEXT,
  259. `ip` TEXT,
  260. `created` DATE,
  261. `expires` DATE
  262. );');
  263. $createDB->query('CREATE TABLE `groups` (
  264. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  265. `group` TEXT UNIQUE,
  266. `group_id` INTEGER,
  267. `image` TEXT,
  268. `default` INTEGER
  269. );');
  270. $createDB->query('CREATE TABLE `categories` (
  271. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  272. `order` INTEGER,
  273. `category` TEXT UNIQUE,
  274. `category_id` INTEGER,
  275. `image` TEXT,
  276. `default` INTEGER
  277. );');
  278. // Create Tabs
  279. $createDB->query('CREATE TABLE `tabs` (
  280. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  281. `order` INTEGER,
  282. `category_id` INTEGER,
  283. `name` TEXT,
  284. `url` TEXT,
  285. `url_local` TEXT,
  286. `default` INTEGER,
  287. `enabled` INTEGER,
  288. `group_id` INTEGER,
  289. `image` TEXT,
  290. `type` INTEGER,
  291. `splash` INTEGER,
  292. `ping` INTEGER,
  293. `ping_url` TEXT,
  294. `timeout` INTEGER,
  295. `timeout_ms` INTEGER,
  296. `preload` INTEGER
  297. );');
  298. // Create Options
  299. $createDB->query('CREATE TABLE `options` (
  300. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  301. `name` TEXT UNIQUE,
  302. `value` TEXT
  303. );');
  304. // Create Invites
  305. $createDB->query('CREATE TABLE `invites` (
  306. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  307. `code` TEXT UNIQUE,
  308. `date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  309. `email` TEXT,
  310. `username` TEXT,
  311. `dateused` TIMESTAMP,
  312. `usedby` TEXT,
  313. `ip` TEXT,
  314. `valid` TEXT,
  315. `type` TEXT
  316. );');
  317. return true;
  318. } catch (Dibi\Exception $e) {
  319. return false;
  320. }
  321. }
  322. // Upgrade Database
  323. function updateDB($oldVerNum = false)
  324. {
  325. $tempLock = $GLOBALS['dbLocation'] . 'DBLOCK.txt';
  326. if (!file_exists($tempLock)) {
  327. touch($tempLock);
  328. // Create Temp DB First
  329. $migrationDB = 'tempMigration.db';
  330. $pathDigest = pathinfo($GLOBALS['dbLocation'] . $GLOBALS['dbName']);
  331. if (file_exists($GLOBALS['dbLocation'] . $migrationDB)) {
  332. unlink($GLOBALS['dbLocation'] . $migrationDB);
  333. }
  334. $backupDB = $pathDigest['dirname'] . '/' . $pathDigest['filename'] . '[' . date('Y-m-d_H-i-s') . ']' . ($oldVerNum ? '[' . $oldVerNum . ']' : '') . '.bak.db';
  335. copy($GLOBALS['dbLocation'] . $GLOBALS['dbName'], $backupDB);
  336. $success = createDB($GLOBALS['dbLocation'], $migrationDB);
  337. if ($success) {
  338. try {
  339. $connectOldDB = new Dibi\Connection([
  340. 'driver' => 'sqlite3',
  341. 'database' => $backupDB,
  342. ]);
  343. $connectNewDB = new Dibi\Connection([
  344. 'driver' => 'sqlite3',
  345. 'database' => $GLOBALS['dbLocation'] . $migrationDB,
  346. ]);
  347. $tables = $connectOldDB->fetchAll('SELECT name FROM sqlite_master WHERE type="table"');
  348. foreach ($tables as $table) {
  349. $data = $connectOldDB->fetchAll('SELECT * FROM ' . $table['name']);
  350. writeLog('success', 'Update Function - Grabbed Table data for Table: ' . $table['name'], 'Database');
  351. foreach ($data as $row) {
  352. $connectNewDB->query('INSERT into ' . $table['name'], $row);
  353. }
  354. writeLog('success', 'Update Function - Wrote Table data for Table: ' . $table['name'], 'Database');
  355. }
  356. writeLog('success', 'Update Function - All Table data converted - Starting Movement', 'Database');
  357. $connectOldDB->disconnect();
  358. $connectNewDB->disconnect();
  359. // Remove Current Database
  360. if (file_exists($GLOBALS['dbLocation'] . $migrationDB)) {
  361. $oldFileSize = filesize($GLOBALS['dbLocation'] . $GLOBALS['dbName']);
  362. $newFileSize = filesize($GLOBALS['dbLocation'] . $migrationDB);
  363. if ($newFileSize > 0) {
  364. writeLog('success', 'Update Function - Table Size of new DB ok..', 'Database');
  365. @unlink($GLOBALS['dbLocation'] . $GLOBALS['dbName']);
  366. copy($GLOBALS['dbLocation'] . $migrationDB, $GLOBALS['dbLocation'] . $GLOBALS['dbName']);
  367. @unlink($GLOBALS['dbLocation'] . $migrationDB);
  368. writeLog('success', 'Update Function - Migrated Old Info to new Database', 'Database');
  369. @unlink($tempLock);
  370. return true;
  371. }
  372. }
  373. @unlink($tempLock);
  374. return false;
  375. } catch (Dibi\Exception $e) {
  376. writeLog('error', 'Update Function - Error [' . $e . ']', 'Database');
  377. @unlink($tempLock);
  378. return false;
  379. }
  380. }
  381. @unlink($tempLock);
  382. return false;
  383. }
  384. return false;
  385. }
  386. function createFirstAdmin($path, $filename, $username, $password, $email)
  387. {
  388. try {
  389. $createDB = new Dibi\Connection([
  390. 'driver' => 'sqlite3',
  391. 'database' => $path . $filename,
  392. ]);
  393. $userInfo = [
  394. 'username' => $username,
  395. 'password' => password_hash($password, PASSWORD_BCRYPT),
  396. 'email' => $email,
  397. 'group' => 'Admin',
  398. 'group_id' => 0,
  399. 'image' => gravatar($email),
  400. 'register_date' => $GLOBALS['currentTime'],
  401. ];
  402. $groupInfo0 = [
  403. 'group' => 'Admin',
  404. 'group_id' => 0,
  405. 'default' => false,
  406. 'image' => 'plugins/images/groups/admin.png',
  407. ];
  408. $groupInfo1 = [
  409. 'group' => 'Co-Admin',
  410. 'group_id' => 1,
  411. 'default' => false,
  412. 'image' => 'plugins/images/groups/coadmin.png',
  413. ];
  414. $groupInfo2 = [
  415. 'group' => 'Super User',
  416. 'group_id' => 2,
  417. 'default' => false,
  418. 'image' => 'plugins/images/groups/superuser.png',
  419. ];
  420. $groupInfo3 = [
  421. 'group' => 'Power User',
  422. 'group_id' => 3,
  423. 'default' => false,
  424. 'image' => 'plugins/images/groups/poweruser.png',
  425. ];
  426. $groupInfo4 = [
  427. 'group' => 'User',
  428. 'group_id' => 4,
  429. 'default' => true,
  430. 'image' => 'plugins/images/groups/user.png',
  431. ];
  432. $groupInfoGuest = [
  433. 'group' => 'Guest',
  434. 'group_id' => 999,
  435. 'default' => false,
  436. 'image' => 'plugins/images/groups/guest.png',
  437. ];
  438. $settingsInfo = [
  439. 'order' => 1,
  440. 'category_id' => 0,
  441. 'name' => 'Settings',
  442. 'url' => 'api/?v1/settings/page',
  443. 'default' => false,
  444. 'enabled' => true,
  445. 'group_id' => 1,
  446. 'image' => 'fontawesome::cog',
  447. 'type' => 0
  448. ];
  449. $homepageInfo = [
  450. 'order' => 2,
  451. 'category_id' => 0,
  452. 'name' => 'Homepage',
  453. 'url' => 'api/?v1/homepage/page',
  454. 'default' => false,
  455. 'enabled' => false,
  456. 'group_id' => 4,
  457. 'image' => 'fontawesome::home',
  458. 'type' => 0
  459. ];
  460. $unsortedInfo = [
  461. 'order' => 1,
  462. 'category' => 'Unsorted',
  463. 'category_id' => 0,
  464. 'image' => 'plugins/images/categories/unsorted.png',
  465. 'default' => true
  466. ];
  467. $createDB->query('INSERT INTO [users]', $userInfo);
  468. $createDB->query('INSERT INTO [groups]', $groupInfo0);
  469. $createDB->query('INSERT INTO [groups]', $groupInfo1);
  470. $createDB->query('INSERT INTO [groups]', $groupInfo2);
  471. $createDB->query('INSERT INTO [groups]', $groupInfo3);
  472. $createDB->query('INSERT INTO [groups]', $groupInfo4);
  473. $createDB->query('INSERT INTO [groups]', $groupInfoGuest);
  474. $createDB->query('INSERT INTO [tabs]', $settingsInfo);
  475. $createDB->query('INSERT INTO [tabs]', $homepageInfo);
  476. $createDB->query('INSERT INTO [categories]', $unsortedInfo);
  477. return true;
  478. } catch (Dibi\Exception $e) {
  479. writeLog('error', 'Wizard Function - Error [' . $e . ']', 'Wizard');
  480. return false;
  481. }
  482. }
  483. function defaultUserGroup()
  484. {
  485. try {
  486. $connect = new Dibi\Connection([
  487. 'driver' => 'sqlite3',
  488. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  489. ]);
  490. $all = $connect->fetch('SELECT * FROM groups WHERE `default` = 1');
  491. return $all;
  492. } catch (Dibi\Exception $e) {
  493. return false;
  494. }
  495. }
  496. function defaultTabCategory()
  497. {
  498. try {
  499. $connect = new Dibi\Connection([
  500. 'driver' => 'sqlite3',
  501. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  502. ]);
  503. $all = $connect->fetch('SELECT * FROM categories WHERE `default` = 1');
  504. return $all;
  505. } catch (Dibi\Exception $e) {
  506. return false;
  507. }
  508. }
  509. function getGuest()
  510. {
  511. if (isset($GLOBALS['dbLocation'])) {
  512. try {
  513. $connect = new Dibi\Connection([
  514. 'driver' => 'sqlite3',
  515. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  516. ]);
  517. $all = $connect->fetch('SELECT * FROM groups WHERE `group_id` = 999');
  518. return $all;
  519. } catch (Dibi\Exception $e) {
  520. return false;
  521. }
  522. } else {
  523. return array(
  524. 'group' => 'Guest',
  525. 'group_id' => 999,
  526. 'image' => 'plugins/images/groups/guest.png'
  527. );
  528. }
  529. }
  530. function adminEditGroup($array)
  531. {
  532. switch ($array['data']['action']) {
  533. case 'changeDefaultGroup':
  534. try {
  535. $connect = new Dibi\Connection([
  536. 'driver' => 'sqlite3',
  537. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  538. ]);
  539. $connect->query('UPDATE groups SET `default` = 0');
  540. $connect->query('
  541. UPDATE groups SET', [
  542. 'default' => 1
  543. ], '
  544. WHERE id=?', $array['data']['id']);
  545. writeLog('success', 'Group Management Function - Changed Default Group from [' . $array['data']['oldGroupName'] . '] to [' . $array['data']['newGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  546. return true;
  547. } catch (Dibi\Exception $e) {
  548. return false;
  549. }
  550. break;
  551. case 'deleteUserGroup':
  552. try {
  553. $connect = new Dibi\Connection([
  554. 'driver' => 'sqlite3',
  555. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  556. ]);
  557. $connect->query('DELETE FROM groups WHERE id = ?', $array['data']['id']);
  558. writeLog('success', 'Group Management Function - Deleted Group [' . $array['data']['groupName'] . ']', $GLOBALS['organizrUser']['username']);
  559. return true;
  560. } catch (Dibi\Exception $e) {
  561. return false;
  562. }
  563. break;
  564. case 'addUserGroup':
  565. try {
  566. $connect = new Dibi\Connection([
  567. 'driver' => 'sqlite3',
  568. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  569. ]);
  570. $newGroup = [
  571. 'group' => $array['data']['newGroupName'],
  572. 'group_id' => $array['data']['newGroupID'],
  573. 'default' => false,
  574. 'image' => $array['data']['newGroupImage'],
  575. ];
  576. $connect->query('INSERT INTO [groups]', $newGroup);
  577. writeLog('success', 'Group Management Function - Added Group [' . $array['data']['newGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  578. return true;
  579. } catch (Dibi\Exception $e) {
  580. return false;
  581. }
  582. break;
  583. case 'editUserGroup':
  584. try {
  585. $connect = new Dibi\Connection([
  586. 'driver' => 'sqlite3',
  587. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  588. ]);
  589. $connect->query('
  590. UPDATE groups SET', [
  591. 'group' => $array['data']['groupName'],
  592. 'image' => $array['data']['groupImage'],
  593. ], '
  594. WHERE id=?', $array['data']['id']);
  595. writeLog('success', 'Group Management Function - Edited Group Info for [' . $array['data']['oldGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  596. return true;
  597. } catch (Dibi\Exception $e) {
  598. return false;
  599. }
  600. break;
  601. default:
  602. return false;
  603. break;
  604. }
  605. }
  606. function adminEditUser($array)
  607. {
  608. switch ($array['data']['action']) {
  609. case 'changeGroup':
  610. if ($array['data']['newGroupID'] == 0) {
  611. return false;
  612. }
  613. try {
  614. $connect = new Dibi\Connection([
  615. 'driver' => 'sqlite3',
  616. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  617. ]);
  618. $connect->query('
  619. UPDATE users SET', [
  620. 'group' => $array['data']['newGroupName'],
  621. 'group_id' => $array['data']['newGroupID'],
  622. ], '
  623. WHERE id=?', $array['data']['id']);
  624. writeLog('success', 'User Management Function - User: ' . $array['data']['username'] . '\'s group was changed from [' . $array['data']['oldGroup'] . '] to [' . $array['data']['newGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  625. return true;
  626. } catch (Dibi\Exception $e) {
  627. writeLog('error', 'User Management Function - Error - User: ' . $array['data']['username'] . '\'s group was changed from [' . $array['data']['oldGroup'] . '] to [' . $array['data']['newGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  628. return false;
  629. }
  630. break;
  631. case 'editUser':
  632. try {
  633. $connect = new Dibi\Connection([
  634. 'driver' => 'sqlite3',
  635. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  636. ]);
  637. if (!usernameTakenExcept($array['data']['username'], $array['data']['email'], $array['data']['id'])) {
  638. $connect->query('
  639. UPDATE users SET', [
  640. 'username' => $array['data']['username'],
  641. 'email' => $array['data']['email'],
  642. 'image' => gravatar($array['data']['email']),
  643. ], '
  644. WHERE id=?', $array['data']['id']);
  645. if (!empty($array['data']['password'])) {
  646. $connect->query('
  647. UPDATE users SET', [
  648. 'password' => password_hash($array['data']['password'], PASSWORD_BCRYPT)
  649. ], '
  650. WHERE id=?', $array['data']['id']);
  651. }
  652. writeLog('success', 'User Management Function - User: ' . $array['data']['username'] . '\'s info was changed', $GLOBALS['organizrUser']['username']);
  653. return true;
  654. } else {
  655. return false;
  656. }
  657. } catch (Dibi\Exception $e) {
  658. writeLog('error', 'User Management Function - Error - User: ' . $array['data']['username'] . '\'s group was changed from [' . $array['data']['oldGroup'] . '] to [' . $array['data']['newGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  659. return false;
  660. }
  661. break;
  662. case 'addNewUser':
  663. $defaults = defaultUserGroup();
  664. if (createUser($array['data']['username'], $array['data']['password'], $defaults, $array['data']['email'])) {
  665. writeLog('success', 'Create User Function - Account created for [' . $array['data']['username'] . ']', $GLOBALS['organizrUser']['username']);
  666. return true;
  667. } else {
  668. writeLog('error', 'Registration Function - An error occurred', $GLOBALS['organizrUser']['username']);
  669. return 'username taken';
  670. }
  671. break;
  672. case 'deleteUser':
  673. try {
  674. $connect = new Dibi\Connection([
  675. 'driver' => 'sqlite3',
  676. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  677. ]);
  678. $connect->query('DELETE FROM users WHERE id = ?', $array['data']['id']);
  679. writeLog('success', 'User Management Function - Deleted User [' . $array['data']['username'] . ']', $GLOBALS['organizrUser']['username']);
  680. return true;
  681. } catch (Dibi\Exception $e) {
  682. return false;
  683. }
  684. break;
  685. default:
  686. return false;
  687. break;
  688. }
  689. }
  690. function editTabs($array)
  691. {
  692. switch ($array['data']['action']) {
  693. case 'changeGroup':
  694. try {
  695. $connect = new Dibi\Connection([
  696. 'driver' => 'sqlite3',
  697. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  698. ]);
  699. $connect->query('
  700. UPDATE tabs SET', [
  701. 'group_id' => $array['data']['newGroupID'],
  702. ], '
  703. WHERE id=?', $array['data']['id']);
  704. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s group was changed to [' . $array['data']['newGroupName'] . ']', $GLOBALS['organizrUser']['username']);
  705. return true;
  706. } catch (Dibi\Exception $e) {
  707. return false;
  708. }
  709. break;
  710. case 'changeCategory':
  711. try {
  712. $connect = new Dibi\Connection([
  713. 'driver' => 'sqlite3',
  714. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  715. ]);
  716. $connect->query('
  717. UPDATE tabs SET', [
  718. 'category_id' => $array['data']['newCategoryID'],
  719. ], '
  720. WHERE id=?', $array['data']['id']);
  721. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s category was changed to [' . $array['data']['newCategoryName'] . ']', $GLOBALS['organizrUser']['username']);
  722. return true;
  723. } catch (Dibi\Exception $e) {
  724. return false;
  725. }
  726. break;
  727. case 'changeType':
  728. try {
  729. $connect = new Dibi\Connection([
  730. 'driver' => 'sqlite3',
  731. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  732. ]);
  733. $connect->query('
  734. UPDATE tabs SET', [
  735. 'type' => $array['data']['newTypeID'],
  736. ], '
  737. WHERE id=?', $array['data']['id']);
  738. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s type was changed to [' . $array['data']['newTypeName'] . ']', $GLOBALS['organizrUser']['username']);
  739. return true;
  740. } catch (Dibi\Exception $e) {
  741. return false;
  742. }
  743. break;
  744. case 'changeEnabled':
  745. try {
  746. $connect = new Dibi\Connection([
  747. 'driver' => 'sqlite3',
  748. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  749. ]);
  750. $connect->query('
  751. UPDATE tabs SET', [
  752. 'enabled' => $array['data']['tabEnabled'],
  753. ], '
  754. WHERE id=?', $array['data']['id']);
  755. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s enable status was changed to [' . $array['data']['tabEnabledWord'] . ']', $GLOBALS['organizrUser']['username']);
  756. return true;
  757. } catch (Dibi\Exception $e) {
  758. return false;
  759. }
  760. break;
  761. case 'changeSplash':
  762. try {
  763. $connect = new Dibi\Connection([
  764. 'driver' => 'sqlite3',
  765. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  766. ]);
  767. $connect->query('
  768. UPDATE tabs SET', [
  769. 'splash' => $array['data']['tabSplash'],
  770. ], '
  771. WHERE id=?', $array['data']['id']);
  772. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s splash status was changed to [' . $array['data']['tabSplashWord'] . ']', $GLOBALS['organizrUser']['username']);
  773. return true;
  774. } catch (Dibi\Exception $e) {
  775. return false;
  776. }
  777. break;
  778. case 'changePing':
  779. try {
  780. $connect = new Dibi\Connection([
  781. 'driver' => 'sqlite3',
  782. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  783. ]);
  784. $connect->query('
  785. UPDATE tabs SET', [
  786. 'ping' => $array['data']['tabPing'],
  787. ], '
  788. WHERE id=?', $array['data']['id']);
  789. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s ping status was changed to [' . $array['data']['tabPingWord'] . ']', $GLOBALS['organizrUser']['username']);
  790. return true;
  791. } catch (Dibi\Exception $e) {
  792. return false;
  793. }
  794. break;
  795. case 'changePreload':
  796. try {
  797. $connect = new Dibi\Connection([
  798. 'driver' => 'sqlite3',
  799. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  800. ]);
  801. $connect->query('
  802. UPDATE tabs SET', [
  803. 'preload' => $array['data']['tabPreload'],
  804. ], '
  805. WHERE id=?', $array['data']['id']);
  806. writeLog('success', 'Tab Editor Function - Tab: ' . $array['data']['tab'] . '\'s preload status was changed to [' . $array['data']['tabPreloadWord'] . ']', $GLOBALS['organizrUser']['username']);
  807. return true;
  808. } catch (Dibi\Exception $e) {
  809. return false;
  810. }
  811. break;
  812. case 'changeDefault':
  813. try {
  814. $connect = new Dibi\Connection([
  815. 'driver' => 'sqlite3',
  816. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  817. ]);
  818. $connect->query('UPDATE tabs SET `default` = 0');
  819. $connect->query('
  820. UPDATE tabs SET', [
  821. 'default' => 1
  822. ], '
  823. WHERE id=?', $array['data']['id']);
  824. writeLog('success', 'Tab Editor Function - Changed Default Tab to [' . $array['data']['tab'] . ']', $GLOBALS['organizrUser']['username']);
  825. return true;
  826. } catch (Dibi\Exception $e) {
  827. return false;
  828. }
  829. break;
  830. case 'deleteTab':
  831. try {
  832. $connect = new Dibi\Connection([
  833. 'driver' => 'sqlite3',
  834. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  835. ]);
  836. $connect->query('DELETE FROM tabs WHERE id = ?', $array['data']['id']);
  837. writeLog('success', 'Tab Editor Function - Deleted Tab [' . $array['data']['tab'] . ']', $GLOBALS['organizrUser']['username']);
  838. return true;
  839. } catch (Dibi\Exception $e) {
  840. return false;
  841. }
  842. break;
  843. case 'editTab':
  844. try {
  845. $connect = new Dibi\Connection([
  846. 'driver' => 'sqlite3',
  847. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  848. ]);
  849. $connect->query('
  850. UPDATE tabs SET', [
  851. 'name' => $array['data']['tabName'],
  852. 'url' => $array['data']['tabURL'],
  853. 'url_local' => $array['data']['tabLocalURL'],
  854. 'ping_url' => $array['data']['pingURL'],
  855. 'image' => $array['data']['tabImage'],
  856. 'timeout' => $array['data']['tabActionType'],
  857. 'timeout_ms' => $array['data']['tabActionTime'],
  858. ], '
  859. WHERE id=?', $array['data']['id']);
  860. writeLog('success', 'Tab Editor Function - Edited Tab Info for [' . $array['data']['tabName'] . ']', $GLOBALS['organizrUser']['username']);
  861. return true;
  862. } catch (Dibi\Exception $e) {
  863. return false;
  864. }
  865. case 'changeOrder':
  866. try {
  867. $connect = new Dibi\Connection([
  868. 'driver' => 'sqlite3',
  869. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  870. ]);
  871. foreach ($array['data']['tabs']['tab'] as $key => $value) {
  872. if ($value['order'] != $value['originalOrder']) {
  873. $connect->query('
  874. UPDATE tabs SET', [
  875. 'order' => $value['order'],
  876. ], '
  877. WHERE id=?', $value['id']);
  878. writeLog('success', 'Tab Editor Function - ' . $value['name'] . ' Order Changed From ' . $value['order'] . ' to ' . $value['originalOrder'], $GLOBALS['organizrUser']['username']);
  879. }
  880. }
  881. writeLog('success', 'Tab Editor Function - Tab Order Changed', $GLOBALS['organizrUser']['username']);
  882. return true;
  883. } catch (Dibi\Exception $e) {
  884. return false;
  885. }
  886. break;
  887. case 'addNewTab':
  888. try {
  889. $default = defaultTabCategory()['category_id'];
  890. $connect = new Dibi\Connection([
  891. 'driver' => 'sqlite3',
  892. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  893. ]);
  894. $newTab = [
  895. 'order' => $array['data']['tabOrder'],
  896. 'category_id' => $default,
  897. 'name' => $array['data']['tabName'],
  898. 'url' => $array['data']['tabURL'],
  899. 'url_local' => $array['data']['tabLocalURL'],
  900. 'ping_url' => $array['data']['pingURL'],
  901. 'default' => $array['data']['tabDefault'],
  902. 'enabled' => 1,
  903. 'group_id' => $array['data']['tabGroupID'],
  904. 'image' => $array['data']['tabImage'],
  905. 'type' => $array['data']['tabType'],
  906. 'timeout' => $array['data']['tabActionType'],
  907. 'timeout_ms' => $array['data']['tabActionTime'],
  908. ];
  909. $connect->query('INSERT INTO [tabs]', $newTab);
  910. writeLog('success', 'Tab Editor Function - Created Tab for: ' . $array['data']['tabName'], $GLOBALS['organizrUser']['username']);
  911. return true;
  912. } catch (Dibi\Exception $e) {
  913. return false;
  914. }
  915. break;
  916. default:
  917. return false;
  918. break;
  919. }
  920. }
  921. function editCategories($array)
  922. {
  923. switch ($array['data']['action']) {
  924. case 'changeDefault':
  925. try {
  926. $connect = new Dibi\Connection([
  927. 'driver' => 'sqlite3',
  928. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  929. ]);
  930. $connect->query('UPDATE categories SET `default` = 0');
  931. $connect->query('
  932. UPDATE categories SET', [
  933. 'default' => 1
  934. ], '
  935. WHERE id=?', $array['data']['id']);
  936. writeLog('success', 'Category Editor Function - Changed Default Category from [' . $array['data']['oldCategoryName'] . '] to [' . $array['data']['newCategoryName'] . ']', $GLOBALS['organizrUser']['username']);
  937. return true;
  938. } catch (Dibi\Exception $e) {
  939. return false;
  940. }
  941. break;
  942. case 'deleteCategory':
  943. try {
  944. $connect = new Dibi\Connection([
  945. 'driver' => 'sqlite3',
  946. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  947. ]);
  948. $connect->query('DELETE FROM categories WHERE id = ?', $array['data']['id']);
  949. writeLog('success', 'Category Editor Function - Deleted Category [' . $array['data']['category'] . ']', $GLOBALS['organizrUser']['username']);
  950. return true;
  951. } catch (Dibi\Exception $e) {
  952. return false;
  953. }
  954. break;
  955. case 'addNewCategory':
  956. try {
  957. $connect = new Dibi\Connection([
  958. 'driver' => 'sqlite3',
  959. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  960. ]);
  961. $newCategory = [
  962. 'category' => $array['data']['categoryName'],
  963. 'order' => $array['data']['categoryOrder'],
  964. 'category_id' => $array['data']['categoryID'],
  965. 'default' => false,
  966. 'image' => $array['data']['categoryImage'],
  967. ];
  968. $connect->query('INSERT INTO [categories]', $newCategory);
  969. writeLog('success', 'Category Editor Function - Added Category [' . $array['data']['categoryName'] . ']', $GLOBALS['organizrUser']['username']);
  970. return true;
  971. } catch (Dibi\Exception $e) {
  972. return $e;
  973. }
  974. break;
  975. case 'editCategory':
  976. try {
  977. $connect = new Dibi\Connection([
  978. 'driver' => 'sqlite3',
  979. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  980. ]);
  981. $connect->query('
  982. UPDATE categories SET', [
  983. 'category' => $array['data']['name'],
  984. 'image' => $array['data']['image'],
  985. ], '
  986. WHERE id=?', $array['data']['id']);
  987. writeLog('success', 'Category Editor Function - Edited Category Info for [' . $array['data']['name'] . ']', $GLOBALS['organizrUser']['username']);
  988. return true;
  989. } catch (Dibi\Exception $e) {
  990. return false;
  991. }
  992. break;
  993. case 'changeOrder':
  994. try {
  995. $connect = new Dibi\Connection([
  996. 'driver' => 'sqlite3',
  997. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  998. ]);
  999. foreach ($array['data']['categories']['category'] as $key => $value) {
  1000. if ($value['order'] != $value['originalOrder']) {
  1001. $connect->query('
  1002. UPDATE categories SET', [
  1003. 'order' => $value['order'],
  1004. ], '
  1005. WHERE id=?', $value['id']);
  1006. writeLog('success', 'Category Editor Function - ' . $value['name'] . ' Order Changed From ' . $value['order'] . ' to ' . $value['originalOrder'], $GLOBALS['organizrUser']['username']);
  1007. }
  1008. }
  1009. writeLog('success', 'Category Editor Function - Category Order Changed', $GLOBALS['organizrUser']['username']);
  1010. return true;
  1011. } catch (Dibi\Exception $e) {
  1012. return false;
  1013. }
  1014. break;
  1015. default:
  1016. return false;
  1017. break;
  1018. }
  1019. }
  1020. function allUsers()
  1021. {
  1022. try {
  1023. $connect = new Dibi\Connection([
  1024. 'driver' => 'sqlite3',
  1025. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1026. ]);
  1027. $users = $connect->fetchAll('SELECT * FROM users');
  1028. $groups = $connect->fetchAll('SELECT * FROM groups ORDER BY group_id ASC');
  1029. foreach ($users as $k => $v) {
  1030. // clear password from array
  1031. unset($users[$k]['password']);
  1032. }
  1033. $all['users'] = $users;
  1034. $all['groups'] = $groups;
  1035. return $all;
  1036. } catch (Dibi\Exception $e) {
  1037. return false;
  1038. }
  1039. }
  1040. function usernameTaken($username, $email)
  1041. {
  1042. try {
  1043. $connect = new Dibi\Connection([
  1044. 'driver' => 'sqlite3',
  1045. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1046. ]);
  1047. $all = $connect->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE', $username, $email);
  1048. return ($all) ? true : false;
  1049. } catch (Dibi\Exception $e) {
  1050. return false;
  1051. }
  1052. }
  1053. function usernameTakenExcept($username, $email, $id)
  1054. {
  1055. try {
  1056. $connect = new Dibi\Connection([
  1057. 'driver' => 'sqlite3',
  1058. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1059. ]);
  1060. $all = $connect->fetch('SELECT * FROM users WHERE id IS NOT ? AND username = ? COLLATE NOCASE OR id IS NOT ? AND email = ? COLLATE NOCASE', $id, $username, $id, $email);
  1061. return ($all) ? true : false;
  1062. } catch (Dibi\Exception $e) {
  1063. return false;
  1064. }
  1065. }
  1066. function createUser($username, $password, $defaults, $email = null)
  1067. {
  1068. $email = ($email) ? $email : random_ascii_string(10) . '@placeholder.eml';
  1069. try {
  1070. if (!usernameTaken($username, $email)) {
  1071. $createDB = new Dibi\Connection([
  1072. 'driver' => 'sqlite3',
  1073. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1074. ]);
  1075. $userInfo = [
  1076. 'username' => $username,
  1077. 'password' => password_hash($password, PASSWORD_BCRYPT),
  1078. 'email' => $email,
  1079. 'group' => $defaults['group'],
  1080. 'group_id' => $defaults['group_id'],
  1081. 'image' => gravatar($email),
  1082. 'register_date' => $GLOBALS['currentTime'],
  1083. ];
  1084. $createDB->query('INSERT INTO [users]', $userInfo);
  1085. return true;
  1086. } else {
  1087. return false;
  1088. }
  1089. } catch (Dibi\Exception $e) {
  1090. return false;
  1091. }
  1092. }
  1093. function importUsers($array)
  1094. {
  1095. $imported = 0;
  1096. $defaults = defaultUserGroup();
  1097. foreach ($array as $user) {
  1098. $password = random_ascii_string(30);
  1099. if ($user['username'] !== '' && $user['email'] !== '' && $password !== '' && $defaults !== '') {
  1100. $newUser = createUser($user['username'], $password, $defaults, $user['email']);
  1101. if (!$newUser) {
  1102. writeLog('error', 'Import Function - Error', $user['username']);
  1103. } else {
  1104. $imported++;
  1105. }
  1106. }
  1107. }
  1108. return $imported;
  1109. }
  1110. function importUsersType($array)
  1111. {
  1112. $type = $array['data']['type'];
  1113. if ($type !== '') {
  1114. switch ($type) {
  1115. case 'plex':
  1116. return importUsers(allPlexUsers(true));
  1117. break;
  1118. case 'jellyfin':
  1119. return importUsers(allJellyfinUsers(true));
  1120. break;
  1121. case 'emby':
  1122. return importUsers(allEmbyUsers(true));
  1123. break;
  1124. default:
  1125. return false;
  1126. }
  1127. }
  1128. return false;
  1129. }
  1130. function allTabs()
  1131. {
  1132. if (file_exists($GLOBALS['userConfigPath'])) {
  1133. try {
  1134. $connect = new Dibi\Connection([
  1135. 'driver' => 'sqlite3',
  1136. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1137. ]);
  1138. $all['tabs'] = $connect->fetchAll('SELECT * FROM tabs ORDER BY `order` ASC');
  1139. $all['categories'] = $connect->fetchAll('SELECT * FROM categories ORDER BY `order` ASC');
  1140. $all['groups'] = $connect->fetchAll('SELECT * FROM groups ORDER BY `group_id` ASC');
  1141. return $all;
  1142. } catch (Dibi\Exception $e) {
  1143. return false;
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. function allGroups()
  1149. {
  1150. if (file_exists($GLOBALS['userConfigPath'])) {
  1151. try {
  1152. $connect = new Dibi\Connection([
  1153. 'driver' => 'sqlite3',
  1154. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1155. ]);
  1156. $all = $connect->fetchAll('SELECT * FROM groups ORDER BY `group_id` ASC');
  1157. return $all;
  1158. } catch (Dibi\Exception $e) {
  1159. return false;
  1160. }
  1161. }
  1162. return false;
  1163. }
  1164. function loadTabs($type = null)
  1165. {
  1166. if (file_exists($GLOBALS['userConfigPath']) && $type) {
  1167. try {
  1168. $connect = new Dibi\Connection([
  1169. 'driver' => 'sqlite3',
  1170. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1171. ]);
  1172. $sort = ($GLOBALS['unsortedTabs'] == 'top') ? 'DESC' : 'ASC';
  1173. $tabs = $connect->fetchAll('SELECT * FROM tabs WHERE `group_id` >= ? AND `enabled` = 1 ORDER BY `order` ' . $sort, $GLOBALS['organizrUser']['groupID']);
  1174. $categories = $connect->fetchAll('SELECT * FROM categories ORDER BY `order` ASC');
  1175. $all['tabs'] = $tabs;
  1176. foreach ($tabs as $k => $v) {
  1177. $v['access_url'] = (!empty($v['url_local']) && ($v['url_local'] !== null) && ($v['url_local'] !== 'null') && isLocal() && $v['type'] !== 0) ? $v['url_local'] : $v['url'];
  1178. }
  1179. $count = array_map(function ($element) {
  1180. return $element['category_id'];
  1181. }, $tabs);
  1182. $count = (array_count_values($count));
  1183. foreach ($categories as $k => $v) {
  1184. $v['count'] = isset($count[$v['category_id']]) ? $count[$v['category_id']] : 0;
  1185. }
  1186. $all['categories'] = $categories;
  1187. switch ($type) {
  1188. case 'categories':
  1189. return $all['categories'];
  1190. case 'tabs':
  1191. return $all['tabs'];
  1192. default:
  1193. return $all;
  1194. }
  1195. } catch (Dibi\Exception $e) {
  1196. return false;
  1197. }
  1198. }
  1199. return false;
  1200. }
  1201. function getActiveTokens()
  1202. {
  1203. try {
  1204. $connect = new Dibi\Connection([
  1205. 'driver' => 'sqlite3',
  1206. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1207. ]);
  1208. $all = $connect->fetchAll('SELECT * FROM `tokens` WHERE `user_id` = ? AND `expires` > ?', $GLOBALS['organizrUser']['userID'], $GLOBALS['currentTime']);
  1209. return $all;
  1210. } catch (Dibi\Exception $e) {
  1211. return false;
  1212. }
  1213. }
  1214. function revokeToken($array)
  1215. {
  1216. if ($array['data']['token']) {
  1217. try {
  1218. $connect = new Dibi\Connection([
  1219. 'driver' => 'sqlite3',
  1220. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1221. ]);
  1222. $connect->query('DELETE FROM tokens WHERE user_id = ? AND token = ?', $GLOBALS['organizrUser']['userID'], $array['data']['token']);
  1223. return true;
  1224. } catch (Dibi\Exception $e) {
  1225. return false;
  1226. }
  1227. }
  1228. }
  1229. function getSchema()
  1230. {
  1231. if (file_exists($GLOBALS['userConfigPath'])) {
  1232. try {
  1233. $connect = new Dibi\Connection([
  1234. 'driver' => 'sqlite3',
  1235. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  1236. ]);
  1237. $result = $connect->fetchAll(' SELECT name, sql FROM sqlite_master WHERE type=\'table\' ORDER BY name');
  1238. return $result;
  1239. } catch (Dibi\Exception $e) {
  1240. return false;
  1241. }
  1242. } else {
  1243. return 'DB not set yet...';
  1244. }
  1245. }
  1246. function youtubeSearch($query)
  1247. {
  1248. if (!$query) {
  1249. return 'no query provided!';
  1250. }
  1251. $keys = array('AIzaSyBsdt8nLJRMTwOq5PY5A5GLZ2q7scgn01w', 'AIzaSyD-8SHutB60GCcSM8q_Fle38rJUV7ujd8k', 'AIzaSyBzOpVBT6VII-b-8gWD0MOEosGg4hyhCsQ', 'AIzaSyBKnRe1P8fpfBHgooJpmT0WOsrdUtZ4cpk');
  1252. $randomKeyIndex = array_rand($keys);
  1253. $key = $keys[$randomKeyIndex];
  1254. $apikey = ($GLOBALS['youtubeAPI'] !== '') ? $GLOBALS['youtubeAPI'] : $key;
  1255. $results = false;
  1256. $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=$query+official+trailer&part=snippet&maxResults=1&type=video&videoDuration=short&key=$apikey";
  1257. $response = Requests::get($url);
  1258. if ($response->success) {
  1259. $results = json_decode($response->body, true);
  1260. }
  1261. return ($results) ? $results : false;
  1262. }
  1263. function scrapePage($array)
  1264. {
  1265. try {
  1266. $url = $array['data']['url'] ?? false;
  1267. $type = $array['data']['type'] ?? false;
  1268. if (!$url) return array(
  1269. 'result' => 'Error',
  1270. 'data' => 'No URL'
  1271. );
  1272. $url = qualifyURL($url);
  1273. $data = array(
  1274. 'full_url' => $url,
  1275. 'drill_url' => qualifyURL($url, true)
  1276. );
  1277. $options = array('verify' => false);
  1278. $response = Requests::get($url, array(), $options);
  1279. $data['response_code'] = $response->status_code;
  1280. if ($response->success) {
  1281. $data['result'] = 'Success';
  1282. switch ($type) {
  1283. case 'html':
  1284. $data['data'] = html_entity_decode($response->body);
  1285. break;
  1286. case 'json':
  1287. $data['data'] = json_decode($response->body);
  1288. break;
  1289. default:
  1290. $data['data'] = $response->body;
  1291. }
  1292. return $data;
  1293. }
  1294. } catch (Requests_Exception $e) {
  1295. return array(
  1296. 'result' => 'Error',
  1297. 'data' => $e->getMessage()
  1298. );
  1299. };
  1300. return array('result' => 'Error');
  1301. }
  1302. function searchCityForCoordinates($array)
  1303. {
  1304. try {
  1305. $query = $array['data']['query'] ?? false;
  1306. $url = qualifyURL('https://api.mapbox.com/geocoding/v5/mapbox.places/' . urlencode($query) . '.json?access_token=pk.eyJ1IjoiY2F1c2VmeCIsImEiOiJjazhyeGxqeXgwMWd2M2ZydWQ4YmdjdGlzIn0.R50iYuMewh1CnUZ7sFPdHA&limit=5&fuzzyMatch=true');
  1307. $options = array('verify' => false);
  1308. $response = Requests::get($url, array(), $options);
  1309. if ($response->success) {
  1310. return json_decode($response->body);
  1311. }
  1312. } catch (Requests_Exception $e) {
  1313. return array(
  1314. 'result' => 'Error',
  1315. 'data' => $e->getMessage()
  1316. );
  1317. };
  1318. return array('result' => 'Error');
  1319. }