4
0

functions.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. <?php
  2. // ===================================
  3. // Organizr Version
  4. $GLOBALS['installedVersion'] = '2.0.0-alpha';
  5. // ===================================
  6. //Set GLOBALS from config file
  7. $GLOBALS['userConfigPath'] = __DIR__.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php';
  8. $GLOBALS['defaultConfigPath'] = __DIR__.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'default.php';
  9. $GLOBALS['currentTime'] = gmdate("Y-m-d\TH:i:s\Z");
  10. //Add in default and custom settings
  11. configLazy();
  12. //Define Logs and files after db location is set
  13. if(isset($GLOBALS['dbLocation'])){
  14. $GLOBALS['organizrLog'] = $GLOBALS['dbLocation'].'organizrLog.json';
  15. $GLOBALS['organizrLoginLog'] = $GLOBALS['dbLocation'].'organizrLoginLog.json';
  16. }
  17. //Set UTC timeZone
  18. date_default_timezone_set("UTC");
  19. // Autoload frameworks
  20. require_once(__DIR__ . '/vendor/autoload.php');
  21. //framework uses
  22. use Lcobucci\JWT\Builder;
  23. use Lcobucci\JWT\Signer\Hmac\Sha256;
  24. use Lcobucci\JWT\ValidationData;
  25. use Lcobucci\JWT\Parser;
  26. //Validate Token if set and set guest if not - sets GLOBALS
  27. getOrganizrUserToken();
  28. //include all pages files
  29. foreach (glob(__DIR__.DIRECTORY_SEPARATOR.'pages' . DIRECTORY_SEPARATOR . "*.php") as $filename){
  30. require_once $filename;
  31. }
  32. function jwtParse($token){
  33. try {
  34. $result = array();
  35. $result['valid'] = false;
  36. //Check Token with JWT
  37. //Set key
  38. if(!isset($GLOBALS['organizrHash'])){
  39. return null;
  40. }
  41. $key = $GLOBALS['organizrHash'];
  42. //HSA256 Encyption
  43. $signer = new Sha256();
  44. $jwttoken = (new Parser())->parse((string) $token); // Parses from a string
  45. $jwttoken->getHeaders(); // Retrieves the token header
  46. $jwttoken->getClaims(); // Retrieves the token claims
  47. //Start Validation
  48. if($jwttoken->verify($signer, $key)){
  49. $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
  50. $data->setIssuer('Organizr');
  51. $data->setAudience('Organizr');
  52. if($jwttoken->validate($data)){
  53. $result['valid'] = true;
  54. $result['username'] = $jwttoken->getClaim('username');
  55. $result['group'] = $jwttoken->getClaim('group');
  56. $result['groupID'] = $jwttoken->getClaim('groupID');
  57. $result['email'] = $jwttoken->getClaim('email');
  58. $result['image'] = $jwttoken->getClaim('image');
  59. $result['tokenExpire'] = $jwttoken->getClaim('exp');
  60. $result['tokenDate'] = $jwttoken->getClaim('iat');
  61. $result['token'] = $jwttoken->getClaim('exp');
  62. }
  63. }
  64. if($result['valid'] == true){ return $result; }else{ return false; }
  65. } catch(\RunException $e) {
  66. return false;
  67. } catch(\OutOfBoundsException $e) {
  68. return false;
  69. } catch(\RunTimeException $e) {
  70. return false;
  71. } catch(\InvalidArgumentException $e) {
  72. return false;
  73. }
  74. }
  75. function createToken($username,$email,$image,$group,$groupID,$key,$days = 1){
  76. //Create JWT
  77. //Set key
  78. //HSA256 Encyption
  79. $signer = new Sha256();
  80. //Start Builder
  81. $jwttoken = (new Builder())->setIssuer('Organizr') // Configures the issuer (iss claim)
  82. ->setAudience('Organizr') // Configures the audience (aud claim)
  83. ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
  84. ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
  85. ->setExpiration(time() + (86400 * $days)) // Configures the expiration time of the token (exp claim)
  86. ->set('username', $username) // Configures a new claim, called "username"
  87. ->set('group', $group) // Configures a new claim, called "group"
  88. ->set('groupID', $groupID) // Configures a new claim, called "groupID"
  89. ->set('email', $email) // Configures a new claim, called "email"
  90. ->set('image', $image) // Configures a new claim, called "image"
  91. ->sign($signer, $key) // creates a signature using "testing" as key
  92. ->getToken(); // Retrieves the generated token
  93. $jwttoken->getHeaders(); // Retrieves the token headers
  94. $jwttoken->getClaims(); // Retrieves the token claims
  95. coookie('set','organizrToken',$jwttoken,$days);
  96. return $jwttoken;
  97. }
  98. function prettyPrint($v) {
  99. $trace = debug_backtrace()[0];
  100. echo '<pre style="white-space: pre; text-overflow: ellipsis; overflow: hidden; background-color: #f2f2f2; border: 2px solid black; border-radius: 5px; padding: 5px; margin: 5px;">'.$trace['file'].':'.$trace['line'].' '.gettype($v)."\n\n".print_r($v, 1).'</pre><br/>';
  101. }
  102. // Create config file in the return syntax
  103. function createConfig($array, $path = null, $nest = 0) {
  104. $path = ($path) ? $path : $GLOBALS['userConfigPath'];
  105. // Define Initial Value
  106. $output = array();
  107. // Sort Items
  108. ksort($array);
  109. // Update the current config version
  110. if (!$nest) {
  111. // Inject Current Version
  112. $output[] = "\t'configVersion' => '".(isset($array['apply_CONFIG_VERSION'])?$array['apply_CONFIG_VERSION']:$GLOBALS['installedVersion'])."'";
  113. }
  114. unset($array['configVersion']);
  115. unset($array['apply_CONFIG_VERSION']);
  116. // Process Settings
  117. foreach ($array as $k => $v) {
  118. $allowCommit = true;
  119. switch (gettype($v)) {
  120. case 'boolean':
  121. $item = ($v?true:false);
  122. break;
  123. case 'integer':
  124. case 'double':
  125. case 'integer':
  126. case 'NULL':
  127. $item = $v;
  128. break;
  129. case 'string':
  130. $item = "'".str_replace(array('\\',"'"),array('\\\\',"\'"),$v)."'";
  131. break;
  132. case 'array':
  133. $item = createConfig($v, false, $nest+1);
  134. break;
  135. default:
  136. $allowCommit = false;
  137. }
  138. if($allowCommit) {
  139. $output[] = str_repeat("\t",$nest+1)."'$k' => $item";
  140. }
  141. }
  142. // Build output
  143. $output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n",$output)."\n".str_repeat("\t",$nest).')'.(!$nest?';':'');
  144. if (!$nest && $path) {
  145. $pathDigest = pathinfo($path);
  146. @mkdir($pathDigest['dirname'], 0770, true);
  147. if (file_exists($path)) {
  148. rename($path, $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.php');
  149. }
  150. $file = fopen($path, 'w');
  151. fwrite($file, $output);
  152. fclose($file);
  153. if (file_exists($path)) {
  154. return true;
  155. }
  156. //writeLog("error", "config was unable to write");
  157. return false;
  158. } else {
  159. //writeLog("success", "config was updated with new values");
  160. return $output;
  161. }
  162. }
  163. // Commit new values to the configuration
  164. function updateConfig($new, $current = false) {
  165. // Get config if not supplied
  166. if ($current === false) {
  167. $current = loadConfig();
  168. } else if (is_string($current) && is_file($current)) {
  169. $current = loadConfig($current);
  170. }
  171. // Inject Parts
  172. foreach ($new as $k => $v) {
  173. $current[$k] = $v;
  174. }
  175. // Return Create
  176. return createConfig($current);
  177. }
  178. function configLazy() {
  179. // Load config or default
  180. if (file_exists($GLOBALS['userConfigPath'])) {
  181. $config = fillDefaultConfig(loadConfig($GLOBALS['userConfigPath']));
  182. } else {
  183. $config = loadConfig($GLOBALS['defaultConfigPath']);
  184. }
  185. if (is_array($config)) {
  186. defineConfig($config);
  187. }
  188. return $config;
  189. }
  190. function loadConfig($path = null){
  191. $path = ($path) ? $path : $GLOBALS['userConfigPath'];
  192. if (!is_file($path)) {
  193. return null;
  194. } else {
  195. return (array) call_user_func(function() use($path) {
  196. return include($path);
  197. });
  198. }
  199. }
  200. function fillDefaultConfig($array) {
  201. $path = $GLOBALS['defaultConfigPath'];
  202. if (is_string($path)) {
  203. $loadedDefaults = loadConfig($path);
  204. } else {
  205. $loadedDefaults = $path;
  206. }
  207. return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  208. }
  209. function fillDefaultConfig_recurse($current, $defaults) {
  210. foreach($defaults as $k => $v) {
  211. if (!isset($current[$k])) {
  212. $current[$k] = $v;
  213. } else if (is_array($current[$k]) && is_array($v)) {
  214. $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
  215. }
  216. }
  217. return $current;
  218. }
  219. function defineConfig($array, $anyCase = true, $nest_prefix = false) {
  220. foreach($array as $k => $v) {
  221. if (is_scalar($v) && !defined($nest_prefix.$k)) {
  222. $GLOBALS[$nest_prefix.$k] = $v;
  223. } else if (is_array($v)) {
  224. defineConfig($v, $anyCase, $nest_prefix.$k.'_');
  225. }
  226. }
  227. }
  228. function cleanDirectory($path){
  229. $path = str_replace(array('/', '\\'), '/', $path);
  230. if(substr($path, -1) != '/'){
  231. $path = $path . '/';
  232. }
  233. if($path[0] != '/' && $path[1] != ':'){
  234. $path = '/' . $path;
  235. }
  236. return $path;
  237. }
  238. function wizardConfig($array){
  239. foreach ($array['data'] as $items) {
  240. foreach ($items as $key => $value) {
  241. if($key == 'name'){
  242. $newKey = $value;
  243. }
  244. if($key == 'value'){
  245. $newValue = $value;
  246. }
  247. if(isset($newKey) && isset($newValue)){
  248. $$newKey = $newValue;
  249. }
  250. }
  251. }
  252. $location = cleanDirectory($location);
  253. $dbName = $dbName.'.db';
  254. $configVersion = $GLOBALS['installedVersion'];
  255. $configArray = array(
  256. 'dbName' => $dbName,
  257. 'dbLocation' => $location,
  258. 'license' => $license,
  259. 'organizrHash' => $hashKey,
  260. 'organizrAPI' => $api,
  261. 'registrationPassword' => $registrationPassword,
  262. );
  263. /*
  264. file_put_contents('config'.DIRECTORY_SEPARATOR.'config.php',
  265. "<?php
  266. return array(
  267. \"configVersion\" => \"$configVersion\",
  268. \"dbName\" => \"$dbName\",
  269. \"dbLocation\" => \"$location\",
  270. \"license\" => \"$license\",
  271. \"organizrHash\" => \"$hashKey\",
  272. \"organizrAPI\" => \"$api\",
  273. \"registrationPassword\" => \"$registrationPassword\"
  274. );");
  275. */
  276. //Create Config
  277. if(createConfig($configArray)){
  278. //Call DB Create
  279. if(createDB($location,$dbName)){
  280. //Add in first user
  281. if(createFirstAdmin($location,$dbName,$username,$password,$email)){
  282. if(createToken($username,$email,gravatar($email),'Admin',0,$hashKey,1)){
  283. return true;
  284. }
  285. }
  286. }
  287. }
  288. return false;
  289. }
  290. function gravatar($email = '') {
  291. $email = md5(strtolower(trim($email)));
  292. $gravurl = "https://www.gravatar.com/avatar/$email?s=100&d=mm";
  293. return $gravurl;
  294. }
  295. function login($array){
  296. //Grab username and Password from login form
  297. foreach ($array['data'] as $items) {
  298. foreach ($items as $key => $value) {
  299. if($key == 'name'){
  300. $newKey = $value;
  301. }
  302. if($key == 'value'){
  303. $newValue = $value;
  304. }
  305. if(isset($newKey) && isset($newValue)){
  306. $$newKey = $newValue;
  307. }
  308. }
  309. }
  310. $username = strtolower($username);
  311. $days = (isset($remember)) ? 7 : 1;
  312. try {
  313. $database = new Dibi\Connection([
  314. 'driver' => 'sqlite3',
  315. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  316. ]);
  317. $result = $database->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',$username,$username);
  318. if(password_verify($password, $result['password'])){
  319. if(createToken($result['username'],$result['email'],$result['image'],$result['group'],$result['group_id'],$GLOBALS['organizrHash'],$days)){
  320. writeLoginLog($username, 'success');
  321. writeLog('success', 'Login Function - A User has logged in', $username);
  322. return true;
  323. }
  324. }else{
  325. writeLoginLog($username, 'error');
  326. writeLog('error', 'Login Function - Wrong Password', $username);
  327. return 'mismatch';
  328. }
  329. } catch (Dibi\Exception $e) {
  330. return 'error';
  331. }
  332. }
  333. function createDB($path,$filename) {
  334. if(file_exists($path.$filename)){
  335. unlink($path.$filename);
  336. }
  337. try {
  338. $createDB = new Dibi\Connection([
  339. 'driver' => 'sqlite3',
  340. 'database' => $path.$filename,
  341. ]);
  342. // Create Users
  343. $users = $createDB->query('CREATE TABLE `users` (
  344. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  345. `username` TEXT UNIQUE,
  346. `password` TEXT,
  347. `email` TEXT,
  348. `plex_token` TEXT,
  349. `group` TEXT,
  350. `group_id` INTEGER,
  351. `image` TEXT,
  352. `register_date` DATE,
  353. `auth_service` TEXT DEFAULT \'internal\'
  354. );');
  355. $groups = $createDB->query('CREATE TABLE `groups` (
  356. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  357. `group` TEXT UNIQUE,
  358. `group_id` INTEGER,
  359. `image` TEXT,
  360. `default` INTEGER
  361. );');
  362. $categories = $createDB->query('CREATE TABLE `categories` (
  363. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  364. `order` INTEGER,
  365. `category` TEXT UNIQUE,
  366. `category_id` INTEGER,
  367. `image` TEXT,
  368. `default` INTEGER
  369. );');
  370. // Create Tabs
  371. $tabs = $createDB->query('CREATE TABLE `tabs` (
  372. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  373. `order` INTEGER,
  374. `category_id` INTEGER,
  375. `name` TEXT,
  376. `url` TEXT,
  377. `url_local` TEXT,
  378. `default` INTEGER,
  379. `enabled` INTEGER,
  380. `group_id` INTEGER,
  381. `image` TEXT,
  382. `type` INTEGER,
  383. `splash` INTEGER,
  384. `ping` INTEGER,
  385. `ping_url` TEXT
  386. );');
  387. // Create Options
  388. $options = $createDB->query('CREATE TABLE `options` (
  389. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  390. `users_id` INTEGER UNIQUE,
  391. `title` TEXT UNIQUE,
  392. `topbar` TEXT,
  393. `bottombar` TEXT,
  394. `sidebar` TEXT,
  395. `hoverbg` TEXT,
  396. `topbartext` TEXT,
  397. `activetabBG` TEXT,
  398. `activetabicon` TEXT,
  399. `activetabtext` TEXT,
  400. `inactiveicon` TEXT,
  401. `inactivetext` TEXT,
  402. `loading` TEXT,
  403. `hovertext` TEXT
  404. );');
  405. // Create Invites
  406. $invites = $createDB->query('CREATE TABLE `invites` (
  407. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  408. `code` TEXT UNIQUE,
  409. `date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  410. `email` TEXT,
  411. `username` TEXT,
  412. `dateused` TIMESTAMP,
  413. `usedby` TEXT,
  414. `ip` TEXT,
  415. `valid` TEXT,
  416. `type` TEXT
  417. );');
  418. return true;
  419. } catch (Dibi\Exception $e) {
  420. return false;
  421. }
  422. }
  423. // Upgrade Database
  424. function updateDB($path,$filename,$oldVerNum = false) {
  425. try {
  426. $connect = new Dibi\Connection([
  427. 'driver' => 'sqlite3',
  428. 'database' => $path.$filename,
  429. ]);
  430. // Cache current DB
  431. $cache = array();
  432. foreach($connect->query('SELECT name FROM sqlite_master WHERE type="table";') as $table) {
  433. foreach($connect->query('SELECT * FROM '.$table['name'].';') as $key => $row) {
  434. foreach($row as $k => $v) {
  435. if (is_string($k)) {
  436. $cache[$table['name']][$key][$k] = $v;
  437. }
  438. }
  439. }
  440. }
  441. // Remove Current Database
  442. /*
  443. $pathDigest = pathinfo($path.$filename);
  444. if (file_exists($path.$filename)) {
  445. rename($path.$filename, $pathDigest['dirname'].'/'.$pathDigest['filename'].'['.date('Y-m-d_H-i-s').']'.($oldVerNum?'['.$oldVerNum.']':'').'.bak.db');
  446. }
  447. // Create New Database
  448. $success = createSQLiteDB($path.$filename);
  449. // Restore Items
  450. if ($success) {
  451. foreach($cache as $table => $tableData) {
  452. if ($tableData) {
  453. $queryBase = 'INSERT INTO '.$table.' (`'.implode('`,`',array_keys(current($tableData))).'`) values ';
  454. $insertValues = array();
  455. reset($tableData);
  456. foreach($tableData as $key => $value) {
  457. $insertValues[] = '('.implode(',',array_map(function($d) {
  458. return (isset($d)?$GLOBALS['file_db']->quote($d):'null');
  459. }, $value)).')';
  460. }
  461. $GLOBALS['file_db']->query($queryBase.implode(',',$insertValues).';');
  462. }
  463. }
  464. //writeLog("success", "database values have been updated");
  465. return true;
  466. } else {
  467. //writeLog("error", "database values unable to be updated");
  468. return false;
  469. }
  470. */
  471. return $cache;
  472. } catch (Dibi\Exception $e) {
  473. return $e;
  474. }
  475. }
  476. function createFirstAdmin($path,$filename,$username,$password,$email) {
  477. try {
  478. $createDB = new Dibi\Connection([
  479. 'driver' => 'sqlite3',
  480. 'database' => $path.$filename,
  481. ]);
  482. $userInfo = [
  483. 'username' => $username,
  484. 'password' => password_hash($password, PASSWORD_BCRYPT),
  485. 'email' => $email,
  486. 'group' => 'Admin',
  487. 'group_id' => 0,
  488. 'image' => gravatar($email),
  489. 'register_date' => $GLOBALS['currentTime'],
  490. ];
  491. $groupInfo0 = [
  492. 'group' => 'Admin',
  493. 'group_id' => 0,
  494. 'default' => false,
  495. 'image' => 'plugins/images/groups/admin.png',
  496. ];
  497. $groupInfo1 = [
  498. 'group' => 'Co-Admin',
  499. 'group_id' => 1,
  500. 'default' => false,
  501. 'image' => 'plugins/images/groups/coadmin.png',
  502. ];
  503. $groupInfo2 = [
  504. 'group' => 'Super User',
  505. 'group_id' => 2,
  506. 'default' => false,
  507. 'image' => 'plugins/images/groups/superuser.png',
  508. ];
  509. $groupInfo3 = [
  510. 'group' => 'Power User',
  511. 'group_id' => 3,
  512. 'default' => false,
  513. 'image' => 'plugins/images/groups/poweruser.png',
  514. ];
  515. $groupInfo4 = [
  516. 'group' => 'User',
  517. 'group_id' => 4,
  518. 'default' => true,
  519. 'image' => 'plugins/images/groups/user.png',
  520. ];
  521. $groupInfoGuest = [
  522. 'group' => 'Guest',
  523. 'group_id' => 999,
  524. 'default' => false,
  525. 'image' => 'plugins/images/groups/guest.png',
  526. ];
  527. $settingsInfo = [
  528. 'order' => 1,
  529. 'category_id' => 0,
  530. 'name' => 'Settings',
  531. 'url' => 'api/?v1/settings/page',
  532. 'default' => false,
  533. 'enabled' => true,
  534. 'group_id' => 1,
  535. 'image' => 'fontawesome::cog',
  536. 'type' => 0
  537. ];
  538. $homepageInfo = [
  539. 'order' => 2,
  540. 'category_id' => 0,
  541. 'name' => 'Homepage',
  542. 'url' => 'api/?v1/homepage/page',
  543. 'default' => false,
  544. 'enabled' => false,
  545. 'group_id' => 4,
  546. 'image' => 'fontawesome::home',
  547. 'type' => 0
  548. ];
  549. $unsortedInfo = [
  550. 'order' => 1,
  551. 'category' => 'Unsorted',
  552. 'category_id' => 0,
  553. 'image' => 'plugins/images/categories/unsorted.png',
  554. 'default' => true
  555. ];
  556. $createDB->query('INSERT INTO [users]', $userInfo);
  557. $createDB->query('INSERT INTO [groups]', $groupInfo0);
  558. $createDB->query('INSERT INTO [groups]', $groupInfo1);
  559. $createDB->query('INSERT INTO [groups]', $groupInfo2);
  560. $createDB->query('INSERT INTO [groups]', $groupInfo3);
  561. $createDB->query('INSERT INTO [groups]', $groupInfo4);
  562. $createDB->query('INSERT INTO [groups]', $groupInfoGuest);
  563. $createDB->query('INSERT INTO [tabs]', $settingsInfo);
  564. $createDB->query('INSERT INTO [tabs]', $homepageInfo);
  565. $createDB->query('INSERT INTO [categories]', $unsortedInfo);
  566. return true;
  567. } catch (Dibi\Exception $e) {
  568. return false;
  569. }
  570. }
  571. function register($array){
  572. //Grab username and Password from login form
  573. foreach ($array['data'] as $items) {
  574. foreach ($items as $key => $value) {
  575. if($key == 'name'){
  576. $newKey = $value;
  577. }
  578. if($key == 'value'){
  579. $newValue = $value;
  580. }
  581. if(isset($newKey) && isset($newValue)){
  582. $$newKey = $newValue;
  583. }
  584. }
  585. }
  586. if($registrationPassword == $GLOBALS['registrationPassword']){
  587. $defaults = defaultUserGroup();
  588. writeLog('success', 'Registration Function - Registration Password Verified', $username);
  589. if(createUser($username,$password,$defaults,$email)){
  590. writeLog('success', 'Registration Function - A User has registered', $username);
  591. if(createToken($username,$email,gravatar($email),$defaults['group'],$defaults['group_id'],$GLOBALS['organizrHash'],1)){
  592. writeLoginLog($username, 'success');
  593. writeLog('success', 'Login Function - A User has logged in', $username);
  594. return true;
  595. }
  596. }else{
  597. writeLog('error', 'Registration Function - An error occured', $username);
  598. return 'username taken';
  599. }
  600. }else{
  601. writeLog('warning', 'Registration Function - Wrong Password', $username);
  602. return 'mismatch';
  603. }
  604. }
  605. function defaultUserGroup(){
  606. try {
  607. $connect = new Dibi\Connection([
  608. 'driver' => 'sqlite3',
  609. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  610. ]);
  611. $all = $connect->fetch('SELECT * FROM groups WHERE `default` = 1');
  612. return $all;
  613. } catch (Dibi\Exception $e) {
  614. return false;
  615. }
  616. }
  617. function defaulTabCategory(){
  618. try {
  619. $connect = new Dibi\Connection([
  620. 'driver' => 'sqlite3',
  621. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  622. ]);
  623. $all = $connect->fetch('SELECT * FROM categories WHERE `default` = 1');
  624. return $all;
  625. } catch (Dibi\Exception $e) {
  626. return false;
  627. }
  628. }
  629. function getGuest(){
  630. if(isset($GLOBALS['dbLocation'])){
  631. try {
  632. $connect = new Dibi\Connection([
  633. 'driver' => 'sqlite3',
  634. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  635. ]);
  636. $all = $connect->fetch('SELECT * FROM groups WHERE `group` = "Guest"');
  637. return $all;
  638. } catch (Dibi\Exception $e) {
  639. return false;
  640. }
  641. }else{
  642. return array(
  643. 'group' => 'Guest',
  644. 'group_id' => 999,
  645. 'image' => 'plugins/images/groups/guest.png'
  646. );
  647. }
  648. }
  649. function adminEditGroup($array){
  650. switch ($array['data']['action']) {
  651. case 'changeDefaultGroup':
  652. try {
  653. $connect = new Dibi\Connection([
  654. 'driver' => 'sqlite3',
  655. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  656. ]);
  657. $connect->query('UPDATE groups SET `default` = 0');
  658. $connect->query('
  659. UPDATE groups SET', [
  660. 'default' => 1
  661. ], '
  662. WHERE id=?', $array['data']['id']);
  663. writeLog('success', 'Group Management Function - Changed Default Group from ['.$array['data']['oldGroupName'].'] to ['.$array['data']['newGroupName'].']', $GLOBALS['organizrUser']['username']);
  664. return true;
  665. } catch (Dibi\Exception $e) {
  666. return false;
  667. }
  668. break;
  669. case 'deleteUserGroup':
  670. try {
  671. $connect = new Dibi\Connection([
  672. 'driver' => 'sqlite3',
  673. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  674. ]);
  675. $connect->query('DELETE FROM groups WHERE id = ?', $array['data']['id']);
  676. writeLog('success', 'Group Management Function - Deleted Group ['.$array['data']['groupName'].']', $GLOBALS['organizrUser']['username']);
  677. return true;
  678. } catch (Dibi\Exception $e) {
  679. return false;
  680. }
  681. break;
  682. case 'addUserGroup':
  683. try {
  684. $connect = new Dibi\Connection([
  685. 'driver' => 'sqlite3',
  686. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  687. ]);
  688. $newGroup = [
  689. 'group' => $array['data']['newGroupName'],
  690. 'group_id' => $array['data']['newGroupID'],
  691. 'default' => false,
  692. 'image' => $array['data']['newGroupImage'],
  693. ];
  694. $connect->query('INSERT INTO [groups]', $newGroup);
  695. writeLog('success', 'Group Management Function - Added Group ['.$array['data']['newGroupName'].']', $GLOBALS['organizrUser']['username']);
  696. return true;
  697. } catch (Dibi\Exception $e) {
  698. return false;
  699. }
  700. break;
  701. case 'editUserGroup':
  702. try {
  703. $connect = new Dibi\Connection([
  704. 'driver' => 'sqlite3',
  705. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  706. ]);
  707. $connect->query('
  708. UPDATE groups SET', [
  709. 'group' => $array['data']['groupName'],
  710. 'image' => $array['data']['groupImage'],
  711. ], '
  712. WHERE id=?', $array['data']['id']);
  713. writeLog('success', 'Group Management Function - Edited Group Info for ['.$array['data']['oldGroupName'].']', $GLOBALS['organizrUser']['username']);
  714. return true;
  715. } catch (Dibi\Exception $e) {
  716. return false;
  717. }
  718. break;
  719. default:
  720. # code...
  721. break;
  722. }
  723. }
  724. function adminEditUser($array){
  725. switch ($array['data']['action']) {
  726. case 'changeGroup':
  727. try {
  728. $connect = new Dibi\Connection([
  729. 'driver' => 'sqlite3',
  730. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  731. ]);
  732. $connect->query('
  733. UPDATE users SET', [
  734. 'group' => $array['data']['newGroupName'],
  735. 'group_id' => $array['data']['newGroupID'],
  736. ], '
  737. WHERE id=?', $array['data']['id']);
  738. writeLog('success', 'User Management Function - User: '.$array['data']['username'].'\'s group was changed from ['.$array['data']['oldGroup'].'] to ['.$array['data']['newGroupName'].']', $GLOBALS['organizrUser']['username']);
  739. return true;
  740. } catch (Dibi\Exception $e) {
  741. 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']);
  742. return false;
  743. }
  744. break;
  745. case 'addNewUser':
  746. $defaults = defaultUserGroup();
  747. if(createUser($array['data']['username'],$array['data']['password'],$defaults,$array['data']['email'])){
  748. writeLog('success', 'Create User Function - Acount created for ['.$array['data']['username'].']', $GLOBALS['organizrUser']['username']);
  749. return true;
  750. }else{
  751. writeLog('error', 'Registration Function - An error occured', $GLOBALS['organizrUser']['username']);
  752. return 'username taken';
  753. }
  754. break;
  755. case 'deleteUser':
  756. try {
  757. $connect = new Dibi\Connection([
  758. 'driver' => 'sqlite3',
  759. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  760. ]);
  761. $connect->query('DELETE FROM users WHERE id = ?', $array['data']['id']);
  762. writeLog('success', 'User Management Function - Deleted User ['.$array['data']['username'].']', $GLOBALS['organizrUser']['username']);
  763. return true;
  764. } catch (Dibi\Exception $e) {
  765. return false;
  766. }
  767. break;
  768. default:
  769. # code...
  770. break;
  771. }
  772. }
  773. function editTabs($array){
  774. switch ($array['data']['action']) {
  775. case 'changeGroup':
  776. try {
  777. $connect = new Dibi\Connection([
  778. 'driver' => 'sqlite3',
  779. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  780. ]);
  781. $connect->query('
  782. UPDATE tabs SET', [
  783. 'group_id' => $array['data']['newGroupID'],
  784. ], '
  785. WHERE id=?', $array['data']['id']);
  786. writeLog('success', 'Tab Editor Function - Tab: '.$array['data']['tab'].'\'s group was changed to ['.$array['data']['newGroupName'].']', $GLOBALS['organizrUser']['username']);
  787. return true;
  788. } catch (Dibi\Exception $e) {
  789. return false;
  790. }
  791. break;
  792. case 'changeCategory':
  793. try {
  794. $connect = new Dibi\Connection([
  795. 'driver' => 'sqlite3',
  796. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  797. ]);
  798. $connect->query('
  799. UPDATE tabs SET', [
  800. 'category_id' => $array['data']['newCategoryID'],
  801. ], '
  802. WHERE id=?', $array['data']['id']);
  803. writeLog('success', 'Tab Editor Function - Tab: '.$array['data']['tab'].'\'s category was changed to ['.$array['data']['newCategoryName'].']', $GLOBALS['organizrUser']['username']);
  804. return true;
  805. } catch (Dibi\Exception $e) {
  806. return false;
  807. }
  808. break;
  809. case 'changeType':
  810. try {
  811. $connect = new Dibi\Connection([
  812. 'driver' => 'sqlite3',
  813. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  814. ]);
  815. $connect->query('
  816. UPDATE tabs SET', [
  817. 'type' => $array['data']['newTypeID'],
  818. ], '
  819. WHERE id=?', $array['data']['id']);
  820. writeLog('success', 'Tab Editor Function - Tab: '.$array['data']['tab'].'\'s type was changed to ['.$array['data']['newTypeName'].']', $GLOBALS['organizrUser']['username']);
  821. return true;
  822. } catch (Dibi\Exception $e) {
  823. return false;
  824. }
  825. break;
  826. case 'changeEnabled':
  827. try {
  828. $connect = new Dibi\Connection([
  829. 'driver' => 'sqlite3',
  830. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  831. ]);
  832. $connect->query('
  833. UPDATE tabs SET', [
  834. 'enabled' => $array['data']['tabEnabled'],
  835. ], '
  836. WHERE id=?', $array['data']['id']);
  837. writeLog('success', 'Tab Editor Function - Tab: '.$array['data']['tab'].'\'s enable status was changed to ['.$array['data']['tabEnabledWord'].']', $GLOBALS['organizrUser']['username']);
  838. return true;
  839. } catch (Dibi\Exception $e) {
  840. return false;
  841. }
  842. break;
  843. case 'changeSplash':
  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. 'splash' => $array['data']['tabSplash'],
  852. ], '
  853. WHERE id=?', $array['data']['id']);
  854. writeLog('success', 'Tab Editor Function - Tab: '.$array['data']['tab'].'\'s splash status was changed to ['.$array['data']['tabSplashWord'].']', $GLOBALS['organizrUser']['username']);
  855. return true;
  856. } catch (Dibi\Exception $e) {
  857. return false;
  858. }
  859. break;
  860. case 'changeDefault':
  861. try {
  862. $connect = new Dibi\Connection([
  863. 'driver' => 'sqlite3',
  864. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  865. ]);
  866. $connect->query('UPDATE tabs SET `default` = 0');
  867. $connect->query('
  868. UPDATE tabs SET', [
  869. 'default' => 1
  870. ], '
  871. WHERE id=?', $array['data']['id']);
  872. writeLog('success', 'Tab Editor Function - Changed Default Tab to ['.$array['data']['tab'].']', $GLOBALS['organizrUser']['username']);
  873. return true;
  874. } catch (Dibi\Exception $e) {
  875. return false;
  876. }
  877. break;
  878. case 'deleteTab':
  879. try {
  880. $connect = new Dibi\Connection([
  881. 'driver' => 'sqlite3',
  882. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  883. ]);
  884. $connect->query('DELETE FROM tabs WHERE id = ?', $array['data']['id']);
  885. writeLog('success', 'Tab Editor Function - Deleted Tab ['.$array['data']['tab'].']', $GLOBALS['organizrUser']['username']);
  886. return true;
  887. } catch (Dibi\Exception $e) {
  888. return false;
  889. }
  890. break;
  891. case 'editTab':
  892. try {
  893. $connect = new Dibi\Connection([
  894. 'driver' => 'sqlite3',
  895. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  896. ]);
  897. $connect->query('
  898. UPDATE tabs SET', [
  899. 'name' => $array['data']['tabName'],
  900. 'url' => $array['data']['tabURL'],
  901. 'image' => $array['data']['tabImage'],
  902. ], '
  903. WHERE id=?', $array['data']['id']);
  904. writeLog('success', 'Tab Editor Function - Edited Tab Info for ['.$array['data']['tabName'].']', $GLOBALS['organizrUser']['username']);
  905. return true;
  906. } catch (Dibi\Exception $e) {
  907. return false;
  908. }
  909. case 'changeOrder':
  910. try {
  911. $connect = new Dibi\Connection([
  912. 'driver' => 'sqlite3',
  913. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  914. ]);
  915. foreach ($array['data']['tabs']['tab'] as $key => $value) {
  916. if($value['order'] != $value['originalOrder']){
  917. $connect->query('
  918. UPDATE tabs SET', [
  919. 'order' => $value['order'],
  920. ], '
  921. WHERE id=?', $value['id']);
  922. writeLog('success', 'Tab Editor Function - '.$value['name'].' Order Changed From '.$value['order'].' to '.$value['originalOrder'], $GLOBALS['organizrUser']['username']);
  923. }
  924. }
  925. writeLog('success', 'Tab Editor Function - Tab Order Changed', $GLOBALS['organizrUser']['username']);
  926. return true;
  927. } catch (Dibi\Exception $e) {
  928. return false;
  929. }
  930. break;
  931. case 'addNewTab':
  932. try {
  933. $default = defaulTabCategory()['category_id'];
  934. $connect = new Dibi\Connection([
  935. 'driver' => 'sqlite3',
  936. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  937. ]);
  938. $newTab = [
  939. 'order' => $array['data']['tabOrder'],
  940. 'category_id' => $default,
  941. 'name' => $array['data']['tabName'],
  942. 'url' => $array['data']['tabURL'],
  943. 'default' => $array['data']['tabDefault'],
  944. 'enabled' => 1,
  945. 'group_id' => $array['data']['tabGroupID'],
  946. 'image' => $array['data']['tabImage'],
  947. 'type' => $array['data']['tabType']
  948. ];
  949. $connect->query('INSERT INTO [tabs]', $newTab);
  950. writeLog('success', 'Tab Editor Function - Created Tab for: '.$array['data']['tabName'], $GLOBALS['organizrUser']['username']);
  951. return true;
  952. } catch (Dibi\Exception $e) {
  953. return false;
  954. }
  955. break;
  956. case 'deleteTab':
  957. try {
  958. $connect = new Dibi\Connection([
  959. 'driver' => 'sqlite3',
  960. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  961. ]);
  962. $connect->query('DELETE FROM tabs WHERE id = ?', $array['data']['id']);
  963. writeLog('success', 'Tab Editor Function - Deleted Tab ['.$array['data']['name'].']', $GLOBALS['organizrUser']['username']);
  964. return true;
  965. } catch (Dibi\Exception $e) {
  966. return false;
  967. }
  968. break;
  969. default:
  970. # code...
  971. break;
  972. }
  973. }
  974. function editCategories($array){
  975. switch ($array['data']['action']) {
  976. case 'changeDefault':
  977. try {
  978. $connect = new Dibi\Connection([
  979. 'driver' => 'sqlite3',
  980. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  981. ]);
  982. $connect->query('UPDATE categories SET `default` = 0');
  983. $connect->query('
  984. UPDATE categories SET', [
  985. 'default' => 1
  986. ], '
  987. WHERE id=?', $array['data']['id']);
  988. writeLog('success', 'Category Editor Function - Changed Default Category from ['.$array['data']['oldCategoryName'].'] to ['.$array['data']['newCategoryName'].']', $GLOBALS['organizrUser']['username']);
  989. return true;
  990. } catch (Dibi\Exception $e) {
  991. return false;
  992. }
  993. break;
  994. case 'deleteCategory':
  995. try {
  996. $connect = new Dibi\Connection([
  997. 'driver' => 'sqlite3',
  998. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  999. ]);
  1000. $connect->query('DELETE FROM categories WHERE id = ?', $array['data']['id']);
  1001. writeLog('success', 'Category Editor Function - Deleted Category ['.$array['data']['category'].']', $GLOBALS['organizrUser']['username']);
  1002. return true;
  1003. } catch (Dibi\Exception $e) {
  1004. return false;
  1005. }
  1006. break;
  1007. case 'addNewCategory':
  1008. try {
  1009. $connect = new Dibi\Connection([
  1010. 'driver' => 'sqlite3',
  1011. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1012. ]);
  1013. $newCategory = [
  1014. 'category' => $array['data']['categoryName'],
  1015. 'order' => $array['data']['categoryOrder'],
  1016. 'category_id' => $array['data']['categoryID'],
  1017. 'default' => false,
  1018. 'image' => $array['data']['categoryImage'],
  1019. ];
  1020. $connect->query('INSERT INTO [categories]', $newCategory);
  1021. writeLog('success', 'Category Editor Function - Added Category ['.$array['data']['categoryName'].']', $GLOBALS['organizrUser']['username']);
  1022. return true;
  1023. } catch (Dibi\Exception $e) {
  1024. return $e;
  1025. }
  1026. break;
  1027. case 'editCategory':
  1028. try {
  1029. $connect = new Dibi\Connection([
  1030. 'driver' => 'sqlite3',
  1031. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1032. ]);
  1033. $connect->query('
  1034. UPDATE categories SET', [
  1035. 'category' => $array['data']['name'],
  1036. 'image' => $array['data']['image'],
  1037. ], '
  1038. WHERE id=?', $array['data']['id']);
  1039. writeLog('success', 'Category Editor Function - Edited Category Info for ['.$array['data']['name'].']', $GLOBALS['organizrUser']['username']);
  1040. return true;
  1041. } catch (Dibi\Exception $e) {
  1042. return false;
  1043. }
  1044. break;
  1045. case 'changeOrder':
  1046. try {
  1047. $connect = new Dibi\Connection([
  1048. 'driver' => 'sqlite3',
  1049. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1050. ]);
  1051. foreach ($array['data']['categories']['category'] as $key => $value) {
  1052. if($value['order'] != $value['originalOrder']){
  1053. $connect->query('
  1054. UPDATE categories SET', [
  1055. 'order' => $value['order'],
  1056. ], '
  1057. WHERE id=?', $value['id']);
  1058. writeLog('success', 'Category Editor Function - '.$value['name'].' Order Changed From '.$value['order'].' to '.$value['originalOrder'], $GLOBALS['organizrUser']['username']);
  1059. }
  1060. }
  1061. writeLog('success', 'Category Editor Function - Category Order Changed', $GLOBALS['organizrUser']['username']);
  1062. return true;
  1063. } catch (Dibi\Exception $e) {
  1064. return false;
  1065. }
  1066. break;
  1067. default:
  1068. # code...
  1069. break;
  1070. }
  1071. }
  1072. function editUser($array){
  1073. return $array;
  1074. }
  1075. function allUsers(){
  1076. try {
  1077. $connect = new Dibi\Connection([
  1078. 'driver' => 'sqlite3',
  1079. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1080. ]);
  1081. $users = $connect->fetchAll('SELECT * FROM users');
  1082. $groups = $connect->fetchAll('SELECT * FROM groups ORDER BY group_id ASC');
  1083. foreach ($users as $k => $v) {
  1084. //clear password from array
  1085. unset($users[$k]['password']);
  1086. }
  1087. $all['users'] = $users;
  1088. $all['groups'] = $groups;
  1089. return $all;
  1090. } catch (Dibi\Exception $e) {
  1091. return false;
  1092. }
  1093. }
  1094. function usernameTaken($username,$email){
  1095. try {
  1096. $connect = new Dibi\Connection([
  1097. 'driver' => 'sqlite3',
  1098. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1099. ]);
  1100. $all = $connect->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE',$username,$email);
  1101. return ($all) ? true : false;
  1102. } catch (Dibi\Exception $e) {
  1103. return false;
  1104. }
  1105. }
  1106. function createUser($username,$password,$defaults,$email=null) {
  1107. $email = ($email) ? $email : random_ascii_string(10).'@placeholder.eml';
  1108. try {
  1109. if(!usernameTaken($username,$email)){
  1110. $createDB = new Dibi\Connection([
  1111. 'driver' => 'sqlite3',
  1112. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1113. ]);
  1114. $userInfo = [
  1115. 'username' => $username,
  1116. 'password' => password_hash($password, PASSWORD_BCRYPT),
  1117. 'email' => $email,
  1118. 'group' => $defaults['group'],
  1119. 'group_id' => $defaults['group_id'],
  1120. 'image' => gravatar($email),
  1121. 'register_date' => $GLOBALS['currentTime'],
  1122. ];
  1123. $createDB->query('INSERT INTO [users]', $userInfo);
  1124. return true;
  1125. }else{
  1126. return false;
  1127. }
  1128. } catch (Dibi\Exception $e) {
  1129. return false;
  1130. }
  1131. }
  1132. //Cookie Function
  1133. function coookie($type, $name, $value = '', $days = -1, $http = true){
  1134. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https"){
  1135. $Secure = true;
  1136. $HTTPOnly = true;
  1137. }elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  1138. $Secure = true;
  1139. $HTTPOnly = true;
  1140. } else {
  1141. $Secure = false;
  1142. $HTTPOnly = false;
  1143. }
  1144. if(!$http){ $HTTPOnly = false; }
  1145. $Path = '/';
  1146. $Domain = $_SERVER['HTTP_HOST'];
  1147. $Port = strpos($Domain, ':');
  1148. if ($Port !== false) $Domain = substr($Domain, 0, $Port);
  1149. $Port = strpos($Domain, ':');
  1150. $check = substr_count($Domain, '.');
  1151. if($check >= 3){
  1152. if(is_numeric($Domain[0])){
  1153. $Domain = '';
  1154. }else{
  1155. $Domain = '.'.explode('.',$Domain)[1].'.'.explode('.',$Domain)[2].'.'.explode('.',$Domain)[3];
  1156. }
  1157. }elseif($check == 2){
  1158. $Domain = '.'.explode('.',$Domain)[1].'.'.explode('.',$Domain)[2];
  1159. }elseif($check == 1){
  1160. $Domain = '.' . $Domain;
  1161. }else{
  1162. $Domain = '';
  1163. }
  1164. if($type = 'set'){
  1165. $_COOKIE[$name] = $value;
  1166. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  1167. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
  1168. . (empty($Path) ? '' : '; path=' . $Path)
  1169. . (empty($Domain) ? '' : '; domain=' . $Domain)
  1170. . (!$Secure ? '' : '; secure')
  1171. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  1172. }elseif($type = 'delete'){
  1173. unset($_COOKIE[$name]);
  1174. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  1175. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  1176. . (empty($Path) ? '' : '; path=' . $Path)
  1177. . (empty($Domain) ? '' : '; domain=' . $Domain)
  1178. . (!$Secure ? '' : '; secure')
  1179. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  1180. }
  1181. }
  1182. function validateToken($token,$global=false){
  1183. //validate script
  1184. $userInfo = jwtParse($token);
  1185. $validated = $userInfo ? true : false;
  1186. if($validated == true){
  1187. if($global == true){
  1188. $GLOBALS['organizrUser'] = array(
  1189. "token"=>$token,
  1190. "tokenDate"=>$userInfo['tokenDate'],
  1191. "tokenExpire"=>$userInfo['tokenExpire'],
  1192. "username"=>$userInfo['username'],
  1193. "group"=>$userInfo['group'],
  1194. "groupID"=>$userInfo['groupID'],
  1195. "email"=>$userInfo['email'],
  1196. "image"=>$userInfo['image'],
  1197. "loggedin"=>true
  1198. );
  1199. }
  1200. }else{
  1201. //delete cookie & reload page
  1202. coookie('delete','organizrToken');
  1203. $GLOBALS['organizrUser'] = false;
  1204. }
  1205. }
  1206. function logout(){
  1207. coookie('delete','organizrToken');
  1208. $GLOBALS['organizrUser'] = false;
  1209. return true;
  1210. }
  1211. function getOrganizrUserToken(){
  1212. if(isset($_COOKIE['organizrToken'])){
  1213. //get token form cookie and validate
  1214. validateToken($_COOKIE['organizrToken'],true);
  1215. }else{
  1216. $GLOBALS['organizrUser'] = array(
  1217. "token"=>null,
  1218. "tokenDate"=>null,
  1219. "tokenExpire"=>null,
  1220. "username"=>"Guest",
  1221. "group"=>getGuest()['group'],
  1222. "groupID"=>getGuest()['group_id'],
  1223. "email"=>null,
  1224. "image"=>getGuest()['image'],
  1225. "loggedin"=>false
  1226. );
  1227. }
  1228. }
  1229. function qualifyRequest($accessLevelNeeded){
  1230. if(getUserLevel() <= $accessLevelNeeded){
  1231. return true;
  1232. }else{
  1233. return false;
  1234. }
  1235. }
  1236. function getUserLevel(){
  1237. $requesterToken = isset(getallheaders()['Token']) ? getallheaders()['Token'] : false;
  1238. //check token or API key
  1239. //If API key, return 0 for admin
  1240. if(strlen($requesterToken) == 20 && $requesterToken == $GLOBALS['organizrAPI']){
  1241. //DO API CHECK
  1242. return 0;
  1243. }elseif(isset($GLOBALS['organizrUser'])){
  1244. return $GLOBALS['organizrUser']['groupID'];
  1245. }
  1246. //all else fails? return guest id
  1247. return 999;
  1248. }
  1249. function getOS(){
  1250. if(PHP_SHLIB_SUFFIX == "dll"){
  1251. return "win";
  1252. }else{
  1253. return "*nix";
  1254. }
  1255. }
  1256. function organizrStatus(){
  1257. $status = array();
  1258. $dependenciesActive = array();
  1259. $dependenciesInactive = array();
  1260. $extensions = array("PDO_SQLITE", "PDO", "SQLITE3", "zip", "cURL", "openssl", "simplexml", "json", "session");
  1261. $functions = array("hash", "fopen", "fsockopen", "fwrite", "fclose", "readfile");
  1262. foreach($extensions as $check){
  1263. if(extension_loaded($check)){
  1264. array_push($dependenciesActive,$check);
  1265. }else{
  1266. array_push($dependenciesInactive,$check);
  1267. }
  1268. }
  1269. foreach($functions as $check){
  1270. if(function_exists($check)){
  1271. array_push($dependenciesActive,$check);
  1272. }else{
  1273. array_push($dependenciesInactive,$check);
  1274. }
  1275. }
  1276. if(!file_exists('config'.DIRECTORY_SEPARATOR.'config.php')){
  1277. $status['status'] = "wizard";//wizard - ok for test
  1278. }
  1279. if(count($dependenciesInactive)>0 || !is_writable(dirname(__DIR__,2))){
  1280. $status['status'] = "dependencies";
  1281. }
  1282. $status['status'] = (!empty($status['status'])) ? $status['status'] : $status['status'] = "ok";
  1283. $status['writable'] = is_writable(dirname(__DIR__,2)) ? 'yes' : 'no';
  1284. $status['dependenciesActive'] = $dependenciesActive;
  1285. $status['dependenciesInactive'] = $dependenciesInactive;
  1286. $status['version'] = $GLOBALS['installedVersion'];
  1287. $status['os'] = getOS();
  1288. $status['php'] = phpversion();
  1289. return $status;
  1290. }
  1291. function allTabs(){
  1292. if(file_exists('config'.DIRECTORY_SEPARATOR.'config.php')){
  1293. try {
  1294. $connect = new Dibi\Connection([
  1295. 'driver' => 'sqlite3',
  1296. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1297. ]);
  1298. $all['tabs'] = $connect->fetchAll('SELECT * FROM tabs ORDER BY `order` ASC');
  1299. $all['categories'] = $connect->fetchAll('SELECT * FROM categories ORDER BY `order` ASC');
  1300. $all['groups'] = $connect->fetchAll('SELECT * FROM groups ORDER BY `group_id` ASC');
  1301. return $all;
  1302. } catch (Dibi\Exception $e) {
  1303. return false;
  1304. }
  1305. }
  1306. }
  1307. function loadTabs(){
  1308. if(file_exists('config'.DIRECTORY_SEPARATOR.'config.php')){
  1309. try {
  1310. $connect = new Dibi\Connection([
  1311. 'driver' => 'sqlite3',
  1312. 'database' => $GLOBALS['dbLocation'].$GLOBALS['dbName'],
  1313. ]);
  1314. $tabs = $connect->fetchAll('SELECT * FROM tabs WHERE `group_id` >= ? AND `enabled` = 1 ORDER BY `order` DESC',$GLOBALS['organizrUser']['groupID']);
  1315. $categories = $connect->fetchAll('SELECT * FROM categories ORDER BY `order` ASC');
  1316. $all['tabs'] = $tabs;
  1317. foreach ($tabs as $k => $v) {
  1318. $v['access_url'] = isset($v['url_local']) && $_SERVER['SERVER_ADDR'] == userIP() ? $v['url_local'] : $v['url'];
  1319. }
  1320. $count = array_map(function($element){
  1321. return $element['category_id'];
  1322. }, $tabs);
  1323. $count = (array_count_values($count));
  1324. foreach ($categories as $k => $v) {
  1325. $v['count'] = isset($count[$v['category_id']]) ? $count[$v['category_id']] : 0;
  1326. }
  1327. $all['categories'] = $categories;
  1328. return $all;
  1329. } catch (Dibi\Exception $e) {
  1330. return false;
  1331. }
  1332. }
  1333. }
  1334. if(!function_exists('getallheaders')){
  1335. function getallheaders(){
  1336. $headers = array ();
  1337. foreach ($_SERVER as $name => $value){
  1338. if (substr($name, 0, 5) == 'HTTP_'){
  1339. $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  1340. }
  1341. }
  1342. return $headers;
  1343. }
  1344. }
  1345. function writeLoginLog($username, $authType) {
  1346. if(file_exists($GLOBALS['organizrLoginLog'])) {
  1347. $getLog = str_replace("\r\ndate", "date", file_get_contents($GLOBALS['organizrLoginLog']));
  1348. $gotLog = json_decode($getLog, true);
  1349. }
  1350. $logEntryFirst = array('logType' => 'login_log', 'auth' => array(array('date' => date("Y-m-d H:i:s"), 'utc_date' => $GLOBALS['currentTime'], 'username' => $username, 'ip' => userIP(), 'auth_type' => $authType)));
  1351. $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $GLOBALS['currentTime'], 'username' => $username, 'ip' => userIP(), 'auth_type' => $authType);
  1352. if(isset($gotLog)) {
  1353. array_push($gotLog["auth"], $logEntry);
  1354. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
  1355. } else {
  1356. $writeFailLog = str_replace("date", "\r\ndate", json_encode($logEntryFirst));
  1357. }
  1358. file_put_contents($GLOBALS['organizrLoginLog'], $writeFailLog);
  1359. };
  1360. function writeLog($type='error', $message, $username=null) {
  1361. $username = ($username) ? $username : $GLOBALS['organizrUser']['username'];
  1362. if(file_exists($GLOBALS['organizrLog'])) {
  1363. $getLog = str_replace("\r\ndate", "date", file_get_contents($GLOBALS['organizrLog']));
  1364. $gotLog = json_decode($getLog, true);
  1365. }
  1366. $logEntryFirst = array('logType' => 'organizr_log', 'log_items' => array(array('date' => date("Y-m-d H:i:s"), 'utc_date' => $GLOBALS['currentTime'], 'type' => $type, 'username' => $username, 'ip' => userIP(), 'message' => $message)));
  1367. $logEntry = array('date' => date("Y-m-d H:i:s"), 'utc_date' => $GLOBALS['currentTime'], 'type' => $type, 'username' => $username, 'ip' => userIP(), 'message' => $message);
  1368. if(isset($gotLog)) {
  1369. array_push($gotLog["log_items"], $logEntry);
  1370. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotLog));
  1371. } else {
  1372. $writeFailLog = str_replace("date", "\r\ndate", json_encode($logEntryFirst));
  1373. }
  1374. file_put_contents($GLOBALS['organizrLog'], $writeFailLog);
  1375. };
  1376. function getLog($type,$reverse=true){
  1377. switch ($type) {
  1378. case 'login':
  1379. case 'loginLog':
  1380. $file = $GLOBALS['organizrLoginLog'];
  1381. $parent = 'auth';
  1382. break;
  1383. case 'org':
  1384. case 'organizrLog':
  1385. $file = $GLOBALS['organizrLog'];
  1386. $parent = 'log_items';
  1387. default:
  1388. break;
  1389. }
  1390. if(!file_exists($file)){
  1391. return false;
  1392. }
  1393. $getLog = str_replace("\r\ndate", "date", file_get_contents($file));
  1394. $gotLog = json_decode($getLog, true);
  1395. return ($reverse) ? array_reverse($gotLog[$parent]) : $gotLog[$parent];
  1396. }
  1397. function random_ascii_string($len){
  1398. $string = "";
  1399. $max = strlen($this->ascii)-1;
  1400. while($len-->0) { $string .= $this->ascii[mt_rand(0, $max)]; }
  1401. return $string;
  1402. }
  1403. function encrypt($password, $key = null) {
  1404. $key = (isset($GLOBALS['organizrHash'])) ? $GLOBALS['organizrHash'] : $key;
  1405. return openssl_encrypt($password, 'AES-256-CBC', $key, 0, fillString($key,16));
  1406. }
  1407. function decrypt($password, $key = null) {
  1408. $key = (isset($GLOBALS['organizrHash'])) ? $GLOBALS['organizrHash'] : $key;
  1409. return openssl_decrypt($password, 'AES-256-CBC', $key, 0, fillString($key,16));
  1410. }
  1411. function fillString($string, $length){
  1412. $filler = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*';
  1413. if(strlen($string) < $length){
  1414. $diff = $length - strlen($string);
  1415. $filler = substr($filler,0,$diff);
  1416. return $string.$filler;
  1417. }elseif(strlen($string) > $length){
  1418. return substr($string,0,$length);
  1419. }else{
  1420. return $string;
  1421. }
  1422. return $diff;
  1423. }
  1424. function userIP() {
  1425. if (isset($_SERVER['HTTP_CLIENT_IP']))
  1426. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  1427. else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  1428. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  1429. else if(isset($_SERVER['HTTP_X_FORWARDED']))
  1430. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  1431. else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
  1432. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  1433. else if(isset($_SERVER['HTTP_FORWARDED']))
  1434. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  1435. else if(isset($_SERVER['REMOTE_ADDR']))
  1436. $ipaddress = $_SERVER['REMOTE_ADDR'];
  1437. else
  1438. $ipaddress = 'UNKNOWN';
  1439. if (strpos($ipaddress, ',') !== false) {
  1440. list($first, $last) = explode(",", $ipaddress);
  1441. return $first;
  1442. }else{
  1443. return $ipaddress;
  1444. }
  1445. }
  1446. function arrayIP($string){
  1447. if (strpos($string, ',') !== false) {
  1448. $result = explode(",", $string);
  1449. }else{
  1450. $result = array($string);
  1451. }
  1452. foreach($result as &$ip){
  1453. $ip = is_numeric(substr($ip, 0, 1)) ? $ip : gethostbyname($ip);
  1454. }
  1455. return $result;
  1456. }
  1457. function auth(){
  1458. $debug = false; //CAREFUL WHEN SETTING TO TRUE AS THIS OPENS AUTH UP
  1459. $ban = isset($_GET['ban']) ? strtoupper($_GET['ban']) : "";
  1460. $whitelist = isset($_GET['whitelist']) ? $_GET['whitelist'] : false;
  1461. $blacklist = isset($_GET['blacklist']) ? $_GET['blacklist'] : false;
  1462. $group = isset($_GET['group']) ? $_GET['group'] : 0;
  1463. $currentIP = userIP();
  1464. $currentUser = $GLOBALS['organizrUser']['username'];
  1465. if ($whitelist) {
  1466. if(in_array($currentIP, arrayIP($whitelist))) {
  1467. !$debug ? exit(http_response_code(200)) : die("$currentIP Whitelist Authorized");
  1468. }
  1469. }
  1470. if ($blacklist) {
  1471. if(in_array($currentIP, arrayIP($blacklist))) {
  1472. !$debug ? exit(http_response_code(401)) : die("$currentIP Blacklisted");
  1473. }
  1474. }
  1475. if($group !== null){
  1476. if(qualifyRequest($group)){
  1477. !$debug ? exit(http_response_code(200)) : die("$currentUser on $currentIP Authorized");
  1478. }else{
  1479. !$debug ? exit(http_response_code(401)) : die("$currentUser on $currentIP Not Authorized");
  1480. }
  1481. }else{
  1482. !$debug ? exit(http_response_code(401)) : die("Not Authorized Due To No Parameters Set");
  1483. }
  1484. }